zenko 0.2.1-beta.1 → 0.2.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function ne(e){let n=new Set,t=new Set,r=[],o=i=>{if(n.has(i)||t.has(i))return;t.add(i);let s=e[i],a=Z(s);for(let p of a)e[p]&&o(p);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function Z(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=O(r.$ref);n.push(o);return}if(Array.isArray(r))r.forEach(t);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&n.push(O(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function O(e){return e.split("/").pop()||"Unknown"}function P(e){if(!e)return!1;let n=e.at(0);return n===void 0||!/[a-zA-Z_$]/.test(n)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return P(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function A(e){return e.charAt(0).toUpperCase()+e.slice(1)}function G(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&te(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!te(r.errors))&&(n.usesOperationErrors=!0),n}function U(e,n,t){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=n==="package"?'"zenko"':`"${t}"`;return`import type { ${r.join(", ")} } from ${o};`}function te(e){return!!(e&&Object.keys(e).length>0)}var C={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function v(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in C)return t;return n[0]||""}function je(e){let n=_optionalChain([e, 'access', _2 => _2.toLowerCase, 'call', _3 => _3(), 'access', _4 => _4.split, 'call', _5 => _5(";"), 'access', _6 => _6[0], 'optionalAccess', _7 => _7.trim, 'call', _8 => _8()]);return n?!!(n.startsWith("text/")||n==="application/xml"||n.startsWith("application/")&&n.endsWith("+xml")):!1}function E(e,n){if(!n||!je(e)||n.$ref)return n;let t=n.nullable===!0?{nullable:!0}:{};return n.enum?{type:"string",enum:n.enum,...t}:{type:"string",...t}}function H(e,n){if(e){if(e.$ref){let t=O(e.$ref),r=_optionalChain([n, 'access', _9 => _9.components, 'optionalAccess', _10 => _10.parameters, 'optionalAccess', _11 => _11[t]]);if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function N(e){let n=new Map;for(let[,t]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}for(let[,t]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}return n}function re(e,n){let t=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return _nullishCoalesce(r.get(p), () => ([]));let u=Z(p);return r.set(p,u),u},i=N(n);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=_optionalChain([u, 'access', _12 => _12.requestBody, 'optionalAccess', _13 => _13.content, 'optionalAccess', _14 => _14["application/json"], 'optionalAccess', _15 => _15.schema]);if(_optionalChain([d, 'optionalAccess', _16 => _16.$ref])){let c=O(d.$ref);t.add(c)}else if(d){let c=o(d);for(let y of c)_optionalChain([n, 'access', _17 => _17.components, 'optionalAccess', _18 => _18.schemas, 'optionalAccess', _19 => _19[y]])&&t.add(y)}let g=u.responses||{};for(let[,c]of Object.entries(g)){let y=_optionalChain([c, 'optionalAccess', _20 => _20.content]);if(!y)continue;let f=v(y),h=_optionalChain([y, 'access', _21 => _21[f], 'optionalAccess', _22 => _22.schema]),$=E(f,h);if(_optionalChain([$, 'optionalAccess', _23 => _23.$ref])){let w=O($.$ref);t.add(w)}else if($){let w=o($);for(let x of w)_optionalChain([n, 'access', _24 => _24.components, 'optionalAccess', _25 => _25.schemas, 'optionalAccess', _26 => _26[x]])&&t.add(x)}}for(let c of p.queryParams){if(_optionalChain([c, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.$ref])){let y=O(c.schema.$ref);t.add(y)}if(_optionalChain([c, 'access', _29 => _29.schema, 'optionalAccess', _30 => _30.items, 'optionalAccess', _31 => _31.$ref])){let y=O(c.schema.items.$ref);t.add(y)}}for(let c of p.requestHeaders||[]){if(_optionalChain([c, 'access', _32 => _32.schema, 'optionalAccess', _33 => _33.$ref])){let y=O(c.schema.$ref);t.add(y)}if(_optionalChain([c, 'access', _34 => _34.schema, 'optionalAccess', _35 => _35.items, 'optionalAccess', _36 => _36.$ref])){let y=O(c.schema.items.$ref);t.add(y)}}let l=u.parameters||[];for(let c of l){let y=H(c,n);if(_optionalChain([y, 'optionalAccess', _37 => _37.schema, 'optionalAccess', _38 => _38.$ref])){let f=O(y.schema.$ref);t.add(f)}if(_optionalChain([y, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.items, 'optionalAccess', _41 => _41.$ref])){let f=O(y.schema.items.$ref);t.add(f)}}}let s=new Set,a=Array.from(t);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=_optionalChain([n, 'access', _42 => _42.components, 'optionalAccess', _43 => _43.schemas, 'optionalAccess', _44 => _44[p]]);if(!u)continue;let d=o(u);for(let g of d)_optionalChain([n, 'access', _45 => _45.components, 'optionalAccess', _46 => _46.schemas, 'optionalAccess', _47 => _47[g]])&&!s.has(g)&&(t.add(g),a.push(g))}return t}function Ne(e,n){return n===!0?!0:Array.isArray(n)?n.includes(e):!1}function B(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function M(e,n,t,r,o,i){if(t.has(e))return"";if(t.add(e),n.enum){let s=n.enum.map(a=>`"${a}"`).join(", ");if(Ne(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
2
+ export const ${e} = z.enum(${e}Known).or(
3
+ z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
4
+ );`}return`export const ${e} = z.enum([${s}]);`}if(n.allOf&&Array.isArray(n.allOf)){let s=_(n),a=s.map(l=>R(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>J(l,i))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${g};`}if(n.type==="object"||n.properties)return`export const ${e} = ${ae(n,r,o,i,e)};`;if(n.type==="array"){let s=_nullishCoalesce(n.items, () => ({type:"unknown"})),a=R(s,r,o,i,e),p=r.strictNumeric||n.minItems!==void 0||n.maxItems!==void 0||n.uniqueItems===!0,u=ue(n,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${R(n,r,o,i,e,e)};`}function oe(e,n,t,r,o){let i=e.map(s=>R(s,n,t,r,o));return i.length===0?"z.unknown()":i.length===1?_nullishCoalesce(i[0], () => ("z.unknown()")):`z.union([${i.join(", ")}])`}function V(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Me(e,n){if(!_optionalChain([e, 'optionalAccess', _48 => _48.$ref]))return e;let t=O(e.$ref);return _nullishCoalesce(_optionalChain([n, 'optionalAccess', _49 => _49[t]]), () => (e))}function ie(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>_optionalChain([e, 'optionalAccess', _50 => _50[t]])!==void 0)}function _(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,ie(t)&&n.push(t),n}function I(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=O(e.$ref);if((_optionalChain([r, 'optionalAccess', _51 => _51.get, 'call', _52 => _52(i)])||i)===n)return!0;let a=_optionalChain([t, 'optionalAccess', _53 => _53[i]]);if(a)return I(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>I(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>I(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>I(i,n,t,r,o)):e.not?I(e.not,n,t,r,o):e.items?I(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>I(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?I(e.additionalProperties,n,t,r,o):!1}function J(e,n){let t=Me(e,n);return t?t.allOf&&Array.isArray(t.allOf)?_(t).every(o=>J(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function Ce(e){let n=new Map;if(!_optionalChain([e, 'optionalAccess', _54 => _54.mapping]))return n;for(let[t,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=O(r),i=n.get(o);if(i){i.values.includes(t)||i.values.push(t);continue}n.set(o,{ref:r,values:[t]})}return n}function D(e,n,t,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=O(e.$ref),a=_optionalChain([t, 'optionalAccess', _55 => _55[s]]);return a?D(a,n,t,r):[]}let o=[],i=_optionalChain([e, 'access', _56 => _56.properties, 'optionalAccess', _57 => _57[n]]);if(i){let s=i.const;s!==void 0&&V(s)?o.push(s):Array.isArray(i.enum)&&_optionalChain([i, 'access', _58 => _58.enum, 'optionalAccess', _59 => _59.length])===1&&V(_optionalChain([i, 'access', _60 => _60.enum, 'optionalAccess', _61 => _61[0]]))&&o.push(_optionalChain([i, 'access', _62 => _62.enum, 'optionalAccess', _63 => _63[0]]))}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...D(s,n,t,r));return Array.from(new Set(o))}function se(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function He(e,n,t,r){let o=new Set;for(let a of e)_optionalChain([a, 'optionalAccess', _64 => _64.$ref])&&o.add(O(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(_optionalChain([a, 'optionalAccess', _65 => _65.$ref])){let d=O(a.$ref),g=t.get(d);_optionalChain([g, 'optionalAccess', _66 => _66.values, 'access', _67 => _67.length])&&p.push(...g.values),p.push(...D(a,n,r))}else p.push(...D(a,n,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(se(a,n,d))}for(let[a,p]of t.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(se(u,n,d))}return{schemas:i,hasUnmapped:s}}function De(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=He(e,n,_nullishCoalesce(s, () => (new Map)),o),u=a.map(d=>R(d,t,r,o,i));return u.length===0?"z.unknown()":u.length===1?_nullishCoalesce(u[0], () => ("z.unknown()")):p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${u.join(", ")}])`}function R(e,n,t,r,o,i){if(e.$ref){let s=O(e.$ref),a=_optionalChain([t, 'optionalAccess', _68 => _68.get, 'call', _69 => _69(s)])||s;return o&&(a===o||I(_optionalChain([r, 'optionalAccess', _70 => _70[s]]),o,r,t))?`z.lazy(() => ${a})`:a}if(e.const!==void 0&&V(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ie(a)?R(a,n,t,r,o):"z.any()";if(_optionalChain([s, 'optionalAccess', _71 => _71.type])==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=R(s,n,t,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=_(e),a=s.map(l=>R(l,n,t,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return _nullishCoalesce(a[0], () => ("z.object({})"));let u=s.every(l=>J(l,r))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${g}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(_optionalChain([e, 'access', _72 => _72.discriminator, 'optionalAccess', _73 => _73.propertyName])){let s=Ce(e.discriminator);return De(e.oneOf,e.discriminator.propertyName,n,t,r,o,s)}return oe(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return oe(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return ae(e,n,t,r,o);switch(e.type){case"string":return Le(e,n,i);case"boolean":return"z.boolean()";case"array":{let s=_nullishCoalesce(e.items, () => ({type:"unknown"})),a=R(s,n,t,r,o),p=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return ue(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return pe(e,n);case"integer":return Ge(e,n);default:return"z.unknown()"}}function Fe(e,n){if(!e||!n)return new Set;let t=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=_optionalChain([r, 'access', _74 => _74.discriminator, 'optionalAccess', _75 => _75.propertyName]);if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>_optionalChain([u, 'optionalAccess', _76 => _76.$ref])&&O(u.$ref)===n),p=Object.values(_nullishCoalesce(_optionalChain([r, 'access', _77 => _77.discriminator, 'optionalAccess', _78 => _78.mapping]), () => ({}))).some(u=>typeof u=="string"&&O(u)===n);(s||p)&&t.add(o)}return t}function ae(e,n,t,r,o){let i=[],s=Fe(r,o),a=new Set(_nullishCoalesce(e.required, () => ([])));for(let[d,g]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),c=R(g,n,t,r,o),y=B(c,n.optionalType),f=n.optionalType!=="nullable"?Ze(y,g):y,h=l?c:f;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
5
+ ${i.join(`
6
+ `)}
7
+ })`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=R(e.additionalProperties,n,t,r,o);return`${p}.catchall(${u})`}function Le(e,n,t){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return n.dateTimeOffset===!0||Array.isArray(n.dateTimeOffset)&&t!==void 0&&n.dateTimeOffset.includes(t)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Ze(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function pe(e,n){let t="z.number()";return n.strictNumeric&&(t=Ve(e,t),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(t+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),t}function Ge(e,n){let t=pe(e,n);return t+=".int()",t}function ue(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ue(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ue(e){return _optionalChain([e, 'optionalAccess', _79 => _79.$ref])?!1:new Set(["string","number","integer","boolean"]).has(_optionalChain([e, 'optionalAccess', _80 => _80.type]))}function Ve(e,n){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?n+=`.gt(${e.minimum})`:n+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(n+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?n+=`.lt(${e.maximum})`:n+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(n+=`.lt(${e.exclusiveMaximum})`),n}var Be={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function fe(e){if(e==="default")return"defaultError";let n=e.trim(),t=Be[n];if(t)return t;if(/^\d{3}$/.test(n))return`status${n}`;let r=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function F(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function Oe(e,n){let t=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=de(r),u=le(s,n),{successResponse:d,errors:g}=ye(s,s.operationId,n),l=ce(o,s,e),c=me(l),y=ge(l),f=he(s,e);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:c,errors:g,security:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=r,u=de(p),d=le(s,n),{successResponse:g,errors:l}=ye(s,s.operationId,n),c=ce(o,s,e),y=me(c),f=ge(c),h=he(s,e);t.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:f,requestType:d,responseType:g,requestHeaders:y,errors:l,security:h})}return t}function ce(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=H(s,t);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function de(e){let n=[],t=e.match(/{([^}]+)}/g);if(t)for(let r of t){let o=r.slice(1,-1);n.push({name:o,type:"string"})}return n}function le(e,n){let t=_e(e);if(!t)return;if(t.$ref){let o=O(t.$ref);return _optionalChain([n, 'optionalAccess', _81 => _81.get, 'call', _82 => _82(o)])||o}return`${A(T(e.operationId))}Request`}function _e(e){let n=_optionalChain([e, 'optionalAccess', _83 => _83.requestBody, 'optionalAccess', _84 => _84.content]);if(!n||Object.keys(n).length===0)return;let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of t){let o=_optionalChain([n, 'access', _85 => _85[r], 'optionalAccess', _86 => _86.schema]);if(o)return o}}function ye(e,n,t){let r=_nullishCoalesce(e.responses, () => ({})),o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=_optionalChain([u, 'optionalAccess', _87 => _87.content]);if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):F(p)&&i.push({code:p,schema:"undefined"});continue}let g=v(d),l=_optionalChain([d, 'access', _88 => _88[g], 'optionalAccess', _89 => _89.schema]),c=E(g,l);if(!c){let y=We(g,p);y&&(F(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(F(p)){i.push({code:p,schema:c});continue}/^2\d\d$/.test(p)&&o.set(p,c)}let s=Je(o,n,t),a=Qe(i,n,t);return{successResponse:s,errors:a}}function Je(e,n,t){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:Q(s,`${A(T(n))}Response`,t)}let[,o]=_nullishCoalesce(e.entries().next().value, () => ([]));if(o)return typeof o=="string"?o:Q(o,`${A(T(n))}Response`,t)}function Qe(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=fe(o),a=Q(i,`${A(T(n))}${A(s)}`,t);r[s]=a}return r}function Q(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=O(e.$ref);return _optionalChain([t, 'optionalAccess', _90 => _90.get, 'call', _91 => _91(r)])||r}if(e.type==="array"&&_optionalChain([e, 'access', _92 => _92.items, 'optionalAccess', _93 => _93.$ref])){let r=O(e.items.$ref);return`z.array(${_optionalChain([t, 'optionalAccess', _94 => _94.get, 'call', _95 => _95(r)])||r})`}return e.allOf&&Array.isArray(e.allOf),n}function me(e){let n=[];for(let t of _nullishCoalesce(e, () => ([])))t.in==="header"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function ge(e){let n=[];for(let t of _nullishCoalesce(e, () => ([])))t.in==="query"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function he(e,n){let t=e.security;if(Array.isArray(t))return t.length===0?[]:t;if(Array.isArray(n.security)&&n.security.length>0)return n.security}function $e(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function We(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in C?C[e]:"unknown"}function Se(e,n){let t=new Map,r=N(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=Ke(a);if(!p)continue;let u=`${A(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(u,p)}}return t}function Ke(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=_optionalChain([e, 'access', _96 => _96[t], 'optionalAccess', _97 => _97.schema]);if(r)return r}}function Te(e,n){let t=new Map,r=N(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=v(u),g=_optionalChain([u, 'access', _98 => _98[d], 'optionalAccess', _99 => _99.schema]),l=E(d,g);if(!l)continue;let c=`${A(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&t.set(c,l)}}return t}function we(e,n,t,r,o){let i=Se(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function xe(e,n,t,r,o){let i=Te(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function be(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
8
+ `)}function Ye(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:_nullishCoalesce(e.open, () => (!1)),prefix:_nullishCoalesce(e.unknownPrefix, () => ("Unknown:"))}}function Xe(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=n,u=nn(n.types),d=Ye(p),g={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};t.push('import { z } from "zod";');let l=new Map;if(_optionalChain([e, 'access', _100 => _100.components, 'optionalAccess', _101 => _101.schemas]))for(let f of Object.keys(e.components.schemas))l.set(f,T(f));let c=Oe(e,l);if(a&&a.length>0){let f=new Set(a);c=c.filter(h=>f.has(h.operationId))}if(tn(t,u,c),t.push(""),_optionalChain([e, 'access', _102 => _102.components, 'optionalAccess', _103 => _103.schemas])){t.push("// Generated Zod Schemas"),t.push("");let f=a&&a.length>0?new Set(re(c,e)):new Set(Object.keys(e.components.schemas)),h=ne(e.components.schemas).filter($=>f.has($));for(let $ of h){let w=e.components.schemas[$],x=l.get($);t.push(M(x,w,r,g,l,e.components.schemas)),t.push(""),t.push(`export type ${x} = z.infer<typeof ${x}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of c){let $=f.pathParams.map(m=>m.name).length>0,w=f.queryParams.length>0,x=T(f.operationId);if(!$&&!w){t.push(` ${S(x)}: () => "${f.path}",`);continue}let q=m=>{if(P(m))return m;let k=T(m);return P(k)||(k=`_${k}`),k},z=[],j=[];for(let m of f.pathParams)z.push(P(m.name)?m.name:`${S(m.name)}: ${q(m.name)}`),j.push(`${S(m.name)}: string`);for(let m of f.queryParams)z.push(P(m.name)?m.name:`${S(m.name)}: ${q(m.name)}`),j.push(`${S(m.name)}${m.required?"":"?"}: ${pn(m)}`);let Ee=!$&&w&&f.queryParams.every(m=>!m.required),K=`${z.length?`{ ${z.join(", ")} }`:"{}"}: { ${j.join(", ")} }${Ee?" = {}":""}`,Y=f.path.replace(/{([^}]+)}/g,(m,k)=>`\${${q(k)}}`);if(!w){t.push(` ${S(x)}: (${K}) => \`${Y}\`,`);continue}t.push(` ${S(x)}: (${K}) => {`),t.push(" const params = new URLSearchParams()");for(let m of f.queryParams){let k=P(m.name)?m.name:q(T(m.name)),L=_nullishCoalesce(m.schema, () => ({}));if(_optionalChain([L, 'optionalAccess', _104 => _104.type])==="array"){let ee=Pe(_nullishCoalesce(L.items, () => ({})),"value");m.required?(t.push(` for (const value of ${k}) {`),t.push(` params.append("${m.name}", ${ee})`),t.push(" }")):(t.push(` if (${k} !== undefined) {`),t.push(` for (const value of ${k}) {`),t.push(` params.append("${m.name}", ${ee})`),t.push(" }"),t.push(" }"));continue}let X=Pe(L,k);m.required?t.push(` params.set("${m.name}", ${X})`):(t.push(` if (${k} !== undefined) {`),t.push(` params.set("${m.name}", ${X})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${Y}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: z.object({}),`);continue}let $=f.requestHeaders.map(w=>{let x=an(w),q=w.required?x:B(x,g.optionalType);return` ${S(w.name)}: ${q},`}).join(`
9
+ `);t.push(` ${S(h)}: z.object({`),t.push($),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: () => ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}t.push(` ${S(h)}: (params: z.input<${P(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),t.push(` return ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),t.push(" },")}if(t.push("} as const;"),t.push(""),_optionalChain([e, 'access', _105 => _105.components, 'optionalAccess', _106 => _106.securitySchemes])&&Object.keys(e.components.securitySchemes).length>0){t.push("// Security Schemes"),t.push("export const securitySchemes = {");for(let[f,h]of Object.entries(e.components.securitySchemes)){let $=h;t.push(` ${S(f)}: {`),t.push(` type: ${JSON.stringify($.type)},`),$.type==="http"?(t.push(` scheme: ${JSON.stringify(String($.scheme).toLowerCase())},`),$.bearerFormat&&t.push(` bearerFormat: ${JSON.stringify($.bearerFormat)},`)):$.type==="apiKey"?(t.push(` name: ${JSON.stringify($.name)},`),t.push(` in: ${JSON.stringify($.in)},`)):$.type==="oauth2"?t.push(` flows: ${JSON.stringify($.flows)},`):$.type==="openIdConnect"&&t.push(` openIdConnectUrl: ${JSON.stringify($.openIdConnectUrl)},`),t.push(" },")}t.push("} as const;"),t.push("")}we(t,c,e,l,g),xe(t,c,e,l,g),rn(t,c,u),t.push("// Operation Objects");for(let f of c){let h=T(f.operationId),$=u.emit?`: ${Re(h,u.operationTypeSuffix)}`:"";if(t.push(`export const ${h}${$} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${h},`),ke(t,"request",f.requestType),ke(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${h},`),f.security!==void 0)if(f.security.length===0)t.push(" security: [],");else{let w=f.security.map(x=>`{ ${Object.entries(x).map(([z,j])=>`${S(z)}: ${JSON.stringify(j)}`).join(", ")} }`);t.push(` security: [${w.join(", ")}],`)}f.errors&&Ae(f.errors)&&en(t,"errors",f.errors),t.push("} as const;"),t.push("")}let y={output:t.join(`
10
+ `)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:be()}),y}function it(e,n={}){return Xe(e,n).output}function ke(e,n,t){t&&e.push(` ${n}: ${t},`)}function en(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Ae(e){return!!(e&&Object.keys(e).length>0)}function nn(e){let n=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _107 => _107.operationTypeSuffix]), () => ("Operation"));if(n!==""&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n))throw new Error(`Invalid operationTypeSuffix "${n}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _108 => _108.emit]), () => (!0)),helpers:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _109 => _109.helpers]), () => ("package")),helpersOutput:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _110 => _110.helpersOutput]), () => ("./zenko-types")),treeShake:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _111 => _111.treeShake]), () => (!0)),optionalType:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _112 => _112.optionalType]), () => ("optional")),operationTypeSuffix:n}}function Re(e,n){return`${A(e)}${n}`}function tn(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=G(t),o=U(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(n.treeShake){let r=G(t),o=U(r,"file",n.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${n.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function rn(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=Re(o,t.operationTypeSuffix),s=_optionalChain([r, 'access', _113 => _113.requestHeaders, 'optionalAccess', _114 => _114.length])?P(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",a=W(r.requestType),p=W(r.responseType),u=on(r.errors),d=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(l=>`{ ${Object.entries(l).map(([y,f])=>`readonly ${S(y)}: readonly ${JSON.stringify(f)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${i} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${P(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${a},`),e.push(` ${p},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${d}`),e.push(">;"),e.push("")}}}function on(e){return!e||!Ae(e)?"OperationErrors":`OperationErrors<${sn(e)}>`}function sn(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=ze(o);return`${i}: ${s}`}).join("; ")} }`}var Ie=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),qe=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function W(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(Ie.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${W(t[1])}>`:qe.test(n)?`typeof ${n}`:n}function ze(e){if(!e)return"unknown";let n=e.trim();if(Ie.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${ze(t[1])}>`:qe.test(n)?`typeof ${n}`:n}function an(e){let n=_nullishCoalesce(e.schema, () => ({}));switch(n.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=_nullishCoalesce(n.items, () => ({type:"string"}));return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function pn(e){return ve(e.schema)}function ve(e){if(!e)return"string";if(e.type==="array")return`Array<${ve(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Pe(e,n){if(!e)return`String(${n})`;switch(e.type){case"integer":case"number":return`String(${n})`;case"boolean":return`${n} ? "true" : "false"`;default:return`String(${n})`}}exports.a = Xe; exports.b = it;
11
+ //# sourceMappingURL=chunk-TDMGTOOL.cjs.map
@@ -0,0 +1,11 @@
1
+ function te(e){let n=new Set,t=new Set,r=[],o=i=>{if(n.has(i)||t.has(i))return;t.add(i);let s=e[i],a=G(s);for(let p of a)e[p]&&o(p);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function G(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=O(r.$ref);n.push(o);return}if(Array.isArray(r))r.forEach(t);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&n.push(O(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function O(e){return e.split("/").pop()||"Unknown"}function A(e){if(!e)return!1;let n=e.at(0);return n===void 0||!/[a-zA-Z_$]/.test(n)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return A(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function R(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&re(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!re(r.errors))&&(n.usesOperationErrors=!0),n}function V(e,n,t){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=n==="package"?'"zenko"':`"${t}"`;return`import type { ${r.join(", ")} } from ${o};`}function re(e){return!!(e&&Object.keys(e).length>0)}var H={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function E(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in H)return t;return n[0]||""}function Ne(e){let n=e.toLowerCase().split(";")[0]?.trim();return n?!!(n.startsWith("text/")||n==="application/xml"||n.startsWith("application/")&&n.endsWith("+xml")):!1}function j(e,n){if(!n||!Ne(e)||n.$ref)return n;let t=n.nullable===!0?{nullable:!0}:{};return n.enum?{type:"string",enum:n.enum,...t}:{type:"string",...t}}function D(e,n){if(e){if(e.$ref){let t=O(e.$ref),r=n.components?.parameters?.[t];if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function M(e){let n=new Map;for(let[,t]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}for(let[,t]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}return n}function oe(e,n){let t=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return r.get(p)??[];let u=G(p);return r.set(p,u),u},i=M(n);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=u.requestBody?.content?.["application/json"]?.schema;if(d?.$ref){let c=O(d.$ref);t.add(c)}else if(d){let c=o(d);for(let y of c)n.components?.schemas?.[y]&&t.add(y)}let g=u.responses||{};for(let[,c]of Object.entries(g)){let y=c?.content;if(!y)continue;let f=E(y),h=y[f]?.schema,$=j(f,h);if($?.$ref){let w=O($.$ref);t.add(w)}else if($){let w=o($);for(let x of w)n.components?.schemas?.[x]&&t.add(x)}}for(let c of p.queryParams){if(c.schema?.$ref){let y=O(c.schema.$ref);t.add(y)}if(c.schema?.items?.$ref){let y=O(c.schema.items.$ref);t.add(y)}}for(let c of p.requestHeaders||[]){if(c.schema?.$ref){let y=O(c.schema.$ref);t.add(y)}if(c.schema?.items?.$ref){let y=O(c.schema.items.$ref);t.add(y)}}let l=u.parameters||[];for(let c of l){let y=D(c,n);if(y?.schema?.$ref){let f=O(y.schema.$ref);t.add(f)}if(y?.schema?.items?.$ref){let f=O(y.schema.items.$ref);t.add(f)}}}let s=new Set,a=Array.from(t);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=n.components?.schemas?.[p];if(!u)continue;let d=o(u);for(let g of d)n.components?.schemas?.[g]&&!s.has(g)&&(t.add(g),a.push(g))}return t}function Me(e,n){return n===!0?!0:Array.isArray(n)?n.includes(e):!1}function _(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function C(e,n,t,r,o,i){if(t.has(e))return"";if(t.add(e),n.enum){let s=n.enum.map(a=>`"${a}"`).join(", ");if(Me(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
2
+ export const ${e} = z.enum(${e}Known).or(
3
+ z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
4
+ );`}return`export const ${e} = z.enum([${s}]);`}if(n.allOf&&Array.isArray(n.allOf)){let s=J(n),a=s.map(l=>I(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>Q(l,i))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${g};`}if(n.type==="object"||n.properties)return`export const ${e} = ${pe(n,r,o,i,e)};`;if(n.type==="array"){let s=n.items??{type:"unknown"},a=I(s,r,o,i,e),p=r.strictNumeric||n.minItems!==void 0||n.maxItems!==void 0||n.uniqueItems===!0,u=fe(n,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${I(n,r,o,i,e,e)};`}function se(e,n,t,r,o){let i=e.map(s=>I(s,n,t,r,o));return i.length===0?"z.unknown()":i.length===1?i[0]??"z.unknown()":`z.union([${i.join(", ")}])`}function B(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ce(e,n){if(!e?.$ref)return e;let t=O(e.$ref);return n?.[t]??e}function ae(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>e?.[t]!==void 0)}function J(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,ae(t)&&n.push(t),n}function q(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=O(e.$ref);if((r?.get(i)||i)===n)return!0;let a=t?.[i];if(a)return q(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>q(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>q(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>q(i,n,t,r,o)):e.not?q(e.not,n,t,r,o):e.items?q(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>q(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?q(e.additionalProperties,n,t,r,o):!1}function Q(e,n){let t=Ce(e,n);return t?t.allOf&&Array.isArray(t.allOf)?J(t).every(o=>Q(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function He(e){let n=new Map;if(!e?.mapping)return n;for(let[t,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=O(r),i=n.get(o);if(i){i.values.includes(t)||i.values.push(t);continue}n.set(o,{ref:r,values:[t]})}return n}function F(e,n,t,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=O(e.$ref),a=t?.[s];return a?F(a,n,t,r):[]}let o=[],i=e.properties?.[n];if(i){let s=i.const;s!==void 0&&B(s)?o.push(s):Array.isArray(i.enum)&&i.enum?.length===1&&B(i.enum?.[0])&&o.push(i.enum?.[0])}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...F(s,n,t,r));return Array.from(new Set(o))}function ie(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function De(e,n,t,r){let o=new Set;for(let a of e)a?.$ref&&o.add(O(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(a?.$ref){let d=O(a.$ref),g=t.get(d);g?.values.length&&p.push(...g.values),p.push(...F(a,n,r))}else p.push(...F(a,n,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(ie(a,n,d))}for(let[a,p]of t.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(ie(u,n,d))}return{schemas:i,hasUnmapped:s}}function Fe(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=De(e,n,s??new Map,o),u=a.map(d=>I(d,t,r,o,i));return u.length===0?"z.unknown()":u.length===1?u[0]??"z.unknown()":p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${u.join(", ")}])`}function I(e,n,t,r,o,i){if(e.$ref){let s=O(e.$ref),a=t?.get(s)||s;return o&&(a===o||q(r?.[s],o,r,t))?`z.lazy(() => ${a})`:a}if(e.const!==void 0&&B(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ae(a)?I(a,n,t,r,o):"z.any()";if(s?.type==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=I(s,n,t,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=J(e),a=s.map(l=>I(l,n,t,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return a[0]??"z.object({})";let u=s.every(l=>Q(l,r))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${g}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let s=He(e.discriminator);return Fe(e.oneOf,e.discriminator.propertyName,n,t,r,o,s)}return se(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return se(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return pe(e,n,t,r,o);switch(e.type){case"string":return Ze(e,n,i);case"boolean":return"z.boolean()";case"array":{let s=e.items??{type:"unknown"},a=I(s,n,t,r,o),p=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return fe(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return ue(e,n);case"integer":return Ue(e,n);default:return"z.unknown()"}}function Le(e,n){if(!e||!n)return new Set;let t=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=r.discriminator?.propertyName;if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>u?.$ref&&O(u.$ref)===n),p=Object.values(r.discriminator?.mapping??{}).some(u=>typeof u=="string"&&O(u)===n);(s||p)&&t.add(o)}return t}function pe(e,n,t,r,o){let i=[],s=Le(r,o),a=new Set(e.required??[]);for(let[d,g]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),c=I(g,n,t,r,o),y=_(c,n.optionalType),f=n.optionalType!=="nullable"?Ge(y,g):y,h=l?c:f;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
5
+ ${i.join(`
6
+ `)}
7
+ })`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=I(e.additionalProperties,n,t,r,o);return`${p}.catchall(${u})`}function Ze(e,n,t){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return n.dateTimeOffset===!0||Array.isArray(n.dateTimeOffset)&&t!==void 0&&n.dateTimeOffset.includes(t)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Ge(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function ue(e,n){let t="z.number()";return n.strictNumeric&&(t=Be(e,t),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(t+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),t}function Ue(e,n){let t=ue(e,n);return t+=".int()",t}function fe(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ve(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ve(e){return e?.$ref?!1:new Set(["string","number","integer","boolean"]).has(e?.type)}function Be(e,n){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?n+=`.gt(${e.minimum})`:n+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(n+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?n+=`.lt(${e.maximum})`:n+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(n+=`.lt(${e.exclusiveMaximum})`),n}var _e={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function ce(e){if(e==="default")return"defaultError";let n=e.trim(),t=_e[n];if(t)return t;if(/^\d{3}$/.test(n))return`status${n}`;let r=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function L(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function Se(e,n){let t=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=le(r),u=ye(s,n),{successResponse:d,errors:g}=me(s,s.operationId,n),l=de(o,s,e),c=ge(l),y=he(l),f=$e(s,e);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:c,errors:g,security:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=r,u=le(p),d=ye(s,n),{successResponse:g,errors:l}=me(s,s.operationId,n),c=de(o,s,e),y=ge(c),f=he(c),h=$e(s,e);t.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:f,requestType:d,responseType:g,requestHeaders:y,errors:l,security:h})}return t}function de(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=D(s,t);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function le(e){let n=[],t=e.match(/{([^}]+)}/g);if(t)for(let r of t){let o=r.slice(1,-1);n.push({name:o,type:"string"})}return n}function ye(e,n){let t=Je(e);if(!t)return;if(t.$ref){let o=O(t.$ref);return n?.get(o)||o}return`${R(T(e.operationId))}Request`}function Je(e){let n=e?.requestBody?.content;if(!n||Object.keys(n).length===0)return;let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of t){let o=n[r]?.schema;if(o)return o}}function me(e,n,t){let r=e.responses??{},o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=u?.content;if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):L(p)&&i.push({code:p,schema:"undefined"});continue}let g=E(d),l=d[g]?.schema,c=j(g,l);if(!c){let y=Ke(g,p);y&&(L(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(L(p)){i.push({code:p,schema:c});continue}/^2\d\d$/.test(p)&&o.set(p,c)}let s=Qe(o,n,t),a=We(i,n,t);return{successResponse:s,errors:a}}function Qe(e,n,t){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:W(s,`${R(T(n))}Response`,t)}let[,o]=e.entries().next().value??[];if(o)return typeof o=="string"?o:W(o,`${R(T(n))}Response`,t)}function We(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=ce(o),a=W(i,`${R(T(n))}${R(s)}`,t);r[s]=a}return r}function W(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=O(e.$ref);return t?.get(r)||r}if(e.type==="array"&&e.items?.$ref){let r=O(e.items.$ref);return`z.array(${t?.get(r)||r})`}return e.allOf&&Array.isArray(e.allOf),n}function ge(e){let n=[];for(let t of e??[])t.in==="header"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function he(e){let n=[];for(let t of e??[])t.in==="query"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function $e(e,n){let t=e.security;if(Array.isArray(t))return t.length===0?[]:t;if(Array.isArray(n.security)&&n.security.length>0)return n.security}function Oe(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function Ke(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in H?H[e]:"unknown"}function Te(e,n){let t=new Map,r=M(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=Ye(a);if(!p)continue;let u=`${R(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(u,p)}}return t}function Ye(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=e[t]?.schema;if(r)return r}}function we(e,n){let t=new Map,r=M(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=E(u),g=u[d]?.schema,l=j(d,g);if(!l)continue;let c=`${R(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&t.set(c,l)}}return t}function xe(e,n,t,r,o){let i=Te(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function be(e,n,t,r,o){let i=we(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ke(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
8
+ `)}function Xe(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:e.open??!1,prefix:e.unknownPrefix??"Unknown:"}}function en(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=n,u=tn(n.types),d=Xe(p),g={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};t.push('import { z } from "zod";');let l=new Map;if(e.components?.schemas)for(let f of Object.keys(e.components.schemas))l.set(f,T(f));let c=Se(e,l);if(a&&a.length>0){let f=new Set(a);c=c.filter(h=>f.has(h.operationId))}if(rn(t,u,c),t.push(""),e.components?.schemas){t.push("// Generated Zod Schemas"),t.push("");let f=a&&a.length>0?new Set(oe(c,e)):new Set(Object.keys(e.components.schemas)),h=te(e.components.schemas).filter($=>f.has($));for(let $ of h){let w=e.components.schemas[$],x=l.get($);t.push(C(x,w,r,g,l,e.components.schemas)),t.push(""),t.push(`export type ${x} = z.infer<typeof ${x}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of c){let $=f.pathParams.map(m=>m.name).length>0,w=f.queryParams.length>0,x=T(f.operationId);if(!$&&!w){t.push(` ${S(x)}: () => "${f.path}",`);continue}let z=m=>{if(A(m))return m;let P=T(m);return A(P)||(P=`_${P}`),P},v=[],N=[];for(let m of f.pathParams)v.push(A(m.name)?m.name:`${S(m.name)}: ${z(m.name)}`),N.push(`${S(m.name)}: string`);for(let m of f.queryParams)v.push(A(m.name)?m.name:`${S(m.name)}: ${z(m.name)}`),N.push(`${S(m.name)}${m.required?"":"?"}: ${un(m)}`);let je=!$&&w&&f.queryParams.every(m=>!m.required),Y=`${v.length?`{ ${v.join(", ")} }`:"{}"}: { ${N.join(", ")} }${je?" = {}":""}`,X=f.path.replace(/{([^}]+)}/g,(m,P)=>`\${${z(P)}}`);if(!w){t.push(` ${S(x)}: (${Y}) => \`${X}\`,`);continue}t.push(` ${S(x)}: (${Y}) => {`),t.push(" const params = new URLSearchParams()");for(let m of f.queryParams){let P=A(m.name)?m.name:z(T(m.name)),Z=m.schema??{};if(Z?.type==="array"){let ne=Ae(Z.items??{},"value");m.required?(t.push(` for (const value of ${P}) {`),t.push(` params.append("${m.name}", ${ne})`),t.push(" }")):(t.push(` if (${P} !== undefined) {`),t.push(` for (const value of ${P}) {`),t.push(` params.append("${m.name}", ${ne})`),t.push(" }"),t.push(" }"));continue}let ee=Ae(Z,P);m.required?t.push(` params.set("${m.name}", ${ee})`):(t.push(` if (${P} !== undefined) {`),t.push(` params.set("${m.name}", ${ee})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${X}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: z.object({}),`);continue}let $=f.requestHeaders.map(w=>{let x=pn(w),z=w.required?x:_(x,g.optionalType);return` ${S(w.name)}: ${z},`}).join(`
9
+ `);t.push(` ${S(h)}: z.object({`),t.push($),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: () => ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}t.push(` ${S(h)}: (params: z.input<${A(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),t.push(` return ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),t.push(" },")}if(t.push("} as const;"),t.push(""),e.components?.securitySchemes&&Object.keys(e.components.securitySchemes).length>0){t.push("// Security Schemes"),t.push("export const securitySchemes = {");for(let[f,h]of Object.entries(e.components.securitySchemes)){let $=h;t.push(` ${S(f)}: {`),t.push(` type: ${JSON.stringify($.type)},`),$.type==="http"?(t.push(` scheme: ${JSON.stringify(String($.scheme).toLowerCase())},`),$.bearerFormat&&t.push(` bearerFormat: ${JSON.stringify($.bearerFormat)},`)):$.type==="apiKey"?(t.push(` name: ${JSON.stringify($.name)},`),t.push(` in: ${JSON.stringify($.in)},`)):$.type==="oauth2"?t.push(` flows: ${JSON.stringify($.flows)},`):$.type==="openIdConnect"&&t.push(` openIdConnectUrl: ${JSON.stringify($.openIdConnectUrl)},`),t.push(" },")}t.push("} as const;"),t.push("")}xe(t,c,e,l,g),be(t,c,e,l,g),on(t,c,u),t.push("// Operation Objects");for(let f of c){let h=T(f.operationId),$=u.emit?`: ${Ie(h,u.operationTypeSuffix)}`:"";if(t.push(`export const ${h}${$} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${h},`),Pe(t,"request",f.requestType),Pe(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${h},`),f.security!==void 0)if(f.security.length===0)t.push(" security: [],");else{let w=f.security.map(x=>`{ ${Object.entries(x).map(([v,N])=>`${S(v)}: ${JSON.stringify(N)}`).join(", ")} }`);t.push(` security: [${w.join(", ")}],`)}f.errors&&Re(f.errors)&&nn(t,"errors",f.errors),t.push("} as const;"),t.push("")}let y={output:t.join(`
10
+ `)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:ke()}),y}function at(e,n={}){return en(e,n).output}function Pe(e,n,t){t&&e.push(` ${n}: ${t},`)}function nn(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Re(e){return!!(e&&Object.keys(e).length>0)}function tn(e){let n=e?.operationTypeSuffix??"Operation";if(n!==""&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n))throw new Error(`Invalid operationTypeSuffix "${n}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:e?.emit??!0,helpers:e?.helpers??"package",helpersOutput:e?.helpersOutput??"./zenko-types",treeShake:e?.treeShake??!0,optionalType:e?.optionalType??"optional",operationTypeSuffix:n}}function Ie(e,n){return`${R(e)}${n}`}function rn(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=U(t),o=V(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(n.treeShake){let r=U(t),o=V(r,"file",n.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${n.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function on(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=Ie(o,t.operationTypeSuffix),s=r.requestHeaders?.length?A(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",a=K(r.requestType),p=K(r.responseType),u=sn(r.errors),d=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(l=>`{ ${Object.entries(l).map(([y,f])=>`readonly ${S(y)}: readonly ${JSON.stringify(f)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${i} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${A(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${a},`),e.push(` ${p},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${d}`),e.push(">;"),e.push("")}}}function sn(e){return!e||!Re(e)?"OperationErrors":`OperationErrors<${an(e)}>`}function an(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=ve(o);return`${i}: ${s}`}).join("; ")} }`}var qe=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),ze=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function K(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(qe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${K(t[1])}>`:ze.test(n)?`typeof ${n}`:n}function ve(e){if(!e)return"unknown";let n=e.trim();if(qe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${ve(t[1])}>`:ze.test(n)?`typeof ${n}`:n}function pn(e){let n=e.schema??{};switch(n.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=n.items??{type:"string"};return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function un(e){return Ee(e.schema)}function Ee(e){if(!e)return"string";if(e.type==="array")return`Array<${Ee(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Ae(e,n){if(!e)return`String(${n})`;switch(e.type){case"integer":case"number":return`String(${n})`;case"boolean":return`${n} ? "true" : "false"`;default:return`String(${n})`}}export{en as a,at as b};
11
+ //# sourceMappingURL=chunk-ZZITTAAE.mjs.map
package/dist/cli.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- "use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkJCJ5ZIGIcjs = require('./chunk-JCJ5ZIGI.cjs');var _fs = require('fs'); var i = _interopRequireWildcard(_fs);var _path = require('path'); var n = _interopRequireWildcard(_path);var _url = require('url');async function E(){let t=process.argv.slice(2),e=O(t);if(e.showHelp||!e.configPath&&e.positional.length===0){y(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){y(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){y(),process.exit(1);return}await b({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function O(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function y(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),console.log(" zenko --config <config-file> [options]"),console.log(""),console.log("Options:"),console.log(" -h, --help Show this help message"),console.log(" --strict-dates Use ISO datetime parsing (can be set per config entry)"),console.log(" --strict-numeric Preserve numeric min/max bounds (can be set per config entry)"),console.log(" -c, --config Path to config file (JSON, YAML, or JS module)"),console.log(""),console.log("Config file format:"),console.log(' {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await T(s);A(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=C(c.input,r),h=C(c.output,r),m=N(f,c.types);await b({inputFile:g,outputFile:h,strictDates:_nullishCoalesce(c.strictDates, () => (t.strictDates)),strictNumeric:_nullishCoalesce(c.strictNumeric, () => (t.strictNumeric)),dateTimeOffset:c.dateTimeOffset,typesConfig:m,operationIds:c.operationIds,openEnums:c.openEnums})}}async function T(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, t).href)));return _nullishCoalesce(_nullishCoalesce(o.default, () => (o.config)), () => (o))}function A(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function C(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function N(t,e){if(!(!t&&!e))return{...t,...e}}async function b(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,dateTimeOffset:f,typesConfig:c,operationIds:g,openEnums:h}=t,m=n.resolve(e),p=n.resolve(s),l=P(m),a=_chunkJCJ5ZIGIcjs.a.call(void 0, l,{strictDates:o,strictNumeric:r,dateTimeOffset:f,types:c,operationIds:g,openEnums:h});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),d=n.resolve(p),F=n.resolve(u);if(d===F){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${d}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}E().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
2
+ "use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkTDMGTOOLcjs = require('./chunk-TDMGTOOL.cjs');var _fs = require('fs'); var i = _interopRequireWildcard(_fs);var _path = require('path'); var n = _interopRequireWildcard(_path);var _url = require('url');async function E(){let t=process.argv.slice(2),e=O(t);if(e.showHelp||!e.configPath&&e.positional.length===0){y(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){y(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){y(),process.exit(1);return}await b({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function O(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function y(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),console.log(" zenko --config <config-file> [options]"),console.log(""),console.log("Options:"),console.log(" -h, --help Show this help message"),console.log(" --strict-dates Use ISO datetime parsing (can be set per config entry)"),console.log(" --strict-numeric Preserve numeric min/max bounds (can be set per config entry)"),console.log(" -c, --config Path to config file (JSON, YAML, or JS module)"),console.log(""),console.log("Config file format:"),console.log(' {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await T(s);A(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=C(c.input,r),h=C(c.output,r),m=N(f,c.types);await b({inputFile:g,outputFile:h,strictDates:_nullishCoalesce(c.strictDates, () => (t.strictDates)),strictNumeric:_nullishCoalesce(c.strictNumeric, () => (t.strictNumeric)),dateTimeOffset:c.dateTimeOffset,typesConfig:m,operationIds:c.operationIds,openEnums:c.openEnums})}}async function T(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, t).href)));return _nullishCoalesce(_nullishCoalesce(o.default, () => (o.config)), () => (o))}function A(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function C(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function N(t,e){if(!(!t&&!e))return{...t,...e}}async function b(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,dateTimeOffset:f,typesConfig:c,operationIds:g,openEnums:h}=t,m=n.resolve(e),p=n.resolve(s),l=P(m),a=_chunkTDMGTOOLcjs.a.call(void 0, l,{strictDates:o,strictNumeric:r,dateTimeOffset:f,types:c,operationIds:g,openEnums:h});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),d=n.resolve(p),F=n.resolve(u);if(d===F){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${d}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}E().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
3
3
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as w}from"./chunk-63YFJ2QY.mjs";import*as i from"fs";import*as n from"path";import{pathToFileURL as S}from"url";async function E(){let t=process.argv.slice(2),e=O(t);if(e.showHelp||!e.configPath&&e.positional.length===0){y(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){y(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){y(),process.exit(1);return}await b({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function O(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function y(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),console.log(" zenko --config <config-file> [options]"),console.log(""),console.log("Options:"),console.log(" -h, --help Show this help message"),console.log(" --strict-dates Use ISO datetime parsing (can be set per config entry)"),console.log(" --strict-numeric Preserve numeric min/max bounds (can be set per config entry)"),console.log(" -c, --config Path to config file (JSON, YAML, or JS module)"),console.log(""),console.log("Config file format:"),console.log(' {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await T(s);A(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=C(c.input,r),h=C(c.output,r),m=N(f,c.types);await b({inputFile:g,outputFile:h,strictDates:c.strictDates??t.strictDates,strictNumeric:c.strictNumeric??t.strictNumeric,dateTimeOffset:c.dateTimeOffset,typesConfig:m,operationIds:c.operationIds,openEnums:c.openEnums})}}async function T(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await import(S(t).href);return o.default??o.config??o}function A(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function C(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function N(t,e){if(!(!t&&!e))return{...t,...e}}async function b(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,dateTimeOffset:f,typesConfig:c,operationIds:g,openEnums:h}=t,m=n.resolve(e),p=n.resolve(s),l=P(m),a=w(l,{strictDates:o,strictNumeric:r,dateTimeOffset:f,types:c,operationIds:g,openEnums:h});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),d=n.resolve(p),F=n.resolve(u);if(d===F){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${d}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}E().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
2
+ import{a as w}from"./chunk-ZZITTAAE.mjs";import*as i from"fs";import*as n from"path";import{pathToFileURL as S}from"url";async function E(){let t=process.argv.slice(2),e=O(t);if(e.showHelp||!e.configPath&&e.positional.length===0){y(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){y(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){y(),process.exit(1);return}await b({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function O(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function y(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),console.log(" zenko --config <config-file> [options]"),console.log(""),console.log("Options:"),console.log(" -h, --help Show this help message"),console.log(" --strict-dates Use ISO datetime parsing (can be set per config entry)"),console.log(" --strict-numeric Preserve numeric min/max bounds (can be set per config entry)"),console.log(" -c, --config Path to config file (JSON, YAML, or JS module)"),console.log(""),console.log("Config file format:"),console.log(' {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await T(s);A(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=C(c.input,r),h=C(c.output,r),m=N(f,c.types);await b({inputFile:g,outputFile:h,strictDates:c.strictDates??t.strictDates,strictNumeric:c.strictNumeric??t.strictNumeric,dateTimeOffset:c.dateTimeOffset,typesConfig:m,operationIds:c.operationIds,openEnums:c.openEnums})}}async function T(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await import(S(t).href);return o.default??o.config??o}function A(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function C(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function N(t,e){if(!(!t&&!e))return{...t,...e}}async function b(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,dateTimeOffset:f,typesConfig:c,operationIds:g,openEnums:h}=t,m=n.resolve(e),p=n.resolve(s),l=P(m),a=w(l,{strictDates:o,strictNumeric:r,dateTimeOffset:f,types:c,operationIds:g,openEnums:h});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),d=n.resolve(p),F=n.resolve(u);if(d===F){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${d}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}E().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
3
3
  //# sourceMappingURL=cli.mjs.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJCJ5ZIGIcjs = require('./chunk-JCJ5ZIGI.cjs');exports.generate = _chunkJCJ5ZIGIcjs.b;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkTDMGTOOLcjs = require('./chunk-TDMGTOOL.cjs');exports.generate = _chunkTDMGTOOLcjs.b;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -17,6 +17,7 @@ type TypesConfig = {
17
17
  helpersOutput?: string;
18
18
  treeShake?: boolean;
19
19
  optionalType?: "optional" | "nullable" | "nullish";
20
+ operationTypeSuffix?: string;
20
21
  };
21
22
  type EnumConfig = {
22
23
  open?: boolean | string[];
package/dist/index.d.ts CHANGED
@@ -17,6 +17,7 @@ type TypesConfig = {
17
17
  helpersOutput?: string;
18
18
  treeShake?: boolean;
19
19
  optionalType?: "optional" | "nullable" | "nullish";
20
+ operationTypeSuffix?: string;
20
21
  };
21
22
  type EnumConfig = {
22
23
  open?: boolean | string[];
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{b as e}from"./chunk-63YFJ2QY.mjs";export{e as generate};
1
+ import{b as e}from"./chunk-ZZITTAAE.mjs";export{e as generate};
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zenko",
3
- "version": "0.2.1-beta.1",
3
+ "version": "0.2.2-beta.1",
4
4
  "description": "Generate TypeScript types and path functions from OpenAPI specs",
5
5
  "keywords": [
6
6
  "api",
@@ -63,7 +63,7 @@
63
63
  },
64
64
  "dependencies": {},
65
65
  "devDependencies": {
66
- "@types/bun": "1.3.8",
66
+ "@types/bun": "1.3.9",
67
67
  "@zenko/specs": "workspace:*",
68
68
  "tsup": "8.5.1",
69
69
  "typescript": "5.9.3"
@@ -1,11 +0,0 @@
1
- function te(e){let t=new Set,n=new Set,r=[],o=i=>{if(t.has(i)||n.has(i))return;n.add(i);let s=e[i],a=Z(s);for(let p of a)e[p]&&o(p);n.delete(i),t.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function Z(e){let t=[],n=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=$(r.$ref);t.push(o);return}if(Array.isArray(r))r.forEach(n);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&t.push($(o));Object.values(r).forEach(n)}}};return n(e),[...new Set(t)]}function $(e){return e.split("/").pop()||"Unknown"}function A(e){if(!e)return!1;let t=e.at(0);return t===void 0||!/[a-zA-Z_$]/.test(t)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return A(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(t,n)=>n.toUpperCase()).replace(/-+$/,"")}function R(e){return e.charAt(0).toUpperCase()+e.slice(1)}function V(e){let t={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(t.usesOperationDefinition=!0);for(let n of e)n.errors&&re(n.errors)&&(t.usesOperationErrors=!0);return e.length>0&&!t.usesOperationErrors&&e.some(r=>!r.errors||!re(r.errors))&&(t.usesOperationErrors=!0),t}function U(e,t,n){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=t==="package"?'"zenko"':`"${n}"`;return`import type { ${r.join(", ")} } from ${o};`}function re(e){return!!(e&&Object.keys(e).length>0)}var H={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function v(e){let t=Object.keys(e);if(t.includes("application/json"))return"application/json";for(let n of t)if(n in H)return n;return t[0]||""}function je(e){let t=e.toLowerCase().split(";")[0]?.trim();return t?!!(t.startsWith("text/")||t==="application/xml"||t.startsWith("application/")&&t.endsWith("+xml")):!1}function j(e,t){if(!t||!je(e)||t.$ref)return t;let n=t.nullable===!0?{nullable:!0}:{};return t.enum?{type:"string",enum:t.enum,...n}:{type:"string",...n}}function D(e,t){if(e){if(e.$ref){let n=$(e.$ref),r=t.components?.parameters?.[n];if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function M(e){let t=new Map;for(let[,n]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(n)){let o=r;o.operationId&&t.set(o.operationId,o)}for(let[,n]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(n)){let o=r;o.operationId&&t.set(o.operationId,o)}return t}function oe(e,t){let n=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return r.get(p)??[];let u=Z(p);return r.set(p,u),u},i=M(t);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=u.requestBody?.content?.["application/json"]?.schema;if(d?.$ref){let f=$(d.$ref);n.add(f)}else if(d){let f=o(d);for(let y of f)t.components?.schemas?.[y]&&n.add(y)}let m=u.responses||{};for(let[,f]of Object.entries(m)){let y=f?.content;if(!y)continue;let c=v(y),h=y[c]?.schema,O=j(c,h);if(O?.$ref){let w=$(O.$ref);n.add(w)}else if(O){let w=o(O);for(let b of w)t.components?.schemas?.[b]&&n.add(b)}}for(let f of p.queryParams){if(f.schema?.$ref){let y=$(f.schema.$ref);n.add(y)}if(f.schema?.items?.$ref){let y=$(f.schema.items.$ref);n.add(y)}}for(let f of p.requestHeaders||[]){if(f.schema?.$ref){let y=$(f.schema.$ref);n.add(y)}if(f.schema?.items?.$ref){let y=$(f.schema.items.$ref);n.add(y)}}let l=u.parameters||[];for(let f of l){let y=D(f,t);if(y?.schema?.$ref){let c=$(y.schema.$ref);n.add(c)}if(y?.schema?.items?.$ref){let c=$(y.schema.items.$ref);n.add(c)}}}let s=new Set,a=Array.from(n);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=t.components?.schemas?.[p];if(!u)continue;let d=o(u);for(let m of d)t.components?.schemas?.[m]&&!s.has(m)&&(n.add(m),a.push(m))}return n}function Ne(e,t){return t===!0?!0:Array.isArray(t)?t.includes(e):!1}function _(e,t){switch(t){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function C(e,t,n,r,o,i){if(n.has(e))return"";if(n.add(e),t.enum){let s=t.enum.map(a=>`"${a}"`).join(", ");if(Ne(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
2
- export const ${e} = z.enum(${e}Known).or(
3
- z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
4
- );`}return`export const ${e} = z.enum([${s}]);`}if(t.allOf&&Array.isArray(t.allOf)){let s=J(t),a=s.map(l=>I(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>Q(l,i))?"merge":"and",d=a[0],m=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${m};`}if(t.type==="object"||t.properties)return`export const ${e} = ${pe(t,r,o,i,e)};`;if(t.type==="array"){let s=t.items??{type:"unknown"},a=I(s,r,o,i,e),p=r.strictNumeric||t.minItems!==void 0||t.maxItems!==void 0||t.uniqueItems===!0,u=ce(t,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${I(t,r,o,i,e,e)};`}function se(e,t,n,r,o){let i=e.map(s=>I(s,t,n,r,o));return i.length===0?"z.unknown()":i.length===1?i[0]??"z.unknown()":`z.union([${i.join(", ")}])`}function B(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Me(e,t){if(!e?.$ref)return e;let n=$(e.$ref);return t?.[n]??e}function ae(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(n=>e?.[n]!==void 0)}function J(e){let t=Array.isArray(e.allOf)?[...e.allOf]:[],n={...e};return delete n.allOf,ae(n)&&t.push(n),t}function q(e,t,n,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=$(e.$ref);if((r?.get(i)||i)===t)return!0;let a=n?.[i];if(a)return q(a,t,n,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>q(i,t,n,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>q(i,t,n,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>q(i,t,n,r,o)):e.not?q(e.not,t,n,r,o):e.items?q(e.items,t,n,r,o):e.properties?Object.values(e.properties).some(i=>q(i,t,n,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?q(e.additionalProperties,t,n,r,o):!1}function Q(e,t){let n=Me(e,t);return n?n.allOf&&Array.isArray(n.allOf)?J(n).every(o=>Q(o,t)):n.type==="object"||n.properties!==void 0||n.additionalProperties!==void 0:!1}function Ce(e){let t=new Map;if(!e?.mapping)return t;for(let[n,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=$(r),i=t.get(o);if(i){i.values.includes(n)||i.values.push(n);continue}t.set(o,{ref:r,values:[n]})}return t}function F(e,t,n,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=$(e.$ref),a=n?.[s];return a?F(a,t,n,r):[]}let o=[],i=e.properties?.[t];if(i){let s=i.const;s!==void 0&&B(s)?o.push(s):Array.isArray(i.enum)&&i.enum?.length===1&&B(i.enum?.[0])&&o.push(i.enum?.[0])}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...F(s,t,n,r));return Array.from(new Set(o))}function ie(e,t,n){return{allOf:[e,{type:"object",properties:{[t]:{const:n}},required:[t]}]}}function He(e,t,n,r){let o=new Set;for(let a of e)a?.$ref&&o.add($(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(a?.$ref){let d=$(a.$ref),m=n.get(d);m?.values.length&&p.push(...m.values),p.push(...F(a,t,r))}else p.push(...F(a,t,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(ie(a,t,d))}for(let[a,p]of n.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(ie(u,t,d))}return{schemas:i,hasUnmapped:s}}function De(e,t,n,r,o,i,s){let{schemas:a,hasUnmapped:p}=He(e,t,s??new Map,o),u=a.map(d=>I(d,n,r,o,i));return u.length===0?"z.unknown()":u.length===1?u[0]??"z.unknown()":p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(t)}, [${u.join(", ")}])`}function I(e,t,n,r,o,i){if(e.$ref){let s=$(e.$ref),a=n?.get(s)||s;return o&&(a===o||q(r?.[s],o,r,n))?`z.lazy(() => ${a})`:a}if(e.const!==void 0&&B(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ae(a)?I(a,t,n,r,o):"z.any()";if(s?.type==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=I(s,t,n,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=J(e),a=s.map(l=>I(l,t,n,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return a[0]??"z.object({})";let u=s.every(l=>Q(l,r))?"merge":"and",d=a[0],m=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${m}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let s=Ce(e.discriminator);return De(e.oneOf,e.discriminator.propertyName,t,n,r,o,s)}return se(e.oneOf,t,n,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return se(e.anyOf,t,n,r,o);if(e.type==="object"||e.properties||e.allOf)return pe(e,t,n,r,o);switch(e.type){case"string":return Le(e,t,i);case"boolean":return"z.boolean()";case"array":{let s=e.items??{type:"unknown"},a=I(s,t,n,r,o),p=t.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return ce(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return ue(e,t);case"integer":return Ze(e,t);default:return"z.unknown()"}}function Fe(e,t){if(!e||!t)return new Set;let n=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=r.discriminator?.propertyName;if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>u?.$ref&&$(u.$ref)===t),p=Object.values(r.discriminator?.mapping??{}).some(u=>typeof u=="string"&&$(u)===t);(s||p)&&n.add(o)}return n}function pe(e,t,n,r,o){let i=[],s=Fe(r,o),a=new Set(e.required??[]);for(let[d,m]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),f=I(m,t,n,r,o),y=_(f,t.optionalType),c=t.optionalType!=="nullable"?Ge(y,m):y,h=l?f:c;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
5
- ${i.join(`
6
- `)}
7
- })`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=I(e.additionalProperties,t,n,r,o);return`${p}.catchall(${u})`}function Le(e,t,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(t.strictDates)switch(e.format){case"date-time":return t.dateTimeOffset===!0||Array.isArray(t.dateTimeOffset)&&n!==void 0&&t.dateTimeOffset.includes(n)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(t.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Ge(e,t){return!t||t.default===void 0?e:`${e}.default(${JSON.stringify(t.default)})`}function ue(e,t){let n="z.number()";return t.strictNumeric&&(n=Ue(e,n),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(n+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),n}function Ze(e,t){let n=ue(e,t);return n+=".int()",n}function ce(e,t,n,r){return r&&(typeof e.minItems=="number"&&(t+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(t+=`.max(${e.maxItems})`),e.uniqueItems&&Ve(n)&&(t+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),t}function Ve(e){return e?.$ref?!1:new Set(["string","number","integer","boolean"]).has(e?.type)}function Ue(e,t){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?t+=`.gt(${e.minimum})`:t+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(t+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?t+=`.lt(${e.maximum})`:t+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(t+=`.lt(${e.exclusiveMaximum})`),t}var Be={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function fe(e){if(e==="default")return"defaultError";let t=e.trim(),n=Be[t];if(n)return n;if(/^\d{3}$/.test(t))return`status${t}`;let r=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function L(e){if(e==="default")return!0;let t=Number(e);return Number.isInteger(t)?t>=400:!1}function Se(e,t){let n=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=le(r),u=ye(s,t),{successResponse:d,errors:m}=me(s,s.operationId,t),l=de(o,s,e),f=ge(l),y=he(l),c=Oe(s,e);n.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:f,errors:m,security:c})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=r,u=le(p),d=ye(s,t),{successResponse:m,errors:l}=me(s,s.operationId,t),f=de(o,s,e),y=ge(f),c=he(f),h=Oe(s,e);n.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:c,requestType:d,responseType:m,requestHeaders:y,errors:l,security:h})}return n}function de(e,t,n){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=D(s,n);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(t.parameters),Array.from(r.values())}function le(e){let t=[],n=e.match(/{([^}]+)}/g);if(n)for(let r of n){let o=r.slice(1,-1);t.push({name:o,type:"string"})}return t}function ye(e,t){let n=_e(e);if(!n)return;if(n.$ref){let o=$(n.$ref);return t?.get(o)||o}return`${R(T(e.operationId))}Request`}function _e(e){let t=e?.requestBody?.content;if(!t||Object.keys(t).length===0)return;let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of n){let o=t[r]?.schema;if(o)return o}}function me(e,t,n){let r=e.responses??{},o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=u?.content;if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):L(p)&&i.push({code:p,schema:"undefined"});continue}let m=v(d),l=d[m]?.schema,f=j(m,l);if(!f){let y=We(m,p);y&&(L(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(L(p)){i.push({code:p,schema:f});continue}/^2\d\d$/.test(p)&&o.set(p,f)}let s=Je(o,t,n),a=Qe(i,t,n);return{successResponse:s,errors:a}}function Je(e,t,n){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:W(s,`${R(T(t))}Response`,n)}let[,o]=e.entries().next().value??[];if(o)return typeof o=="string"?o:W(o,`${R(T(t))}Response`,n)}function Qe(e=[],t,n){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=fe(o),a=W(i,`${R(T(t))}${R(s)}`,n);r[s]=a}return r}function W(e,t,n){if(typeof e=="string")return e;if(e.$ref){let r=$(e.$ref);return n?.get(r)||r}if(e.type==="array"&&e.items?.$ref){let r=$(e.items.$ref);return`z.array(${n?.get(r)||r})`}return e.allOf&&Array.isArray(e.allOf),t}function ge(e){let t=[];for(let n of e??[])n.in==="header"&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function he(e){let t=[];for(let n of e??[])n.in==="query"&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function Oe(e,t){let n=e.security;if(Array.isArray(n))return n.length===0?[]:n;if(Array.isArray(t.security)&&t.security.length>0)return t.security}function $e(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function We(e,t){return t==="204"||/^3\d\d$/.test(t)?"undefined":e in H?H[e]:"unknown"}function Te(e,t){let n=new Map,r=M(t);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=Ke(a);if(!p)continue;let u=`${R(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&n.set(u,p)}}return n}function Ke(e){let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let n of t){let r=e[n]?.schema;if(r)return r}}function we(e,t){let n=new Map,r=M(t);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=v(u),m=u[d]?.schema,l=j(d,m);if(!l)continue;let f=`${R(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&n.set(f,l)}}return n}function be(e,t,n,r,o){let i=Te(t,n);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function xe(e,t,n,r,o){let i=we(t,n);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ke(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
8
- `)}function Ye(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:e.open??!1,prefix:e.unknownPrefix??"Unknown:"}}function Xe(e,t={}){let n=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=t,u=nn(t.types),d=Ye(p),m={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};n.push('import { z } from "zod";');let l=new Map;if(e.components?.schemas)for(let c of Object.keys(e.components.schemas))l.set(c,T(c));let f=Se(e,l);if(a&&a.length>0){let c=new Set(a);f=f.filter(h=>c.has(h.operationId))}if(tn(n,u,f),n.push(""),e.components?.schemas){n.push("// Generated Zod Schemas"),n.push("");let c=a&&a.length>0?new Set(oe(f,e)):new Set(Object.keys(e.components.schemas)),h=te(e.components.schemas).filter(O=>c.has(O));for(let O of h){let w=e.components.schemas[O],b=l.get(O);n.push(C(b,w,r,m,l,e.components.schemas)),n.push(""),n.push(`export type ${b} = z.infer<typeof ${b}>;`),n.push("")}}n.push("// Path Functions"),n.push("export const paths = {");for(let c of f){let O=c.pathParams.map(g=>g.name).length>0,w=c.queryParams.length>0,b=T(c.operationId);if(!O&&!w){n.push(` ${S(b)}: () => "${c.path}",`);continue}let z=g=>{if(A(g))return g;let P=T(g);return A(P)||(P=`_${P}`),P},E=[],N=[];for(let g of c.pathParams)E.push(A(g.name)?g.name:`${S(g.name)}: ${z(g.name)}`),N.push(`${S(g.name)}: string`);for(let g of c.queryParams)E.push(A(g.name)?g.name:`${S(g.name)}: ${z(g.name)}`),N.push(`${S(g.name)}${g.required?"":"?"}: ${pn(g)}`);let ve=!O&&w&&c.queryParams.every(g=>!g.required),Y=`${E.length?`{ ${E.join(", ")} }`:"{}"}: { ${N.join(", ")} }${ve?" = {}":""}`,X=c.path.replace(/{([^}]+)}/g,(g,P)=>`\${${z(P)}}`);if(!w){n.push(` ${S(b)}: (${Y}) => \`${X}\`,`);continue}n.push(` ${S(b)}: (${Y}) => {`),n.push(" const params = new URLSearchParams()");for(let g of c.queryParams){let P=A(g.name)?g.name:z(T(g.name)),G=g.schema??{};if(G?.type==="array"){let ne=Ae(G.items??{},"value");g.required?(n.push(` for (const value of ${P}) {`),n.push(` params.append("${g.name}", ${ne})`),n.push(" }")):(n.push(` if (${P} !== undefined) {`),n.push(` for (const value of ${P}) {`),n.push(` params.append("${g.name}", ${ne})`),n.push(" }"),n.push(" }"));continue}let ee=Ae(G,P);g.required?n.push(` params.set("${g.name}", ${ee})`):(n.push(` if (${P} !== undefined) {`),n.push(` params.set("${g.name}", ${ee})`),n.push(" }"))}n.push(" const _searchParams = params.toString()"),n.push(` return \`${X}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),n.push(" },")}n.push("} as const;"),n.push(""),n.push("// Header Schemas"),n.push("export const headerSchemas = {");for(let c of f){let h=T(c.operationId);if(!c.requestHeaders||c.requestHeaders.length===0){n.push(` ${S(h)}: z.object({}),`);continue}let O=c.requestHeaders.map(w=>{let b=an(w),z=w.required?b:_(b,m.optionalType);return` ${S(w.name)}: ${z},`}).join(`
9
- `);n.push(` ${S(h)}: z.object({`),n.push(O),n.push(" }),")}n.push("} as const;"),n.push(""),n.push("// Header Functions"),n.push("export const headers = {");for(let c of f){let h=T(c.operationId);if(!c.requestHeaders||c.requestHeaders.length===0){n.push(` ${S(h)}: () => ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}n.push(` ${S(h)}: (params: z.input<${A(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),n.push(` return ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),n.push(" },")}if(n.push("} as const;"),n.push(""),e.components?.securitySchemes&&Object.keys(e.components.securitySchemes).length>0){n.push("// Security Schemes"),n.push("export const securitySchemes = {");for(let[c,h]of Object.entries(e.components.securitySchemes)){let O=h;n.push(` ${S(c)}: {`),n.push(` type: ${JSON.stringify(O.type)},`),O.type==="http"?(n.push(` scheme: ${JSON.stringify(String(O.scheme).toLowerCase())},`),O.bearerFormat&&n.push(` bearerFormat: ${JSON.stringify(O.bearerFormat)},`)):O.type==="apiKey"?(n.push(` name: ${JSON.stringify(O.name)},`),n.push(` in: ${JSON.stringify(O.in)},`)):O.type==="oauth2"?n.push(` flows: ${JSON.stringify(O.flows)},`):O.type==="openIdConnect"&&n.push(` openIdConnectUrl: ${JSON.stringify(O.openIdConnectUrl)},`),n.push(" },")}n.push("} as const;"),n.push("")}be(n,f,e,l,m),xe(n,f,e,l,m),rn(n,f,u),n.push("// Operation Objects");for(let c of f){let h=T(c.operationId),O=u.emit?`: ${R(h)}Operation`:"";if(n.push(`export const ${h}${O} = {`),n.push(` method: "${c.method}",`),n.push(` path: paths.${h},`),Pe(n,"request",c.requestType),Pe(n,"response",c.responseType),c.requestHeaders&&c.requestHeaders.length>0&&n.push(` headers: headers.${h},`),c.security!==void 0)if(c.security.length===0)n.push(" security: [],");else{let w=c.security.map(b=>`{ ${Object.entries(b).map(([E,N])=>`${S(E)}: ${JSON.stringify(N)}`).join(", ")} }`);n.push(` security: [${w.join(", ")}],`)}c.errors&&Re(c.errors)&&en(n,"errors",c.errors),n.push("} as const;"),n.push("")}let y={output:n.join(`
10
- `)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:ke()}),y}function it(e,t={}){return Xe(e,t).output}function Pe(e,t,n){n&&e.push(` ${t}: ${n},`)}function en(e,t,n){if(!(!n||Object.keys(n).length===0)){e.push(` ${t}: {`);for(let[r,o]of Object.entries(n))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Re(e){return!!(e&&Object.keys(e).length>0)}function nn(e){return{emit:e?.emit??!0,helpers:e?.helpers??"package",helpersOutput:e?.helpersOutput??"./zenko-types",treeShake:e?.treeShake??!0,optionalType:e?.optionalType??"optional"}}function tn(e,t,n){if(t.emit)switch(t.helpers){case"package":if(t.treeShake){let r=V(n),o=U(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(t.treeShake){let r=V(n),o=U(r,"file",t.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${t.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function rn(e,t,n){if(n.emit){e.push("// Operation Types");for(let r of t){let o=T(r.operationId),i=r.requestHeaders?.length?A(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",s=K(r.requestType),a=K(r.responseType),p=on(r.errors),u=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(m=>`{ ${Object.entries(m).map(([f,y])=>`readonly ${S(f)}: readonly ${JSON.stringify(y)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${R(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${A(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${s},`),e.push(` ${a},`),e.push(` ${i},`),e.push(` ${p},`),e.push(` ${u}`),e.push(">;"),e.push("")}}}function on(e){return!e||!Re(e)?"OperationErrors":`OperationErrors<${sn(e)}>`}function sn(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=ze(o);return`${i}: ${s}`}).join("; ")} }`}var Ie=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),qe=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function K(e){if(!e)return"undefined";let t=e.trim();if(t==="undefined")return"undefined";if(Ie.has(t)||t.startsWith("typeof "))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${K(n[1])}>`:qe.test(t)?`typeof ${t}`:t}function ze(e){if(!e)return"unknown";let t=e.trim();if(Ie.has(t)||t.startsWith("typeof "))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${ze(n[1])}>`:qe.test(t)?`typeof ${t}`:t}function an(e){let t=e.schema??{};switch(t.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=t.items??{type:"string"};return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function pn(e){return Ee(e.schema)}function Ee(e){if(!e)return"string";if(e.type==="array")return`Array<${Ee(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Ae(e,t){if(!e)return`String(${t})`;switch(e.type){case"integer":case"number":return`String(${t})`;case"boolean":return`${t} ? "true" : "false"`;default:return`String(${t})`}}export{Xe as a,it as b};
11
- //# sourceMappingURL=chunk-63YFJ2QY.mjs.map
@@ -1,11 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function ne(e){let t=new Set,n=new Set,r=[],o=i=>{if(t.has(i)||n.has(i))return;n.add(i);let s=e[i],a=G(s);for(let p of a)e[p]&&o(p);n.delete(i),t.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function G(e){let t=[],n=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=$(r.$ref);t.push(o);return}if(Array.isArray(r))r.forEach(n);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&t.push($(o));Object.values(r).forEach(n)}}};return n(e),[...new Set(t)]}function $(e){return e.split("/").pop()||"Unknown"}function P(e){if(!e)return!1;let t=e.at(0);return t===void 0||!/[a-zA-Z_$]/.test(t)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return P(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(t,n)=>n.toUpperCase()).replace(/-+$/,"")}function A(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Z(e){let t={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(t.usesOperationDefinition=!0);for(let n of e)n.errors&&te(n.errors)&&(t.usesOperationErrors=!0);return e.length>0&&!t.usesOperationErrors&&e.some(r=>!r.errors||!te(r.errors))&&(t.usesOperationErrors=!0),t}function V(e,t,n){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=t==="package"?'"zenko"':`"${n}"`;return`import type { ${r.join(", ")} } from ${o};`}function te(e){return!!(e&&Object.keys(e).length>0)}var C={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function E(e){let t=Object.keys(e);if(t.includes("application/json"))return"application/json";for(let n of t)if(n in C)return n;return t[0]||""}function ve(e){let t=_optionalChain([e, 'access', _2 => _2.toLowerCase, 'call', _3 => _3(), 'access', _4 => _4.split, 'call', _5 => _5(";"), 'access', _6 => _6[0], 'optionalAccess', _7 => _7.trim, 'call', _8 => _8()]);return t?!!(t.startsWith("text/")||t==="application/xml"||t.startsWith("application/")&&t.endsWith("+xml")):!1}function v(e,t){if(!t||!ve(e)||t.$ref)return t;let n=t.nullable===!0?{nullable:!0}:{};return t.enum?{type:"string",enum:t.enum,...n}:{type:"string",...n}}function H(e,t){if(e){if(e.$ref){let n=$(e.$ref),r=_optionalChain([t, 'access', _9 => _9.components, 'optionalAccess', _10 => _10.parameters, 'optionalAccess', _11 => _11[n]]);if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function N(e){let t=new Map;for(let[,n]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(n)){let o=r;o.operationId&&t.set(o.operationId,o)}for(let[,n]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(n)){let o=r;o.operationId&&t.set(o.operationId,o)}return t}function re(e,t){let n=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return _nullishCoalesce(r.get(p), () => ([]));let u=G(p);return r.set(p,u),u},i=N(t);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=_optionalChain([u, 'access', _12 => _12.requestBody, 'optionalAccess', _13 => _13.content, 'optionalAccess', _14 => _14["application/json"], 'optionalAccess', _15 => _15.schema]);if(_optionalChain([d, 'optionalAccess', _16 => _16.$ref])){let f=$(d.$ref);n.add(f)}else if(d){let f=o(d);for(let y of f)_optionalChain([t, 'access', _17 => _17.components, 'optionalAccess', _18 => _18.schemas, 'optionalAccess', _19 => _19[y]])&&n.add(y)}let m=u.responses||{};for(let[,f]of Object.entries(m)){let y=_optionalChain([f, 'optionalAccess', _20 => _20.content]);if(!y)continue;let c=E(y),h=_optionalChain([y, 'access', _21 => _21[c], 'optionalAccess', _22 => _22.schema]),O=v(c,h);if(_optionalChain([O, 'optionalAccess', _23 => _23.$ref])){let w=$(O.$ref);n.add(w)}else if(O){let w=o(O);for(let b of w)_optionalChain([t, 'access', _24 => _24.components, 'optionalAccess', _25 => _25.schemas, 'optionalAccess', _26 => _26[b]])&&n.add(b)}}for(let f of p.queryParams){if(_optionalChain([f, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.$ref])){let y=$(f.schema.$ref);n.add(y)}if(_optionalChain([f, 'access', _29 => _29.schema, 'optionalAccess', _30 => _30.items, 'optionalAccess', _31 => _31.$ref])){let y=$(f.schema.items.$ref);n.add(y)}}for(let f of p.requestHeaders||[]){if(_optionalChain([f, 'access', _32 => _32.schema, 'optionalAccess', _33 => _33.$ref])){let y=$(f.schema.$ref);n.add(y)}if(_optionalChain([f, 'access', _34 => _34.schema, 'optionalAccess', _35 => _35.items, 'optionalAccess', _36 => _36.$ref])){let y=$(f.schema.items.$ref);n.add(y)}}let l=u.parameters||[];for(let f of l){let y=H(f,t);if(_optionalChain([y, 'optionalAccess', _37 => _37.schema, 'optionalAccess', _38 => _38.$ref])){let c=$(y.schema.$ref);n.add(c)}if(_optionalChain([y, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.items, 'optionalAccess', _41 => _41.$ref])){let c=$(y.schema.items.$ref);n.add(c)}}}let s=new Set,a=Array.from(n);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=_optionalChain([t, 'access', _42 => _42.components, 'optionalAccess', _43 => _43.schemas, 'optionalAccess', _44 => _44[p]]);if(!u)continue;let d=o(u);for(let m of d)_optionalChain([t, 'access', _45 => _45.components, 'optionalAccess', _46 => _46.schemas, 'optionalAccess', _47 => _47[m]])&&!s.has(m)&&(n.add(m),a.push(m))}return n}function je(e,t){return t===!0?!0:Array.isArray(t)?t.includes(e):!1}function B(e,t){switch(t){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function M(e,t,n,r,o,i){if(n.has(e))return"";if(n.add(e),t.enum){let s=t.enum.map(a=>`"${a}"`).join(", ");if(je(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
2
- export const ${e} = z.enum(${e}Known).or(
3
- z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
4
- );`}return`export const ${e} = z.enum([${s}]);`}if(t.allOf&&Array.isArray(t.allOf)){let s=_(t),a=s.map(l=>R(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>J(l,i))?"merge":"and",d=a[0],m=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${m};`}if(t.type==="object"||t.properties)return`export const ${e} = ${ae(t,r,o,i,e)};`;if(t.type==="array"){let s=_nullishCoalesce(t.items, () => ({type:"unknown"})),a=R(s,r,o,i,e),p=r.strictNumeric||t.minItems!==void 0||t.maxItems!==void 0||t.uniqueItems===!0,u=ue(t,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${R(t,r,o,i,e,e)};`}function oe(e,t,n,r,o){let i=e.map(s=>R(s,t,n,r,o));return i.length===0?"z.unknown()":i.length===1?_nullishCoalesce(i[0], () => ("z.unknown()")):`z.union([${i.join(", ")}])`}function U(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ne(e,t){if(!_optionalChain([e, 'optionalAccess', _48 => _48.$ref]))return e;let n=$(e.$ref);return _nullishCoalesce(_optionalChain([t, 'optionalAccess', _49 => _49[n]]), () => (e))}function ie(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(n=>_optionalChain([e, 'optionalAccess', _50 => _50[n]])!==void 0)}function _(e){let t=Array.isArray(e.allOf)?[...e.allOf]:[],n={...e};return delete n.allOf,ie(n)&&t.push(n),t}function I(e,t,n,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=$(e.$ref);if((_optionalChain([r, 'optionalAccess', _51 => _51.get, 'call', _52 => _52(i)])||i)===t)return!0;let a=_optionalChain([n, 'optionalAccess', _53 => _53[i]]);if(a)return I(a,t,n,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>I(i,t,n,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>I(i,t,n,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>I(i,t,n,r,o)):e.not?I(e.not,t,n,r,o):e.items?I(e.items,t,n,r,o):e.properties?Object.values(e.properties).some(i=>I(i,t,n,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?I(e.additionalProperties,t,n,r,o):!1}function J(e,t){let n=Ne(e,t);return n?n.allOf&&Array.isArray(n.allOf)?_(n).every(o=>J(o,t)):n.type==="object"||n.properties!==void 0||n.additionalProperties!==void 0:!1}function Me(e){let t=new Map;if(!_optionalChain([e, 'optionalAccess', _54 => _54.mapping]))return t;for(let[n,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=$(r),i=t.get(o);if(i){i.values.includes(n)||i.values.push(n);continue}t.set(o,{ref:r,values:[n]})}return t}function D(e,t,n,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=$(e.$ref),a=_optionalChain([n, 'optionalAccess', _55 => _55[s]]);return a?D(a,t,n,r):[]}let o=[],i=_optionalChain([e, 'access', _56 => _56.properties, 'optionalAccess', _57 => _57[t]]);if(i){let s=i.const;s!==void 0&&U(s)?o.push(s):Array.isArray(i.enum)&&_optionalChain([i, 'access', _58 => _58.enum, 'optionalAccess', _59 => _59.length])===1&&U(_optionalChain([i, 'access', _60 => _60.enum, 'optionalAccess', _61 => _61[0]]))&&o.push(_optionalChain([i, 'access', _62 => _62.enum, 'optionalAccess', _63 => _63[0]]))}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...D(s,t,n,r));return Array.from(new Set(o))}function se(e,t,n){return{allOf:[e,{type:"object",properties:{[t]:{const:n}},required:[t]}]}}function Ce(e,t,n,r){let o=new Set;for(let a of e)_optionalChain([a, 'optionalAccess', _64 => _64.$ref])&&o.add($(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(_optionalChain([a, 'optionalAccess', _65 => _65.$ref])){let d=$(a.$ref),m=n.get(d);_optionalChain([m, 'optionalAccess', _66 => _66.values, 'access', _67 => _67.length])&&p.push(...m.values),p.push(...D(a,t,r))}else p.push(...D(a,t,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(se(a,t,d))}for(let[a,p]of n.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(se(u,t,d))}return{schemas:i,hasUnmapped:s}}function He(e,t,n,r,o,i,s){let{schemas:a,hasUnmapped:p}=Ce(e,t,_nullishCoalesce(s, () => (new Map)),o),u=a.map(d=>R(d,n,r,o,i));return u.length===0?"z.unknown()":u.length===1?_nullishCoalesce(u[0], () => ("z.unknown()")):p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(t)}, [${u.join(", ")}])`}function R(e,t,n,r,o,i){if(e.$ref){let s=$(e.$ref),a=_optionalChain([n, 'optionalAccess', _68 => _68.get, 'call', _69 => _69(s)])||s;return o&&(a===o||I(_optionalChain([r, 'optionalAccess', _70 => _70[s]]),o,r,n))?`z.lazy(() => ${a})`:a}if(e.const!==void 0&&U(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ie(a)?R(a,t,n,r,o):"z.any()";if(_optionalChain([s, 'optionalAccess', _71 => _71.type])==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=R(s,t,n,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=_(e),a=s.map(l=>R(l,t,n,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return _nullishCoalesce(a[0], () => ("z.object({})"));let u=s.every(l=>J(l,r))?"merge":"and",d=a[0],m=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${m}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(_optionalChain([e, 'access', _72 => _72.discriminator, 'optionalAccess', _73 => _73.propertyName])){let s=Me(e.discriminator);return He(e.oneOf,e.discriminator.propertyName,t,n,r,o,s)}return oe(e.oneOf,t,n,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return oe(e.anyOf,t,n,r,o);if(e.type==="object"||e.properties||e.allOf)return ae(e,t,n,r,o);switch(e.type){case"string":return Fe(e,t,i);case"boolean":return"z.boolean()";case"array":{let s=_nullishCoalesce(e.items, () => ({type:"unknown"})),a=R(s,t,n,r,o),p=t.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return ue(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return pe(e,t);case"integer":return Ge(e,t);default:return"z.unknown()"}}function De(e,t){if(!e||!t)return new Set;let n=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=_optionalChain([r, 'access', _74 => _74.discriminator, 'optionalAccess', _75 => _75.propertyName]);if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>_optionalChain([u, 'optionalAccess', _76 => _76.$ref])&&$(u.$ref)===t),p=Object.values(_nullishCoalesce(_optionalChain([r, 'access', _77 => _77.discriminator, 'optionalAccess', _78 => _78.mapping]), () => ({}))).some(u=>typeof u=="string"&&$(u)===t);(s||p)&&n.add(o)}return n}function ae(e,t,n,r,o){let i=[],s=De(r,o),a=new Set(_nullishCoalesce(e.required, () => ([])));for(let[d,m]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),f=R(m,t,n,r,o),y=B(f,t.optionalType),c=t.optionalType!=="nullable"?Le(y,m):y,h=l?f:c;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
5
- ${i.join(`
6
- `)}
7
- })`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=R(e.additionalProperties,t,n,r,o);return`${p}.catchall(${u})`}function Fe(e,t,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(t.strictDates)switch(e.format){case"date-time":return t.dateTimeOffset===!0||Array.isArray(t.dateTimeOffset)&&n!==void 0&&t.dateTimeOffset.includes(n)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(t.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Le(e,t){return!t||t.default===void 0?e:`${e}.default(${JSON.stringify(t.default)})`}function pe(e,t){let n="z.number()";return t.strictNumeric&&(n=Ve(e,n),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(n+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),n}function Ge(e,t){let n=pe(e,t);return n+=".int()",n}function ue(e,t,n,r){return r&&(typeof e.minItems=="number"&&(t+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(t+=`.max(${e.maxItems})`),e.uniqueItems&&Ze(n)&&(t+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),t}function Ze(e){return _optionalChain([e, 'optionalAccess', _79 => _79.$ref])?!1:new Set(["string","number","integer","boolean"]).has(_optionalChain([e, 'optionalAccess', _80 => _80.type]))}function Ve(e,t){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?t+=`.gt(${e.minimum})`:t+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(t+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?t+=`.lt(${e.maximum})`:t+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(t+=`.lt(${e.exclusiveMaximum})`),t}var Ue={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function ce(e){if(e==="default")return"defaultError";let t=e.trim(),n=Ue[t];if(n)return n;if(/^\d{3}$/.test(t))return`status${t}`;let r=t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function F(e){if(e==="default")return!0;let t=Number(e);return Number.isInteger(t)?t>=400:!1}function $e(e,t){let n=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=de(r),u=le(s,t),{successResponse:d,errors:m}=ye(s,s.operationId,t),l=fe(o,s,e),f=me(l),y=ge(l),c=he(s,e);n.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:f,errors:m,security:c})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=r,u=de(p),d=le(s,t),{successResponse:m,errors:l}=ye(s,s.operationId,t),f=fe(o,s,e),y=me(f),c=ge(f),h=he(s,e);n.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:c,requestType:d,responseType:m,requestHeaders:y,errors:l,security:h})}return n}function fe(e,t,n){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=H(s,n);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(t.parameters),Array.from(r.values())}function de(e){let t=[],n=e.match(/{([^}]+)}/g);if(n)for(let r of n){let o=r.slice(1,-1);t.push({name:o,type:"string"})}return t}function le(e,t){let n=Be(e);if(!n)return;if(n.$ref){let o=$(n.$ref);return _optionalChain([t, 'optionalAccess', _81 => _81.get, 'call', _82 => _82(o)])||o}return`${A(T(e.operationId))}Request`}function Be(e){let t=_optionalChain([e, 'optionalAccess', _83 => _83.requestBody, 'optionalAccess', _84 => _84.content]);if(!t||Object.keys(t).length===0)return;let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of n){let o=_optionalChain([t, 'access', _85 => _85[r], 'optionalAccess', _86 => _86.schema]);if(o)return o}}function ye(e,t,n){let r=_nullishCoalesce(e.responses, () => ({})),o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=_optionalChain([u, 'optionalAccess', _87 => _87.content]);if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):F(p)&&i.push({code:p,schema:"undefined"});continue}let m=E(d),l=_optionalChain([d, 'access', _88 => _88[m], 'optionalAccess', _89 => _89.schema]),f=v(m,l);if(!f){let y=Qe(m,p);y&&(F(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(F(p)){i.push({code:p,schema:f});continue}/^2\d\d$/.test(p)&&o.set(p,f)}let s=_e(o,t,n),a=Je(i,t,n);return{successResponse:s,errors:a}}function _e(e,t,n){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:Q(s,`${A(T(t))}Response`,n)}let[,o]=_nullishCoalesce(e.entries().next().value, () => ([]));if(o)return typeof o=="string"?o:Q(o,`${A(T(t))}Response`,n)}function Je(e=[],t,n){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=ce(o),a=Q(i,`${A(T(t))}${A(s)}`,n);r[s]=a}return r}function Q(e,t,n){if(typeof e=="string")return e;if(e.$ref){let r=$(e.$ref);return _optionalChain([n, 'optionalAccess', _90 => _90.get, 'call', _91 => _91(r)])||r}if(e.type==="array"&&_optionalChain([e, 'access', _92 => _92.items, 'optionalAccess', _93 => _93.$ref])){let r=$(e.items.$ref);return`z.array(${_optionalChain([n, 'optionalAccess', _94 => _94.get, 'call', _95 => _95(r)])||r})`}return e.allOf&&Array.isArray(e.allOf),t}function me(e){let t=[];for(let n of _nullishCoalesce(e, () => ([])))n.in==="header"&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function ge(e){let t=[];for(let n of _nullishCoalesce(e, () => ([])))n.in==="query"&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function he(e,t){let n=e.security;if(Array.isArray(n))return n.length===0?[]:n;if(Array.isArray(t.security)&&t.security.length>0)return t.security}function Oe(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function Qe(e,t){return t==="204"||/^3\d\d$/.test(t)?"undefined":e in C?C[e]:"unknown"}function Se(e,t){let n=new Map,r=N(t);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=We(a);if(!p)continue;let u=`${A(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&n.set(u,p)}}return n}function We(e){let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let n of t){let r=_optionalChain([e, 'access', _96 => _96[n], 'optionalAccess', _97 => _97.schema]);if(r)return r}}function Te(e,t){let n=new Map,r=N(t);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=E(u),m=_optionalChain([u, 'access', _98 => _98[d], 'optionalAccess', _99 => _99.schema]),l=v(d,m);if(!l)continue;let f=`${A(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&n.set(f,l)}}return n}function we(e,t,n,r,o){let i=Se(t,n);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function be(e,t,n,r,o){let i=Te(t,n);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function xe(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
8
- `)}function Ke(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:_nullishCoalesce(e.open, () => (!1)),prefix:_nullishCoalesce(e.unknownPrefix, () => ("Unknown:"))}}function Ye(e,t={}){let n=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=t,u=en(t.types),d=Ke(p),m={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};n.push('import { z } from "zod";');let l=new Map;if(_optionalChain([e, 'access', _100 => _100.components, 'optionalAccess', _101 => _101.schemas]))for(let c of Object.keys(e.components.schemas))l.set(c,T(c));let f=$e(e,l);if(a&&a.length>0){let c=new Set(a);f=f.filter(h=>c.has(h.operationId))}if(nn(n,u,f),n.push(""),_optionalChain([e, 'access', _102 => _102.components, 'optionalAccess', _103 => _103.schemas])){n.push("// Generated Zod Schemas"),n.push("");let c=a&&a.length>0?new Set(re(f,e)):new Set(Object.keys(e.components.schemas)),h=ne(e.components.schemas).filter(O=>c.has(O));for(let O of h){let w=e.components.schemas[O],b=l.get(O);n.push(M(b,w,r,m,l,e.components.schemas)),n.push(""),n.push(`export type ${b} = z.infer<typeof ${b}>;`),n.push("")}}n.push("// Path Functions"),n.push("export const paths = {");for(let c of f){let O=c.pathParams.map(g=>g.name).length>0,w=c.queryParams.length>0,b=T(c.operationId);if(!O&&!w){n.push(` ${S(b)}: () => "${c.path}",`);continue}let q=g=>{if(P(g))return g;let k=T(g);return P(k)||(k=`_${k}`),k},z=[],j=[];for(let g of c.pathParams)z.push(P(g.name)?g.name:`${S(g.name)}: ${q(g.name)}`),j.push(`${S(g.name)}: string`);for(let g of c.queryParams)z.push(P(g.name)?g.name:`${S(g.name)}: ${q(g.name)}`),j.push(`${S(g.name)}${g.required?"":"?"}: ${an(g)}`);let Ee=!O&&w&&c.queryParams.every(g=>!g.required),K=`${z.length?`{ ${z.join(", ")} }`:"{}"}: { ${j.join(", ")} }${Ee?" = {}":""}`,Y=c.path.replace(/{([^}]+)}/g,(g,k)=>`\${${q(k)}}`);if(!w){n.push(` ${S(b)}: (${K}) => \`${Y}\`,`);continue}n.push(` ${S(b)}: (${K}) => {`),n.push(" const params = new URLSearchParams()");for(let g of c.queryParams){let k=P(g.name)?g.name:q(T(g.name)),L=_nullishCoalesce(g.schema, () => ({}));if(_optionalChain([L, 'optionalAccess', _104 => _104.type])==="array"){let ee=Pe(_nullishCoalesce(L.items, () => ({})),"value");g.required?(n.push(` for (const value of ${k}) {`),n.push(` params.append("${g.name}", ${ee})`),n.push(" }")):(n.push(` if (${k} !== undefined) {`),n.push(` for (const value of ${k}) {`),n.push(` params.append("${g.name}", ${ee})`),n.push(" }"),n.push(" }"));continue}let X=Pe(L,k);g.required?n.push(` params.set("${g.name}", ${X})`):(n.push(` if (${k} !== undefined) {`),n.push(` params.set("${g.name}", ${X})`),n.push(" }"))}n.push(" const _searchParams = params.toString()"),n.push(` return \`${Y}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),n.push(" },")}n.push("} as const;"),n.push(""),n.push("// Header Schemas"),n.push("export const headerSchemas = {");for(let c of f){let h=T(c.operationId);if(!c.requestHeaders||c.requestHeaders.length===0){n.push(` ${S(h)}: z.object({}),`);continue}let O=c.requestHeaders.map(w=>{let b=sn(w),q=w.required?b:B(b,m.optionalType);return` ${S(w.name)}: ${q},`}).join(`
9
- `);n.push(` ${S(h)}: z.object({`),n.push(O),n.push(" }),")}n.push("} as const;"),n.push(""),n.push("// Header Functions"),n.push("export const headers = {");for(let c of f){let h=T(c.operationId);if(!c.requestHeaders||c.requestHeaders.length===0){n.push(` ${S(h)}: () => ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}n.push(` ${S(h)}: (params: z.input<${P(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),n.push(` return ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),n.push(" },")}if(n.push("} as const;"),n.push(""),_optionalChain([e, 'access', _105 => _105.components, 'optionalAccess', _106 => _106.securitySchemes])&&Object.keys(e.components.securitySchemes).length>0){n.push("// Security Schemes"),n.push("export const securitySchemes = {");for(let[c,h]of Object.entries(e.components.securitySchemes)){let O=h;n.push(` ${S(c)}: {`),n.push(` type: ${JSON.stringify(O.type)},`),O.type==="http"?(n.push(` scheme: ${JSON.stringify(String(O.scheme).toLowerCase())},`),O.bearerFormat&&n.push(` bearerFormat: ${JSON.stringify(O.bearerFormat)},`)):O.type==="apiKey"?(n.push(` name: ${JSON.stringify(O.name)},`),n.push(` in: ${JSON.stringify(O.in)},`)):O.type==="oauth2"?n.push(` flows: ${JSON.stringify(O.flows)},`):O.type==="openIdConnect"&&n.push(` openIdConnectUrl: ${JSON.stringify(O.openIdConnectUrl)},`),n.push(" },")}n.push("} as const;"),n.push("")}we(n,f,e,l,m),be(n,f,e,l,m),tn(n,f,u),n.push("// Operation Objects");for(let c of f){let h=T(c.operationId),O=u.emit?`: ${A(h)}Operation`:"";if(n.push(`export const ${h}${O} = {`),n.push(` method: "${c.method}",`),n.push(` path: paths.${h},`),ke(n,"request",c.requestType),ke(n,"response",c.responseType),c.requestHeaders&&c.requestHeaders.length>0&&n.push(` headers: headers.${h},`),c.security!==void 0)if(c.security.length===0)n.push(" security: [],");else{let w=c.security.map(b=>`{ ${Object.entries(b).map(([z,j])=>`${S(z)}: ${JSON.stringify(j)}`).join(", ")} }`);n.push(` security: [${w.join(", ")}],`)}c.errors&&Ae(c.errors)&&Xe(n,"errors",c.errors),n.push("} as const;"),n.push("")}let y={output:n.join(`
10
- `)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:xe()}),y}function st(e,t={}){return Ye(e,t).output}function ke(e,t,n){n&&e.push(` ${t}: ${n},`)}function Xe(e,t,n){if(!(!n||Object.keys(n).length===0)){e.push(` ${t}: {`);for(let[r,o]of Object.entries(n))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Ae(e){return!!(e&&Object.keys(e).length>0)}function en(e){return{emit:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _107 => _107.emit]), () => (!0)),helpers:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _108 => _108.helpers]), () => ("package")),helpersOutput:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _109 => _109.helpersOutput]), () => ("./zenko-types")),treeShake:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _110 => _110.treeShake]), () => (!0)),optionalType:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _111 => _111.optionalType]), () => ("optional"))}}function nn(e,t,n){if(t.emit)switch(t.helpers){case"package":if(t.treeShake){let r=Z(n),o=V(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(t.treeShake){let r=Z(n),o=V(r,"file",t.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${t.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function tn(e,t,n){if(n.emit){e.push("// Operation Types");for(let r of t){let o=T(r.operationId),i=_optionalChain([r, 'access', _112 => _112.requestHeaders, 'optionalAccess', _113 => _113.length])?P(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",s=W(r.requestType),a=W(r.responseType),p=rn(r.errors),u=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(m=>`{ ${Object.entries(m).map(([f,y])=>`readonly ${S(f)}: readonly ${JSON.stringify(y)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${A(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${P(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${s},`),e.push(` ${a},`),e.push(` ${i},`),e.push(` ${p},`),e.push(` ${u}`),e.push(">;"),e.push("")}}}function rn(e){return!e||!Ae(e)?"OperationErrors":`OperationErrors<${on(e)}>`}function on(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=qe(o);return`${i}: ${s}`}).join("; ")} }`}var Re=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),Ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function W(e){if(!e)return"undefined";let t=e.trim();if(t==="undefined")return"undefined";if(Re.has(t)||t.startsWith("typeof "))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${W(n[1])}>`:Ie.test(t)?`typeof ${t}`:t}function qe(e){if(!e)return"unknown";let t=e.trim();if(Re.has(t)||t.startsWith("typeof "))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${qe(n[1])}>`:Ie.test(t)?`typeof ${t}`:t}function sn(e){let t=_nullishCoalesce(e.schema, () => ({}));switch(t.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=_nullishCoalesce(t.items, () => ({type:"string"}));return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function an(e){return ze(e.schema)}function ze(e){if(!e)return"string";if(e.type==="array")return`Array<${ze(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Pe(e,t){if(!e)return`String(${t})`;switch(e.type){case"integer":case"number":return`String(${t})`;case"boolean":return`${t} ? "true" : "false"`;default:return`String(${t})`}}exports.a = Ye; exports.b = st;
11
- //# sourceMappingURL=chunk-JCJ5ZIGI.cjs.map