openapi-sync 5.0.7 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +203 -2
- package/bin/cli.js +396 -27
- package/bin/mcp.js +36 -0
- package/dist/chunk-3VKPQNDD.mjs +22 -0
- package/dist/chunk-L52BXDAC.mjs +24 -0
- package/dist/chunk-TTLQP4UN.mjs +856 -0
- package/dist/chunk-VLACEFT4.mjs +1 -0
- package/dist/index.d.mts +351 -32
- package/dist/index.d.ts +351 -32
- package/dist/index.js +418 -377
- package/dist/index.mjs +1 -858
- package/dist/interactive-init-XBZJKJCH.mjs +1 -0
- package/dist/mcp/server.d.mts +1 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +913 -0
- package/dist/mcp/server.mjs +4 -0
- package/dist/validate-3G3NZCPG.mjs +11 -0
- package/llms.txt +334 -0
- package/openapi.sync.schema.json +396 -0
- package/package.json +38 -17
- package/dist/chunk-PUWCZVB7.mjs +0 -1
- package/dist/interactive-init-DZKTNNQK.mjs +0 -12
package/dist/index.mjs
CHANGED
|
@@ -1,858 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
`+" ".repeat(i)+n+": ",Array.isArray(p)){c+="[";for(let t=0;t<p.length;t++){let $=p[t];typeof $=="object"&&$!==null?c+=Te($,i+1):c+=typeof $=="string"?`"${$}"`:$,t<p.length-1&&(c+=", ");}c+="]";}else typeof p=="object"&&p!==null?c+=""+Te(p,i+1):c+=p.split(`
|
|
3
|
-
`).filter(t=>t.trim()!=="").join(`
|
|
4
|
-
${" ".repeat(i)}`);s<e.length-1&&(c+=", ");}return c+=`
|
|
5
|
-
${" ".repeat(i-1)}}`,c},ve=(l,i=1)=>{let c=l.replace(/\/\*\*?[\s\S]*?\*\//g,e=>e.replace(/^\/\*\*?\s*/,"").replace(/\s*\*\/$/,"").split(`
|
|
6
|
-
`).map(n=>n.replace(/^\s*\*\s?/,"").trim()).filter(n=>n.length>0).map(n=>`// ${n}`).join(`
|
|
7
|
-
`));return `
|
|
8
|
-
\`\`\`typescript
|
|
9
|
-
${" ".repeat(i)} ${c.split(`
|
|
10
|
-
`).filter(e=>e.trim()!=="").join(`
|
|
11
|
-
${" ".repeat(i)} `)}
|
|
12
|
-
\`\`\``};function Ft(l,i){return i.split(".").reduce((e,s)=>e&&e[s]!==void 0?e[s]:void 0,l)}var At=(l,i="CUSTOM CODE")=>{let e=["//","#"].map(t=>({start:`${t} \u{1F512} ${i} START`,end:`${t} \u{1F512} ${i} END`})),s={beforeGenerated:"",afterGenerated:""},n=0,p=[];for(;n<l.length;){let t=null,$=-1;for(let j of e){let T=l.indexOf(j.start,n);T!==-1&&($===-1||T<$)&&($=T,t=j);}if($===-1||!t)break;let d=l.indexOf(t.end,$);if(d===-1)break;let f=d+t.end.length,w=l.substring(f,f+100),M=w.match(/^\s*\n\s*((?:\/\/|#)\s*=+)/);if(M){let j=w.indexOf(`
|
|
13
|
-
`,M.index+1);j!==-1?f+=j+1:f+=M[0].length;}let R=$,O=l.substring(Math.max(0,$-200),$),U=/(^|\n)\s*(?:\/\/|#)\s*=+/g,L,k=-1;for(;(L=U.exec(O))!==null;)k=L.index+L[1].length;k!==-1&&(R=Math.max(0,$-200)+k);let B=l.substring(R,f);p.push({start:R,end:f,content:B}),n=f;}return p.length>0&&(l.substring(0,p[0].start).split(`
|
|
14
|
-
`).filter(d=>{let f=d.trim();return f.length>0&&!f.startsWith("//")&&!f.startsWith("#")}).join("").length===0?(s.beforeGenerated=p[0].content,p.length>1&&(s.afterGenerated=p[1].content)):(s.afterGenerated=p[0].content,p.length>1&&!s.beforeGenerated&&(s.beforeGenerated=p[1].content))),s},rt=(l,i="CUSTOM CODE",c=true,e="//")=>{let s=c?`${e} ${l==="top"?"Add your custom code below this line":"Add your custom code above this line"}
|
|
15
|
-
${e} This section will be preserved during regeneration
|
|
16
|
-
`:"";return `${e} ${"=".repeat(60)}
|
|
17
|
-
${e} \u{1F512} ${i} START
|
|
18
|
-
${s}${e} ${"=".repeat(60)}
|
|
19
|
-
|
|
20
|
-
${e} \u{1F512} ${i} END
|
|
21
|
-
${e} ${"=".repeat(60)}`},st=(l,i,c)=>{if(!l)return l;let e=new RegExp(`^\\s*//\\s*(?:={3,}|\u{1F512}\\s+${i}\\s+(?:START|END)|Add your custom code (?:below|above) this line|This section will be preserved during regeneration)\\s*$`);return l.split(`
|
|
22
|
-
`).map(s=>e.test(s)?s.replace(/^\s*\/\//,c):s).join(`
|
|
23
|
-
`)},qe=(l,i,c={})=>{let{position:e="bottom",markerText:s="CUSTOM CODE",includeInstructions:n=true,commentPrefix:p="//"}=c,t={beforeGenerated:"",afterGenerated:""};i&&(t=At(i,s),t.beforeGenerated=st(t.beforeGenerated,s,p),t.afterGenerated=st(t.afterGenerated,s,p)),!t.beforeGenerated&&!t.afterGenerated&&((e==="top"||e==="both")&&(t.beforeGenerated=rt("top",s,n,p)),(e==="bottom"||e==="both")&&(t.afterGenerated=rt("bottom",s,n,p)));let $=[];return t.beforeGenerated&&($.push(t.beforeGenerated),$.push("")),$.push(l),t.afterGenerated&&($.push(""),$.push(t.afterGenerated)),$.join(`
|
|
24
|
-
`)};var Re=V.join(__dirname,"../","../db.json");ue.existsSync(Re)||ue.writeFileSync(Re,"{}");var Me={};try{Me=c(Re);}catch(l){Me={};}var we=Me||{},lt=l=>{ue.writeFileSync(Re,JSON.stringify(l));},pt=(l,i)=>{we[l]=i,lt(we);},ut=l=>we[l],Ge=()=>{we={},lt(we);};var mt={},ct=(l,i)=>{mt[l]=i;},dt=l=>mt[l]||[];var $e=process.cwd(),Fe={},ft=Pt.create({timeout:6e4});jt(ft,{retries:20,retryCondition:l=>l.code==="ECONNABORTED"||l.message.includes("Network Error"),retryDelay:l=>l*1e3});var be=(l,i,c)=>d(null,null,function*(){var t,$,d,f;if(!(((t=c==null?void 0:c.customCode)==null?void 0:t.enabled)!==false)){yield ue.promises.writeFile(l,i);return}let s=null;try{s=yield ue.promises.readFile(l,"utf-8");}catch(w){}let n=l.endsWith(".py")?"#":"//",p=qe(i,s,{position:(($=c==null?void 0:c.customCode)==null?void 0:$.position)||"bottom",markerText:(d=c==null?void 0:c.customCode)==null?void 0:d.markerText,includeInstructions:(f=c==null?void 0:c.customCode)==null?void 0:f.includeInstructions,commentPrefix:n});yield ue.promises.writeFile(l,p);}),yt=(l,i,c,e)=>d(null,null,function*(){let s=yield Rt(l,i,c,e);return e&&!isNaN(e)&&e>0&&(process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||(Fe[i]&&clearTimeout(Fe[i]),Fe[i]=setTimeout(()=>{console.info(`\u{1F504} Auto syncing ${i}`),yt(l,i,c,e);},e))),s}),Rt=(...l)=>d(null,null,function*(){var He,Ke,Ve,Ye,Ze,Xe,en,nn,tn,rn;let[i,c,e]=l,s=r=>r.startsWith("http://")||r.startsWith("https://"),n;try{if(s(i))n=(yield ft.get(i)).data;else {let r=V.isAbsolute(i)?i:V.join($e,i);`${r}`,n=yield ue.promises.readFile(r,"utf-8");}}catch(r){throw process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||console.error(`Failed to load OpenAPI spec for ${c}:`,r),r}if(!n)return;let p=ot(n)?n:at(n),t;try{t=yield vt.parse(p);}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Failed to parse OpenAPI spec for ${c}: ${o}`)}let $=V.join((e==null?void 0:e.folder)||"",c),d=(e==null?void 0:e.language)==="python",f=d?"py":"ts",w={},M=r=>{var o,b;if((o=e==null?void 0:e.folderSplit)!=null&&o.customFolder){let C=e.folderSplit.customFolder(r);if(C)return C}return (b=e==null?void 0:e.folderSplit)!=null&&b.byTags&&r.tags&&r.tags.length>0?r.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},R=typeof(e==null?void 0:e.server)=="string"?e==null?void 0:e.server:((Ke=(He=t==null?void 0:t.servers)==null?void 0:He[(e==null?void 0:e.server)||0])==null?void 0:Ke.url)||"",O=typeof((Ye=(Ve=e==null?void 0:e.types)==null?void 0:Ve.name)==null?void 0:Ye.prefix)=="string"?e==null?void 0:e.types.name.prefix:"I",U=typeof((Xe=(Ze=e==null?void 0:e.endpoints)==null?void 0:Ze.name)==null?void 0:Xe.prefix)=="string"?e==null?void 0:e.endpoints.name.prefix:"",L=(r,o)=>{var C,u;let b=ye(r);if((u=(C=e==null?void 0:e.types)==null?void 0:C.name)!=null&&u.format){let y=e==null?void 0:e.types.name.format("shared",{name:r},b);if(y)return `${O}${y}`}return `${O}${b}`},k=(r,o,b$1,C,u,y=0)=>{let m="",h="",g="";if(o)if(o.$ref)if(o.$ref[0]==="#"){let x=(o.$ref||"").split("/");x.shift();x[0]==="definitions";[...x].pop();let S=ke(r,x,null);if(S){S!=null&&S.name&&(m=S.name),h=x[x.length-1];let J=L(h);J.includes(".")&&(J=J.split(".").map((Ce,fe)=>fe===0?Ce:`["${Ce}"]`).join("")),g+=`${u!=null&&u.noSharedImport?"":"Shared."}${J}`;}}else g+="";else if(o.anyOf)g+=`(${o.anyOf.map(x=>k(r,x,"",C,b(a({},u),{useComponentName:false}))).filter(x=>!!x).join("|")})`;else if(o.oneOf)g+=`(${o.oneOf.map(x=>k(r,x,"",C,b(a({},u),{useComponentName:false}))).filter(x=>!!x).join("|")})`;else if(o.allOf)g+=`(${o.allOf.map(x=>k(r,x,"",C,b(a({},u),{useComponentName:false}))).filter(x=>!!x).join("&")})`;else if(o.items)g+=`${k(r,o.items,"",false,b(a({},u),{useComponentName:false}))}[]`;else if(o.properties){let x=Object.keys(o.properties),P=o.required||[],v="";x.forEach(N=>{var J,xe,Ce,fe,ge,he;let S="";!((xe=(J=e==null?void 0:e.types)==null?void 0:J.doc)!=null&&xe.disable)&&((fe=(Ce=o.properties)==null?void 0:Ce[N])!=null&&fe.description)&&(S=" * "+((ge=o.properties)==null?void 0:ge[N].description.split(`
|
|
25
|
-
`).filter(Ne=>Ne.trim()!=="").join(`
|
|
26
|
-
*${" ".repeat(1)}`))),v+=(S?`/**
|
|
27
|
-
${S}
|
|
28
|
-
*/
|
|
29
|
-
`:"")+`${k(r,(he=o.properties)==null?void 0:he[N],N,P.includes(N),u,y+1)}`;}),v.length>0?g+=`{
|
|
30
|
-
${" ".repeat(y)}${v}${" ".repeat(y)}}`:g+="{[k: string]: any}";}else if(o.enum&&o.enum.length>0){let x=o.enum.includes(null),P=o.enum.filter(N=>N!==null).map(N=>JSON.stringify(N)).filter(N=>N!==void 0),v=P.length>1||P.length>0&&x;v&&(g+="("),P.forEach((N,S)=>{g+=`${S===0?"":"|"}${N}`;}),x&&(g+=`${P.length>0?"|":""}null`),v&&(g+=")");}else if(o.type){let x=P=>{let v="";if(typeof P=="string")["string","integer","number","array","boolean","null"].includes(P)?["integer","number"].includes(P)?v+="number":P==="array"?v+="any[]":v+=P:P==="object"&&(o.additionalProperties?v+=`{[k: string]: ${k(r,o.additionalProperties,"",true,b(a({},u),{useComponentName:false}))||"any"}}`:v+="{[k: string]: any}");else if(Array.isArray(P)){let N=P.map(S=>x(S));N.filter(S=>S!==""),N.length>1&&(v+="("+N.join("|")+")");}else v+="any";return v};g=x(o.type);}else g+="any";else g="string";let q=m||b$1;u!=null&&u.useComponentName&&!q&&(q=h);let Q=q?` "${q}"${C?"":"?"}: `:"",a$1=(o==null?void 0:o.enum)&&o.enum.includes(null),z=o!=null&&o.nullable&&!a$1?" | null":"";return g.length>0?`${Q}${g}${z}${q?`;
|
|
31
|
-
`:""}`:""},B=(r,o,b$1,C,u,y=0)=>{let m="",h="",g="";if(o)if(o.$ref)if(o.$ref[0]==="#"){let x=(o.$ref||"").split("/");x.shift();x[0]==="definitions";[...x].pop();let S=ke(r,x,null);if(S){S!=null&&S.name&&(m=S.name),h=x[x.length-1];let J=L(h);J.includes(".")&&(J=J.split(".").join("_")),g+=`${u!=null&&u.noSharedImport?"":"Shared."}${J}`;}}else g+="Any";else if(o.anyOf)g+=`Union[${o.anyOf.map(x=>B(r,x,"",C,b(a({},u),{useComponentName:false}))).filter(x=>!!x).join(", ")}]`;else if(o.oneOf)g+=`Union[${o.oneOf.map(x=>B(r,x,"",C,b(a({},u),{useComponentName:false}))).filter(x=>!!x).join(", ")}]`;else if(o.allOf)g+="Dict[str, Any]";else if(o.items)g+=`List[${B(r,o.items,"",false,b(a({},u),{useComponentName:false}))}]`;else if(o.properties){let x=Object.keys(o.properties),P=o.required||[],v="";x.forEach(N=>{var S;v+=B(r,(S=o.properties)==null?void 0:S[N],N,P.includes(N),u,y+1);}),v.length>0?b$1?g+="Dict[str, Any]":g+=`
|
|
32
|
-
${v}`:g+="Dict[str, Any]";}else if(o.enum&&o.enum.length>0){let x=o.enum.filter(P=>P!==null).map(P=>JSON.stringify(P));x.length>0?g+=`Literal[${x.join(", ")}]`:g+="Any";}else if(o.type){let x=P=>{let v="";if(typeof P=="string")["integer","number"].includes(P)?v+=P==="number"?"float":"int":P==="string"?v+="str":P==="boolean"?v+="bool":P==="array"?v+="List[Any]":P==="object"?v+="Dict[str, Any]":P==="null"?v+="None":v+="Any";else if(Array.isArray(P)){let N=P.map(S=>x(S)).filter(S=>S!=="");N.length>1?v+=`Union[${N.join(", ")}]`:v+=N[0]||"Any";}else v+="Any";return v};g=x(o.type);}else g+="Any";else g="str";let q=m||b$1;u!=null&&u.useComponentName&&!q&&(q=h);let Q="";q&&(Q=` ${q.replace(/[^a-zA-Z0-9_]/g,"_")}: `);let a$1=g,z=!q&&g.includes(`
|
|
33
|
-
`);return o!=null&&o.nullable&&!z&&(g.startsWith("Union[")?a$1=g.replace("Union[","Union[None, "):a$1=`Optional[${g}]`),g.length>0?`${Q}${a$1}${q?`
|
|
34
|
-
`:""}`:""},j=r=>{let o=(r||"").replace(/^\n+/,"").trimEnd();if(!o)return ` pass
|
|
35
|
-
`;let b=o.split(`
|
|
36
|
-
`),C=/^[A-Za-z_][A-Za-z0-9_]*\s*:\s*.+$/,u=b.map(h=>h.trim()).filter(h=>!!h).filter(h=>!h.startsWith('"""')&&!h.endsWith('"""'));return !u.some(h=>C.test(h))&&u.length===1?` value: ${u[0]}
|
|
37
|
-
`:`${o.split(`
|
|
38
|
-
`).map(h=>h.trim()?/^\s/.test(h)?h:` ${h}`:h).join(`
|
|
39
|
-
`)}
|
|
40
|
-
`},T=r=>{let o=(r||"").replace(/^\n+/,"").trimEnd();if(!o)return null;let b=o.split(`
|
|
41
|
-
`),C=/^[A-Za-z_][A-Za-z0-9_]*\s*:\s*.+$/,u=b.map(m=>m.trim()).filter(m=>!!m).filter(m=>!m.startsWith('"""')&&!m.endsWith('"""'));return !u.some(m=>C.test(m))&&u.length===1?u[0]:null},ee=(r,o,b)=>{let C=T(o);return (b==null?void 0:b.inheritSingleTypeExpression)===true&&!!C?`@dataclass
|
|
42
|
-
class ${r}(${C}):
|
|
43
|
-
pass
|
|
44
|
-
`:`@dataclass
|
|
45
|
-
class ${r}:
|
|
46
|
-
${j(o)}`},F=r=>{let b=["Any","List","Dict","Union","Optional","Literal"].filter(C=>new RegExp(`\\b${C}\\b`).test(r));return b.length>0?`from typing import ${b.join(", ")}
|
|
47
|
-
`:""},W=(r,o=72)=>{let b=(r||"").replace(/\s+/g," ").trim().split(" ");if(!b[0])return [];let C=[],u="";return b.forEach(y=>{let m=u?`${u} ${y}`:y;m.length>o&&u?(C.push(u),u=y):u=m;}),u&&C.push(u),C},ce=r=>{var u,y;if(!r||(y=(u=e==null?void 0:e.types)==null?void 0:u.doc)!=null&&y.disable)return "";let o=(r.description||"").trim(),b=Object.entries(r.properties||{}).map(([m,h])=>({name:m,desc:((h==null?void 0:h.description)||"").trim()})).filter(m=>m.desc.length>0);if(!o&&b.length===0)return "";let C=[' """'];return o&&W(o).forEach(m=>C.push(` ${m}`)),b.length>0&&(o&&C.push(""),C.push(" Attributes:"),b.forEach(m=>{let h=W(m.desc);h.length&&(C.push(` ${m.name}: ${h[0]}`),h.slice(1).forEach(g=>C.push(` ${g}`)));})),C.push(' """'),`${C.join(`
|
|
48
|
-
`)}
|
|
49
|
-
`},se=(r,o)=>{let u="";if(o)if(o.$ref)if(o.$ref[0]==="#"){let y=(o.$ref||"").split("/");y.shift();let h=ke(r,y,null);h&&(h!=null&&h.name&&(h.name),y[y.length-1],u+=se(r,h));}else u+="";else if(o.anyOf)u+=se(r,o.anyOf[0]);else if(o.oneOf)u+=se(r,o.oneOf[0]);else if(o.allOf)u+=`{${o.allOf.map(y=>`...(${se(r,y)})`).join(",")}}`;else if(o.items)u+=`[${se(r,o.items)}]`;else if(o.properties){let h=Object.keys(o.properties).map(g=>{var q;return ` "${g}": ${se(r,(q=o.properties)==null?void 0:q[g])}`}).join(`,
|
|
50
|
-
`);h.length>0?u+=`{
|
|
51
|
-
${h}
|
|
52
|
-
}`:u+="{}";}else if(o.enum&&o.enum.length>0)o.enum.length>1&&(u+=o.enum[0]);else if(o.type)if(o.example)u+=JSON.stringify(o.example);else {let y=m=>{let h="";if(typeof m=="string")["string","integer","number","array","boolean","null"].includes(m)?["integer","number"].includes(m)?h+="123":m==="array"?h+="[]":m==="boolean"?h+="true":m==="null"?h+="null":h+=`"${m}"`:m==="object"&&(h+="{}");else if(Array.isArray(m)){let g=m.map(q=>y(q));g.filter(q=>q!==""),g.length>1&&(h+=g.join("|"));}else h+="any";return h};u=y(o.type);}else u+="any";else u="string";return u},ie=ut(c);if(Ot(ie,t))return;pt(c,t);let pe="",de="",le={},Pe=[],Je=(r,o)=>{let b={},C={};Object.keys(r).forEach(y=>{var g;let m=(g=r[y])!=null&&g.schema?r[y].schema:r[y],h=d?`${B(t,m,"",true,{noSharedImport:true,useComponentName:false})}`:`${k(t,m,"",true,{noSharedImport:true,useComponentName:false})}`;if(h){let q=y.split("."),Q=b,a=C;for(let z=0;z<q.length;z++){let x=q[z];z<q.length-1?(x in Q||(Q[x]={},a[x]={}),Q=Q[x],a=a[x]):(Q[x]=h,a[x]=m);}}}),Object.keys(b).forEach(y=>{var z,x,P,v,N;let m=L(y),h=b[y],g=r[y],q=g!=null&&g.schema?g.schema:g,Q="",a="";!((x=(z=e==null?void 0:e.types)==null?void 0:z.doc)!=null&&x.disable)&&y in r&&((P=r[y])!=null&&P.description)&&(Q=" * "+r[y].description.split(`
|
|
53
|
-
`).filter(J=>J.trim()!=="").join(`
|
|
54
|
-
*${" ".repeat(1)}`)),a=ce(q),d?le[y]=((v=le[y])!=null?v:"")+`@dataclass
|
|
55
|
-
class ${m}:
|
|
56
|
-
`+(a||"")+j(typeof h=="string"?h:"")+`
|
|
57
|
-
`:le[y]=((N=le[y])!=null?N:"")+(Q?`/**
|
|
58
|
-
${Q}
|
|
59
|
-
*/
|
|
60
|
-
`:"")+"export type "+m+" = "+(typeof h=="string"?h:Te(h))+`;
|
|
61
|
-
`;});};t.definitions&&Je(t.definitions),t.components&&Object.keys(t.components).forEach(r=>{if(["schemas","responses","parameters","examples","requestBodies","headers","links","callbacks"].includes(r)){let o=t.components[r];Je(o);}});let _e=r=>{let o="";if(r.content){let b=Object.keys(r.content);b[0]&&r.content[b[0]].schema&&(o+=d?`${B(t,r.content[b[0]].schema,"")}`:`${k(t,r.content[b[0]].schema,"")}`);}return o},me=(r,o,b=0)=>{if(!r)return o==="joi"?"Joi.any()":o==="yup"?"yup.mixed()":"z.any()";if(r.$ref){if(r.$ref[0]==="#"){let C=r.$ref.split("/");C.shift();let u=C.join("."),y=ke(t,u);if(y)return me(y,o,b)}return o==="joi"?"Joi.any()":o==="yup"?"yup.mixed()":"z.any()"}if(r.anyOf||r.oneOf){let C=r.anyOf||r.oneOf;if(C.every(y=>y.enum!==void 0&&Array.isArray(y.enum))){let y=[],m=false;if(C.forEach(h=>{h.enum&&h.enum.forEach(g=>{g===null?m=true:y.includes(g)||y.push(g);});}),y.length>0){let h=y.map(g=>JSON.stringify(g)).join(", ");if(o==="zod"){let g=`z.enum([${h}])`;return m&&(g+=".nullable()"),g}else if(o==="yup"){let g=`yup.mixed().oneOf([${h}])`;return m&&(g+=".nullable()"),g}else return m?`Joi.valid(${h}, null)`:`Joi.valid(${h})`}else if(m)return o==="zod"?"z.null()":o==="yup"?"yup.mixed().nullable()":"Joi.valid(null)"}return o==="zod"?`z.union([${C.map(h=>me(h,o,b+1)).join(", ")}])`:o==="yup"?`yup.mixed().oneOf([${C.map(h=>me(h,o,b+1)).join(", ")}])`:`Joi.alternatives().try(${C.map(m=>me(m,o,b+1)).join(", ")})`}if(r.allOf)if(o==="zod"){let C=r.allOf.map(y=>me(y,o,b+1)),u=C[0];for(let y=1;y<C.length;y++)u=`${u}.merge(${C[y]})`;return u}else return me(r.allOf[0],o,b+1);if(r.items){let C=me(r.items,o,b+1);if(o==="zod"){let u=`z.array(${C})`;return r.minItems!==void 0&&(u+=`.min(${r.minItems})`),r.maxItems!==void 0&&(u+=`.max(${r.maxItems})`),u}else if(o==="yup"){let u=`yup.array().of(${C})`;return r.minItems!==void 0&&(u+=`.min(${r.minItems})`),r.maxItems!==void 0&&(u+=`.max(${r.maxItems})`),u}else {let u=`Joi.array().items(${C})`;return r.minItems!==void 0&&(u+=`.min(${r.minItems})`),r.maxItems!==void 0&&(u+=`.max(${r.maxItems})`),u}}if(r.properties){let C=r.required||[],u=" ".repeat(b+1),y=Object.entries(r.properties).map(([m,h])=>{let g=C.includes(m),q=me(h,o,b+1);return g||(q+=".optional()"),`${u}${m}: ${q}`}).join(`,
|
|
62
|
-
`);return o==="zod"?`z.object({
|
|
63
|
-
${y}
|
|
64
|
-
${" ".repeat(b)}})`:o==="yup"?`yup.object({
|
|
65
|
-
${y}
|
|
66
|
-
${" ".repeat(b)}})`:`Joi.object({
|
|
67
|
-
${y}
|
|
68
|
-
${" ".repeat(b)}})`}if(r.enum&&r.enum.length>0){let C=[],u=false;r.enum.forEach(m=>{m===null?u=true:C.includes(m)||C.push(m);});let y=C.map(m=>JSON.stringify(m)).join(", ");if(o==="zod"){let m=`z.enum([${y}])`;return u&&(m+=".nullable()"),m}else if(o==="yup"){let m=`yup.mixed().oneOf([${y}])`;return u&&(m+=".nullable()"),m}else {let m=`Joi.valid(${y})`;return u&&(m+=".allow(null)"),m}}if(r.type){let u=(y=>{switch(y){case "string":if(o==="zod"){let m="z.string()";return r.format==="email"?m+=".email()":r.format==="uuid"?m+=".uuid()":r.format==="url"||r.format==="uri"?m+=".url()":r.format==="date-time"?m+=".datetime()":r.format==="date"&&(m+=".date()"),r.minLength&&(m+=`.min(${r.minLength})`),r.maxLength&&(m+=`.max(${r.maxLength})`),r.pattern&&(m+=`.regex(/${r.pattern}/)`),m}else if(o==="yup"){let m="yup.string()";return r.format==="email"?m+=".email()":(r.format==="url"||r.format==="uri")&&(m+=".url()"),r.minLength&&(m+=`.min(${r.minLength})`),r.maxLength&&(m+=`.max(${r.maxLength})`),r.pattern&&(m+=`.matches(/${r.pattern}/)`),m}else {let m="Joi.string()";return r.format==="email"?m+=".email()":r.format==="url"||r.format==="uri"?m+=".uri()":r.format==="uuid"?m+=".guid({ version: 'uuidv4' })":r.format==="date-time"&&(m+=".isoDate()"),r.minLength&&(m+=`.min(${r.minLength})`),r.maxLength&&(m+=`.max(${r.maxLength})`),r.pattern&&(m+=`.pattern(/${r.pattern}/)`),m}case "integer":case "number":if(o==="zod"){let m="z.number()";return y==="integer"&&(m+=".int()"),r.minimum!==void 0&&(r.exclusiveMinimum?m+=`.gt(${r.minimum})`:m+=`.min(${r.minimum})`),r.maximum!==void 0&&(r.exclusiveMaximum?m+=`.lt(${r.maximum})`:m+=`.max(${r.maximum})`),m}else if(o==="yup"){let m="yup.number()";return y==="integer"&&(m+=".integer()"),r.minimum!==void 0&&(m+=`.min(${r.minimum})`),r.maximum!==void 0&&(m+=`.max(${r.maximum})`),m}else {let m="Joi.number()";return y==="integer"&&(m+=".integer()"),r.minimum!==void 0&&(r.exclusiveMinimum?m+=`.greater(${r.minimum})`:m+=`.min(${r.minimum})`),r.maximum!==void 0&&(r.exclusiveMaximum?m+=`.less(${r.maximum})`:m+=`.max(${r.maximum})`),m}case "boolean":return o==="joi"?"Joi.boolean()":o==="yup"?"yup.boolean()":"z.boolean()";case "null":return o==="joi"?"Joi.any().allow(null)":o==="yup"?"yup.mixed().nullable()":"z.null()";default:return o==="joi"?"Joi.any()":o==="yup"?"yup.mixed()":"z.any()"}})(typeof r.type=="string"?r.type:r.type[0]);return r.nullable&&o!=="joi"?u+=".nullable()":r.nullable&&o==="joi"&&(u+=".allow(null)"),u}return o==="joi"?"Joi.any()":o==="yup"?"yup.mixed()":"z.any()"},Ct=r=>{var o,b,C,u,y;if((b=(o=e==null?void 0:e.endpoints)==null?void 0:o.value)!=null&&b.replaceWords&&Array.isArray(e==null?void 0:e.endpoints.value.replaceWords)){let m=r;return (y=(u=(C=e==null?void 0:e.endpoints)==null?void 0:C.value)==null?void 0:u.replaceWords)==null||y.forEach((h,g)=>{let q=new RegExp(h.replace,"g");m=m.replace(q,h.with||"");}),m}else return r},bt=(r,o,b=[])=>{var y,m;let C=(y=e==null?void 0:e.endpoints)==null?void 0:y.exclude,u=(m=e==null?void 0:e.endpoints)==null?void 0:m.include;if(u){let h=u.tags&&u.tags.length>0?b.some(q=>u.tags.includes(q)):true,g=u.endpoints&&u.endpoints.length>0?u.endpoints.some(q=>{let Q=!q.method||q.method.toLowerCase()===o.toLowerCase();return q.path?r===q.path&&Q:q.regex?new RegExp(q.regex).test(r)&&Q:false}):true;if(!h||!g)return true}return !!(C&&(C.tags&&C.tags.length>0&&b.some(g=>C.tags.includes(g))||C.endpoints&&C.endpoints.length>0&&C.endpoints.some(g=>{let q=!g.method||g.method.toLowerCase()===o.toLowerCase();return g.path?r===g.path&&q:g.regex?new RegExp(g.regex).test(r)&&q:false})))};if(Object.keys(t.paths||{}).forEach(r=>{let o=t.paths[r];Object.keys(o).forEach(C=>{var on,an,ln,pn,un,mn,cn,dn,fn,yn,gn,hn,$n,Cn,bn,In,xn,En,Tn,An,wn,On,Pn,jn,vn,qn,Rn,kn,Sn,Un,Nn,Ln,Mn,Gn,Fn,Qn,Bn,zn,Dn,Wn,Jn,_n,Hn,Kn,Vn,Yn,Zn,Xn,et,nt;let u=C,y=it(r,u),m=((on=o[u])==null?void 0:on.tags)||[];if(bt(r,u,m))return;let h=o[u],g=M({method:u,path:r,summary:h==null?void 0:h.summary,operationId:h==null?void 0:h.operationId,tags:m,parameters:h==null?void 0:h.parameters,requestBody:h==null?void 0:h.requestBody,responses:h==null?void 0:h.responses});w[g]||(w[g]={endpoints:"",types:"",validation:""});let q=((ln=(an=e==null?void 0:e.endpoints)==null?void 0:an.value)!=null&&ln.includeServer?R:"")+y.pathParts.map(E=>(E[0]==="{"&&E[E.length-1]==="}"?E=`\${${E.replace(/{/,"").replace(/}/,"")}}`:E[0]==="<"&&E[E.length-1]===">"?E=`\${${E.replace(/</,"").replace(/>/,"")}}`:E[0]===":"&&(E=`\${${E.replace(/:/,"")}}`),E)).join("/"),Q=`"${q}"`;y.variables.length>0&&(Q=`(${y.variables.map(I=>`${I}:string`).join(",")})=> \`${q}\``),Q=Ct(Q);let a=o[u],z="",x;if(a!=null&&a.parameters&&((a==null?void 0:a.parameters).forEach((I,A)=>{(I.$ref||I.in==="query"&&I.name)&&(z+=d?`${B(t,I.$ref?I:I.schema,I.name||"",I.required)}`:`${k(t,I.$ref?I:I.schema,I.name||"",I.required)}`);}),z)){z=d?z:`{
|
|
69
|
-
${z}}`;let A=`${y.name}Query`;if((un=(pn=e==null?void 0:e.types)==null?void 0:pn.name)!=null&&un.useOperationId&&(a!=null&&a.operationId)&&(A=`${a.operationId}Query`),A=ye(`${O}${A}`),(cn=(mn=e==null?void 0:e.types)==null?void 0:mn.name)!=null&&cn.format){let _=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"query",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},A);_&&(A=`${O}${_}`);}x=A;let G=d?`${ee(A,z)}
|
|
70
|
-
`:`export type ${A} = ${z};
|
|
71
|
-
`;e!=null&&e.folderSplit?w[g].types+=G:de+=G;}if(((dn=e==null?void 0:e.validations)==null?void 0:dn.disable)!==true&&((yn=(fn=e==null?void 0:e.validations)==null?void 0:fn.generate)==null?void 0:yn.query)!==false&&(a!=null&&a.parameters)){let E=((gn=e.validations)==null?void 0:gn.library)||"zod",A=a.parameters.filter(G=>!G.$ref&&G.in==="query"&&G.name);if(A.length>0){let G=((hn=e==null?void 0:e.validations)==null?void 0:hn.name)||(($n=e==null?void 0:e.types)==null?void 0:$n.name),_=typeof(G==null?void 0:G.prefix)=="string"?G.prefix:"I",Y=typeof((bn=(Cn=e==null?void 0:e.validations)==null?void 0:Cn.name)==null?void 0:bn.suffix)=="string"?e.validations.name.suffix:"Schema",Z=`${y.name}Query`;if(G!=null&&G.useOperationId&&(a!=null&&a.operationId)&&(Z=`${a.operationId}Query`),Z=ye(`${_}${Z}${Y}`),(xn=(In=e==null?void 0:e.validations)==null?void 0:In.name)!=null&&xn.format){let K=e.validations.name.format({code:"",type:"query",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},Z);K&&(Z=`${_}${K}${Y}`);}else if((Tn=(En=e==null?void 0:e.types)==null?void 0:En.name)!=null&&Tn.format){let K=e.types.name.format("endpoint",{code:"",type:"query",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},Z);K&&(Z=`${_}${K}${Y}`);}let D=A.map(K=>{let je=K!=null&&K.schema?me(K.schema,E):E==="joi"?"Joi.string()":E==="yup"?"yup.string()":"z.string()",Et=K.required?"":".optional()";return ` ${K.name}: ${je}${Et}`}).join(`,
|
|
72
|
-
`),H=`export const ${Z} = ${E==="joi"?"Joi.object":E==="yup"?"yup.object":"z.object"}({
|
|
73
|
-
${D}
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
`;e!=null&&e.folderSplit||w[g]||(w[g]={endpoints:"",types:"",validation:""}),w[g].validation+=H;}}let P=a==null?void 0:a.requestBody,v="",N;if(P&&(v=_e(P),v)){let E=`${y.name}DTO`;if((wn=(An=e==null?void 0:e.types)==null?void 0:An.name)!=null&&wn.useOperationId&&(a!=null&&a.operationId)&&(E=`${a.operationId}DTO`),E=ye(`${O}${E}`),(Pn=(On=e==null?void 0:e.types)==null?void 0:On.name)!=null&&Pn.format){let A=e==null?void 0:e.types.name.format("endpoint",{code:"",type:"dto",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},E);A&&(E=`${O}${A}`);}N=E;let I=d?`${ee(E,v,{inheritSingleTypeExpression:true})}
|
|
77
|
-
`:`export type ${E} = ${v};
|
|
78
|
-
`;e!=null&&e.folderSplit?w[g].types+=I:de+=I;}if(((jn=e==null?void 0:e.validations)==null?void 0:jn.disable)!==true&&((qn=(vn=e==null?void 0:e.validations)==null?void 0:vn.generate)==null?void 0:qn.dto)!==false&&P){let E=((Rn=e.validations)==null?void 0:Rn.library)||"zod";if(P.content){let I=Object.keys(P.content);if(I[0]&&P.content[I[0]].schema){let A=((kn=e==null?void 0:e.validations)==null?void 0:kn.name)||((Sn=e==null?void 0:e.types)==null?void 0:Sn.name),G=typeof(A==null?void 0:A.prefix)=="string"?A.prefix:"I",_=typeof((Nn=(Un=e==null?void 0:e.validations)==null?void 0:Un.name)==null?void 0:Nn.suffix)=="string"?e.validations.name.suffix:"Schema",Y=`${y.name}DTO`;if(A!=null&&A.useOperationId&&(a!=null&&a.operationId)&&(Y=`${a.operationId}DTO`),Y=ye(`${G}${Y}${_}`),(Mn=(Ln=e==null?void 0:e.validations)==null?void 0:Ln.name)!=null&&Mn.format){let re=e.validations.name.format({code:"",type:"dto",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},Y);re&&(Y=`${G}${re}${_}`);}else if((Fn=(Gn=e==null?void 0:e.types)==null?void 0:Gn.name)!=null&&Fn.format){let re=e.types.name.format("endpoint",{code:"",type:"dto",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},Y);re&&(Y=`${G}${re}${_}`);}let Z=me(P.content[I[0]].schema,E),D=`export const ${Y} = ${Z};
|
|
79
|
-
|
|
80
|
-
`;e!=null&&e.folderSplit||w[g]||(w[g]={endpoints:"",types:"",validation:""}),w[g].validation+=D;}}}let S={},J="",xe="";if(a!=null&&a.responses){let E=a==null?void 0:a.responses;Object.keys(E).forEach(A=>{var G,_,Y,Z;if(J=_e(E[A]),S[A]=J,J){let D=`${y.name}${A}Response`;if((_=(G=e==null?void 0:e.types)==null?void 0:G.name)!=null&&_.useOperationId&&(a!=null&&a.operationId)&&(D=`${a.operationId}${A}Response`),D=ye(`${O}${D}`),(Z=(Y=e==null?void 0:e.types)==null?void 0:Y.name)!=null&&Z.format){let K=e==null?void 0:e.types.name.format("endpoint",{code:A,type:"response",method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},D);K&&(D=`${O}${K}`);}let re=d?`${ee(D,J,{inheritSingleTypeExpression:true})}
|
|
81
|
-
`:`export type ${D} = ${J};
|
|
82
|
-
`;e!=null&&e.folderSplit?w[g].types+=re:de+=re,S[A]=D;let H=parseInt(A);H>=200&&H<300&&(xe=D);}});}let Ce=E=>!E||!E.length?"":E.map(I=>Object.entries(I).map(([G,_])=>{let Y=G,Z="";return Array.isArray(_)&&_.length&&(Z=`
|
|
83
|
-
- Scopes: [\`${_.join("`, `")}\`]`,Y=`**${Y}**`),`
|
|
84
|
-
- ${Y}${Z}`}).join("")).join(`
|
|
85
|
-
`),fe=a!=null&&a.security?Ce(a.security):"",ge="";if(!((Bn=(Qn=e==null?void 0:e.endpoints)==null?void 0:Qn.doc)!=null&&Bn.disable)){let E="";if((Dn=(zn=e==null?void 0:e.endpoints)==null?void 0:zn.doc)!=null&&Dn.showCurl||d){let I={},A="",G="";(Wn=a.requestBody)!=null&&Wn.content&&Object.keys(a.requestBody.content).forEach(re=>{let H=a.requestBody.content[re].schema;if(H){Array.isArray(I["Content-type"])?I["Content-type"].push(re):I["Content-type"]=[re];let K=se(t,H);K&&(A=K);}}),a!=null&&a.security&&a.security.forEach(D=>{Object.keys(D).forEach(re=>{var K,je;let H=(je=(K=t.components)==null?void 0:K.securitySchemes)==null?void 0:je[re];H&&(H.type==="mutualTLS"?G+=`
|
|
86
|
-
--cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:H.type==="apiKey"?I[(H==null?void 0:H.name)||"X-API-KEY"]="{API_KEY_VALUE}":I.Authorization=`${(H==null?void 0:H.scheme)==="basic"?"Basic":"Bearer"} {${(H==null?void 0:H.scheme)==="basic"?"VALUE":"TOKEN"}}`);});});let _={};Object.keys(I).forEach(D=>{Array.isArray(I[D])?_[D]=I[D].join("; "):_[D]=I[D];});let Z=`${CurlGenerator({url:R+r,method:u.toUpperCase(),headers:_,body:A})||`curl ${R+r} -X ${u.toUpperCase()}`}${G}`;E=d?`
|
|
87
|
-
\`\`\`bash
|
|
88
|
-
${Z}
|
|
89
|
-
\`\`\``:`
|
|
90
|
-
\`\`\`bash
|
|
91
|
-
${Z}
|
|
92
|
-
\`\`\``;}if(d){let I=[];a!=null&&a.description&&I.push(`* ${a.description}`),I.push(`* **Method**: ${u.toUpperCase()}`),I.push(`* **Summary**: ${(a==null?void 0:a.summary)||""}`),I.push(`* **Tags**: [${((Jn=a==null?void 0:a.tags)==null?void 0:Jn.join(", "))||""}]`),I.push(`* **OperationId**: ${(a==null?void 0:a.operationId)||""}`),z&&(I.push("* **Query**:"),I.push("```python"),z.split(`
|
|
93
|
-
`).filter(A=>A.trim().length>0).forEach(A=>I.push(A)),I.push("```")),v&&(I.push("* **DTO**:"),I.push("```python"),v.split(`
|
|
94
|
-
`).filter(A=>A.trim().length>0).forEach(A=>I.push(A)),I.push("```")),J&&(I.push("* **Response**:"),I.push("```python"),Object.entries(S).forEach(([A,G])=>{I.push(`${A}: ${String(G).replace(/\n/g," ")}`);}),I.push("```")),fe&&(I.push("* **Security**:"),fe.split(`
|
|
95
|
-
`).filter(A=>A.trim().length>0).forEach(A=>I.push(A.replace(/\*\*/g,"")))),ge=`"""
|
|
96
|
-
${I.join(`
|
|
97
|
-
`)}${E}
|
|
98
|
-
"""
|
|
99
|
-
`;}else ge=`/**${a!=null&&a.description?`
|
|
100
|
-
* ${a==null?void 0:a.description} `:""}
|
|
101
|
-
* **Method**: \`${u.toUpperCase()}\`
|
|
102
|
-
* **Summary**: ${(a==null?void 0:a.summary)||""}
|
|
103
|
-
* **Tags**: [${((_n=a==null?void 0:a.tags)==null?void 0:_n.join(", "))||""}]
|
|
104
|
-
* **OperationId**: ${(a==null?void 0:a.operationId)||""} ${z?`
|
|
105
|
-
* **Query**: ${ve(z)} `:""}${v?`
|
|
106
|
-
* **DTO**: ${ve(v)} `:""}${J?`
|
|
107
|
-
* **Response**: ${Object.entries(S).map(([I,A])=>`
|
|
108
|
-
- **${I}**: ${ve(A,2)} `).join("")}`:""}${fe?`
|
|
109
|
-
* **Security**: ${fe}
|
|
110
|
-
`:""}${E}
|
|
111
|
-
*/
|
|
112
|
-
`;}let he=(Kn=(Hn=e==null?void 0:e.endpoints)==null?void 0:Hn.name)!=null&&Kn.useOperationId&&((Vn=a==null?void 0:a.operationId)==null?void 0:Vn.length)>0?a.operationId:`${y.name}`;if((Zn=(Yn=e==null?void 0:e.endpoints)==null?void 0:Yn.name)!=null&&Zn.format){let E=e==null?void 0:e.endpoints.name.format({method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId},he);E&&(he=E);}let Ne={method:`"${u}"`,operationId:`"${a==null?void 0:a.operationId}"`,url:Q,tags:(a==null?void 0:a.tags)||[]},It=`Endpoint(
|
|
113
|
-
method="${u}",
|
|
114
|
-
operationId="${(a==null?void 0:a.operationId)||""}",
|
|
115
|
-
url=${Q},
|
|
116
|
-
tags=[${((a==null?void 0:a.tags)||[]).map(E=>`"${E}"`).join(", ")}]
|
|
117
|
-
)`,sn=d?`${U}${he} = ${It}
|
|
118
|
-
${ge?`${ge}`:""}
|
|
119
|
-
|
|
120
|
-
`:`${ge}export const ${U}${he} = ${((et=(Xn=e==null?void 0:e.endpoints)==null?void 0:Xn.value)==null?void 0:et.type)==="object"?Te(Ne):Q};
|
|
121
|
-
`;e!=null&&e.folderSplit?w[g].endpoints+=sn:pe+=sn;let xt={name:`${U}${he}`,method:u,path:r,summary:a==null?void 0:a.summary,operationId:a==null?void 0:a.operationId,tags:m,parameters:(nt=a==null?void 0:a.parameters)==null?void 0:nt.filter(E=>!E.$ref&&E.in&&E.name).map(E=>{var I;return {name:E.name,in:E.in,required:E.required,type:((I=E.schema)==null?void 0:I.type)||"string"}}),requestBody:P?{type:v,required:P.required}:void 0,responses:S?Object.entries(S).reduce((E,[I,A])=>(E[I]={type:A},E),{}):void 0,queryType:x,dtoType:N,responseType:xe||void 0};Pe.push(xt);});}),e!=null&&e.folderSplit){let r=`from dataclasses import dataclass
|
|
122
|
-
from typing import List
|
|
123
|
-
|
|
124
|
-
@dataclass
|
|
125
|
-
class Endpoint:
|
|
126
|
-
method: str
|
|
127
|
-
operationId: str
|
|
128
|
-
url: str
|
|
129
|
-
tags: List[str]
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
`;for(let[o,b]of Object.entries(w))if(b.endpoints||b.types){let C=V.join($,o);if(b.endpoints){let u=V.join($e,C,`endpoints.${f}`);yield ue.promises.mkdir(V.dirname(u),{recursive:true}),yield be(u,d?`${r}${b.endpoints}`:b.endpoints,e);}if(b.types){let u=V.join($e,C,`types.${f}`);yield ue.promises.mkdir(V.dirname(u),{recursive:true});let y=Object.values(le).length>0?d?`from __future__ import annotations
|
|
134
|
-
from dataclasses import dataclass
|
|
135
|
-
from . import shared as Shared
|
|
136
|
-
${F(b.types)}
|
|
137
|
-
${b.types}`:`import * as Shared from "../shared";
|
|
138
|
-
|
|
139
|
-
${b.types}`:b.types;yield be(u,y,e);}if(((en=e==null?void 0:e.validations)==null?void 0:en.disable)!==true&&b.validation&&!d){let u=((nn=e.validations)==null?void 0:nn.library)||"zod",y=u==="joi"?'import Joi from "joi";':u==="yup"?'import * as yup from "yup";':'import { z } from "zod";',m=V.join($e,C,"validations.ts");yield ue.promises.mkdir(V.dirname(m),{recursive:true}),yield be(m,`${y}
|
|
140
|
-
|
|
141
|
-
${b.validation}`,e);}}}if(pe.length>0){let r=`from dataclasses import dataclass
|
|
142
|
-
from typing import List
|
|
143
|
-
|
|
144
|
-
@dataclass
|
|
145
|
-
class Endpoint:
|
|
146
|
-
method: str
|
|
147
|
-
operationId: str
|
|
148
|
-
url: str
|
|
149
|
-
tags: List[str]
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
`,o=V.join($e,$,`endpoints.${f}`);yield ue.promises.mkdir(V.dirname(o),{recursive:true}),yield be(o,d?`${r}${pe}`:pe,e);}if(Object.values(le).length>0){let r=Object.values(le).join(`
|
|
154
|
-
`),o=V.join($e,$,e!=null&&e.folderSplit?"":"types",`shared.${f}`);yield ue.promises.mkdir(V.dirname(o),{recursive:true}),yield be(o,(d?`from __future__ import annotations
|
|
155
|
-
from dataclasses import dataclass
|
|
156
|
-
${F(r)}
|
|
157
|
-
`:"")+r,e);}if(de.length>0){let r=V.join($e,$,"types",`index.${f}`);yield ue.promises.mkdir(V.dirname(r),{recursive:true}),yield be(r,(Object.values(le).length>0?d?`from __future__ import annotations
|
|
158
|
-
from dataclasses import dataclass
|
|
159
|
-
from . import shared as Shared
|
|
160
|
-
${F(de)}
|
|
161
|
-
`:`import * as Shared from "./shared";
|
|
162
|
-
|
|
163
|
-
`:"")+de,e);}if(((tn=e==null?void 0:e.validations)==null?void 0:tn.disable)!==true&&!(e!=null&&e.folderSplit)&&!d){let r=((rn=e.validations)==null?void 0:rn.library)||"zod",o=r==="joi"?'import Joi from "joi";':r==="yup"?'import * as yup from "yup";':'import { z } from "zod";',b=Object.values(w).map(C=>C.validation).filter(C=>C.length>0).join("");if(b){let C=V.join($e,$,"validations.ts");yield ue.promises.mkdir(V.dirname(C),{recursive:true}),yield be(C,`${o}
|
|
164
|
-
|
|
165
|
-
${b}`,e);}}return ct(c,Pe),console.info(`\u2705 Successfully synced ${c}`),{success:true}}),Qe=yt;var gt=(l,i)=>{let c=l;return i.tags&&i.tags.length>0&&(c=c.filter(e=>!e.tags||e.tags.length===0?false:e.tags.some(s=>i.tags.includes(s)))),i.endpoints&&i.endpoints.length>0&&(c=c.filter(e=>i.endpoints.includes(e.name))),c};var Be=(l,i,c=false)=>{var t,$;let e=i.baseURL||"";i.auth;let n=`// Generated Fetch API Client
|
|
166
|
-
`;n+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
167
|
-
|
|
168
|
-
`,n+=`import type {
|
|
169
|
-
`;let p=new Set;return l.forEach(d=>{d.queryType&&p.add(d.queryType),d.dtoType&&p.add(d.dtoType),d.responseType&&p.add(d.responseType);}),p.forEach(d=>{n+=` ${d},
|
|
170
|
-
`;}),n+=`} from '../types';
|
|
171
|
-
|
|
172
|
-
`,n+=`import {
|
|
173
|
-
`,l.forEach(d=>{n+=` ${d.name} as ${d.name}_endpoint,
|
|
174
|
-
`;}),n+=`} from '../endpoints';
|
|
175
|
-
|
|
176
|
-
`,n+=`export interface ApiConfig {
|
|
177
|
-
`,n+=` baseURL?: string;
|
|
178
|
-
`,n+=` headers?: Record<string, string>;
|
|
179
|
-
`,n+=`}
|
|
180
|
-
|
|
181
|
-
`,n+=`let globalConfig: ApiConfig = {
|
|
182
|
-
`,n+=` baseURL: "${e}",
|
|
183
|
-
`,n+=`};
|
|
184
|
-
|
|
185
|
-
`,n+=`export const setApiConfig = (config: Partial<ApiConfig>) => {
|
|
186
|
-
`,n+=` globalConfig = { ...globalConfig, ...config };
|
|
187
|
-
`,n+=`};
|
|
188
|
-
|
|
189
|
-
`,(t=i.errorHandling)!=null&&t.generateErrorClasses&&(n+=`export class ApiError extends Error {
|
|
190
|
-
`,n+=` constructor(
|
|
191
|
-
`,n+=` message: string,
|
|
192
|
-
`,n+=` public statusCode: number,
|
|
193
|
-
`,n+=` public response?: any
|
|
194
|
-
`,n+=` ) {
|
|
195
|
-
`,n+=` super(message);
|
|
196
|
-
`,n+=` this.name = 'ApiError';
|
|
197
|
-
`,n+=` }
|
|
198
|
-
`,n+=`}
|
|
199
|
-
|
|
200
|
-
`),n+=`async function fetchAPI<T>(
|
|
201
|
-
`,n+=` url: string,
|
|
202
|
-
`,n+=` options: RequestInit = {}
|
|
203
|
-
`,n+=`): Promise<T> {
|
|
204
|
-
`,n+=` const headers: Record<string, string> = {
|
|
205
|
-
`,n+=` 'Content-Type': 'application/json',
|
|
206
|
-
`,n+=` ...globalConfig.headers,
|
|
207
|
-
`,n+=` ...(options.headers as Record<string, string>),
|
|
208
|
-
`,n+=` };
|
|
209
|
-
|
|
210
|
-
`,n+=" const response = await fetch(`${globalConfig.baseURL}${url}`, {\n",n+=` ...options,
|
|
211
|
-
`,n+=` headers,
|
|
212
|
-
`,n+=` });
|
|
213
|
-
|
|
214
|
-
`,n+=` if (!response.ok) {
|
|
215
|
-
`,($=i.errorHandling)!=null&&$.generateErrorClasses?(n+=` const errorData = await response.json().catch(() => ({}));
|
|
216
|
-
`,n+=` throw new ApiError(
|
|
217
|
-
`,n+=` errorData.message || response.statusText,
|
|
218
|
-
`,n+=` response.status,
|
|
219
|
-
`,n+=` errorData
|
|
220
|
-
`,n+=` );
|
|
221
|
-
`):n+=" throw new Error(`HTTP error! status: ${response.status}`);\n",n+=` }
|
|
222
|
-
|
|
223
|
-
`,n+=` return response.json();
|
|
224
|
-
`,n+=`}
|
|
225
|
-
|
|
226
|
-
`,l.forEach(d=>{var B,j;let f=d.name,w=((B=d.parameters)==null?void 0:B.filter(T=>T.in==="path"))||[],M=((j=d.parameters)==null?void 0:j.filter(T=>T.in==="query"))||[],R=w.length>0,O=M.length>0,U=!!d.requestBody,L=d.responseType||"any";if(n+=`/**
|
|
227
|
-
`,d.summary&&(n+=` * ${d.summary}
|
|
228
|
-
`),n+=` * @method ${d.method.toUpperCase()}
|
|
229
|
-
`,n+=` * @path ${d.path}
|
|
230
|
-
`,d.tags&&d.tags.length>0&&(n+=` * @tags ${d.tags.join(", ")}
|
|
231
|
-
`),n+=` */
|
|
232
|
-
`,n+=`export async function ${f}(`,(R||O||U)&&(n+=`params: {
|
|
233
|
-
`,R&&(n+=` url: {
|
|
234
|
-
`,w.forEach(T=>{let F={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[T.type||"string"]||"any",W=T.required?"":"?";n+=` ${T.name}${W}: ${F};
|
|
235
|
-
`;}),n+=` };
|
|
236
|
-
`),O&&(n+=` query: ${d.queryType||"Record<string, any>"};
|
|
237
|
-
`),U&&(n+=` data: ${d.dtoType||"any"};
|
|
238
|
-
`),n+=`}
|
|
239
|
-
`),n+=`): Promise<${L}> {
|
|
240
|
-
`,R||O||U){let T=[];R&&T.push("url"),O&&T.push("query"),U&&T.push("data"),n+=` const { ${T.join(", ")} } = params;
|
|
241
|
-
`;}let k;if(R){let T=w.map(ee=>`url.${ee.name}`).join(", ");k=`${d.name}_endpoint(${T})`;}else k=`${d.name}_endpoint`;O?(n+=` const queryParams = new URLSearchParams();
|
|
242
|
-
`,M.forEach(T=>{T.required?n+=` queryParams.append('${T.name}', String(query.${T.name}));
|
|
243
|
-
`:(n+=` if (query.${T.name} !== undefined) {
|
|
244
|
-
`,n+=` queryParams.append('${T.name}', String(query.${T.name}));
|
|
245
|
-
`,n+=` }
|
|
246
|
-
`);}),n+=` const _url = \`\${${k}}?\${queryParams.toString()}\`;
|
|
247
|
-
`):n+=` const _url = ${k};
|
|
248
|
-
`,n+=` return fetchAPI<${L}>(_url, {
|
|
249
|
-
`,n+=` method: '${d.method.toUpperCase()}',
|
|
250
|
-
`,U&&(n+=` body: JSON.stringify(data),
|
|
251
|
-
`),n+=` });
|
|
252
|
-
`,n+=`}
|
|
253
|
-
|
|
254
|
-
`;}),c&&(n+=`// Export all functions as a default object
|
|
255
|
-
`,n+=`const apiClient = {
|
|
256
|
-
`,n+=` setApiConfig,
|
|
257
|
-
`,l.forEach(d=>{n+=` ${d.name},
|
|
258
|
-
`;}),n+=`};
|
|
259
|
-
|
|
260
|
-
`,n+=`export default apiClient;
|
|
261
|
-
`),n},Ie=(l,i,c=false)=>{var t,$;let e=i.baseURL||"";i.auth;let n=`// Generated Axios API Client
|
|
262
|
-
`;n+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
263
|
-
|
|
264
|
-
`,n+=`import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
265
|
-
|
|
266
|
-
`,n+=`import type {
|
|
267
|
-
`;let p=new Set;return l.forEach(d=>{d.queryType&&p.add(d.queryType),d.dtoType&&p.add(d.dtoType),d.responseType&&p.add(d.responseType);}),p.forEach(d=>{n+=` ${d},
|
|
268
|
-
`;}),n+=`} from '../types';
|
|
269
|
-
|
|
270
|
-
`,n+=`import {
|
|
271
|
-
`,l.forEach(d=>{n+=` ${d.name},
|
|
272
|
-
`;}),n+=`} from '../endpoints';
|
|
273
|
-
|
|
274
|
-
`,n+=`export interface ApiConfig {
|
|
275
|
-
`,n+=` baseURL?: string;
|
|
276
|
-
`,n+=` headers?: Record<string, string>;
|
|
277
|
-
`,n+=` timeout?: number;
|
|
278
|
-
`,n+=`}
|
|
279
|
-
|
|
280
|
-
`,(t=i.errorHandling)!=null&&t.generateErrorClasses&&(n+=`export class ApiError extends Error {
|
|
281
|
-
`,n+=` constructor(
|
|
282
|
-
`,n+=` message: string,
|
|
283
|
-
`,n+=` public statusCode: number,
|
|
284
|
-
`,n+=` public response?: any
|
|
285
|
-
`,n+=` ) {
|
|
286
|
-
`,n+=` super(message);
|
|
287
|
-
`,n+=` this.name = 'ApiError';
|
|
288
|
-
`,n+=` }
|
|
289
|
-
`,n+=`}
|
|
290
|
-
|
|
291
|
-
`),n+=`class ApiClient {
|
|
292
|
-
`,n+=` private client: AxiosInstance;
|
|
293
|
-
|
|
294
|
-
`,n+=` constructor(config: ApiConfig = {}) {
|
|
295
|
-
`,n+=` this.client = axios.create({
|
|
296
|
-
`,n+=` baseURL: config.baseURL || "${e}",
|
|
297
|
-
`,n+=` timeout: config.timeout || 30000,
|
|
298
|
-
`,n+=` headers: {
|
|
299
|
-
`,n+=` 'Content-Type': 'application/json',
|
|
300
|
-
`,n+=` ...config.headers,
|
|
301
|
-
`,n+=` },
|
|
302
|
-
`,n+=` });
|
|
303
|
-
|
|
304
|
-
`,n+=` // Response interceptor for error handling
|
|
305
|
-
`,n+=` this.client.interceptors.response.use(
|
|
306
|
-
`,n+=` (response) => response,
|
|
307
|
-
`,n+=` (error) => {
|
|
308
|
-
`,($=i.errorHandling)!=null&&$.generateErrorClasses?(n+=` const message = error.response?.data?.message || error.message;
|
|
309
|
-
`,n+=` const statusCode = error.response?.status || 500;
|
|
310
|
-
`,n+=` throw new ApiError(message, statusCode, error.response?.data);
|
|
311
|
-
`):n+=` return Promise.reject(error);
|
|
312
|
-
`,n+=` }
|
|
313
|
-
`,n+=` );
|
|
314
|
-
`,n+=` }
|
|
315
|
-
|
|
316
|
-
`,n+=` updateConfig(config: Partial<ApiConfig>) {
|
|
317
|
-
`,n+=` Object.assign(this.client.defaults, config);
|
|
318
|
-
`,n+=` }
|
|
319
|
-
|
|
320
|
-
`,l.forEach(d=>{var k,B;let f=d.name,w=((k=d.parameters)==null?void 0:k.filter(j=>j.in==="path"))||[],M=((B=d.parameters)==null?void 0:B.filter(j=>j.in==="query"))||[],R=w.length>0,O=M.length>0,U=!!d.requestBody,L=d.responseType||"any";if(n+=` /**
|
|
321
|
-
`,d.summary&&(n+=` * ${d.summary}
|
|
322
|
-
`),n+=` * @method ${d.method.toUpperCase()}
|
|
323
|
-
`,n+=` * @path ${d.path}
|
|
324
|
-
`,d.tags&&d.tags.length>0&&(n+=` * @tags ${d.tags.join(", ")}
|
|
325
|
-
`),n+=` */
|
|
326
|
-
`,n+=` async ${f}(`,(R||O||U)&&(n+=`params: {
|
|
327
|
-
`,R&&(n+=` url: {
|
|
328
|
-
`,w.forEach(j=>{let ee={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[j.type||"string"]||"any",F=j.required?"":"?";n+=` ${j.name}${F}: ${ee};
|
|
329
|
-
`;}),n+=` };
|
|
330
|
-
`),O&&(n+=` query: ${d.queryType||"Record<string, any>"};
|
|
331
|
-
`),U&&(n+=` data: ${d.dtoType||"any"};
|
|
332
|
-
`),n+=" }"),n+=`): Promise<${L}> {
|
|
333
|
-
`,R||O||U){let j=[];R&&j.push("url"),O&&j.push("query"),U&&j.push("data"),n+=` const { ${j.join(", ")} } = params;
|
|
334
|
-
`;}if(R){let j=w.map(T=>`url.${T.name}`).join(", ");n+=` const _url = ${d.name}(${j});
|
|
335
|
-
`;}else n+=` const _url = ${d.name};
|
|
336
|
-
`;n+=` const config: AxiosRequestConfig = {};
|
|
337
|
-
`,O&&(n+=` config.params = { ...query };
|
|
338
|
-
`),n+=` const response = await this.client.${d.method.toLowerCase()}<${L}>(
|
|
339
|
-
`,n+=` _url,
|
|
340
|
-
`,U?n+=` data,
|
|
341
|
-
config
|
|
342
|
-
`:n+=` config
|
|
343
|
-
`,n+=` );
|
|
344
|
-
`,n+=` return response.data;
|
|
345
|
-
`,n+=` }
|
|
346
|
-
|
|
347
|
-
`;}),n+=`}
|
|
348
|
-
|
|
349
|
-
`,c?n+=`export default ApiClient;
|
|
350
|
-
`:(n+=`export const apiClient = new ApiClient();
|
|
351
|
-
`,n+=`export default apiClient;
|
|
352
|
-
`),n},ze=(l,i)=>{var $,d;let c=(($=i.reactQuery)==null?void 0:$.version)||5,e=((d=i.reactQuery)==null?void 0:d.mutations)!==false,s=!!(i.reactQuery&&i.reactQuery.infiniteQueries&&!i.reactQuery.infiniteQueries.disable),n=`// Generated React Query Hooks
|
|
353
|
-
`;n+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
354
|
-
|
|
355
|
-
`;let p=e&&l.some(f=>["POST","PUT","PATCH","DELETE"].includes(f.method.toUpperCase()));if(c===5){let f=p?`import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
|
|
356
|
-
`:`import { useQuery, UseQueryOptions } from '@tanstack/react-query';
|
|
357
|
-
`;s&&(f=f.replace("@tanstack/react-query';\\n",`@tanstack/react-query';
|
|
358
|
-
import { useInfiniteQuery, UseInfiniteQueryOptions } from '@tanstack/react-query';
|
|
359
|
-
`)),n+=f;}else {let f=p?`import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';
|
|
360
|
-
`:`import { useQuery, UseQueryOptions } from 'react-query';
|
|
361
|
-
`;s&&(f=f.replace("react-query';\\n",`react-query';
|
|
362
|
-
import { useInfiniteQuery, UseInfiniteQueryOptions } from 'react-query';
|
|
363
|
-
`)),n+=f;}n+=`
|
|
364
|
-
`,n+=`import apiClient from './client';
|
|
365
|
-
`,n+=`import type {
|
|
366
|
-
`;let t=new Set;return l.forEach(f=>{f.queryType&&t.add(f.queryType),f.dtoType&&t.add(f.dtoType),f.responseType&&t.add(f.responseType);}),t.forEach(f=>{n+=` ${f},
|
|
367
|
-
`;}),n+=`} from '../types';
|
|
368
|
-
|
|
369
|
-
`,l.forEach(f=>{var T,ee;let w=f.method.toUpperCase(),M=w==="GET",R=["POST","PUT","PATCH","DELETE"].includes(w),O=((T=f.parameters)==null?void 0:T.filter(F=>F.in==="path"))||[],U=((ee=f.parameters)==null?void 0:ee.filter(F=>F.in==="query"))||[],L=O.length>0,k=U.length>0,B=!!f.requestBody,j=f.responseType||"any";if(M){let F=U.map(ie=>ie.name.toLowerCase()),ce=(F.includes("page")||F.includes("cursor")||F.includes("cursorid")||F.includes("after")||F.includes("before"))&&s,se=`use${f.name.charAt(0).toUpperCase()+f.name.slice(1)}`;if(n+=`/**
|
|
370
|
-
`,f.summary&&(n+=` * ${f.summary}
|
|
371
|
-
`),n+=` * @method ${w}
|
|
372
|
-
`,n+=` * @path ${f.path}
|
|
373
|
-
`,f.tags&&f.tags.length>0&&(n+=` * @tags ${f.tags.join(", ")}
|
|
374
|
-
`),n+=` */
|
|
375
|
-
`,L||k?(n+=`export function ${se}(
|
|
376
|
-
`,n+=` params: {
|
|
377
|
-
`,L&&(n+=` url: {
|
|
378
|
-
`,O.forEach(ie=>{let de={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[ie.type||"string"]||"any",le=ie.required?"":"?";n+=` ${ie.name}${le}: ${de};
|
|
379
|
-
`;}),n+=` };
|
|
380
|
-
`),k&&(n+=` query: ${f.queryType||"Record<string, any>"};
|
|
381
|
-
`),n+=` },
|
|
382
|
-
`,n+=` options?: Omit<UseQueryOptions<${j}>, 'queryKey' | 'queryFn'>
|
|
383
|
-
`,n+=`) {
|
|
384
|
-
`,n+=` return useQuery({
|
|
385
|
-
`,n+=` queryKey: ['${f.name}', params],
|
|
386
|
-
`,n+=` queryFn: () => apiClient.${f.name}(params),
|
|
387
|
-
`,n+=` ...options,
|
|
388
|
-
`,n+=` });
|
|
389
|
-
`,n+=`}
|
|
390
|
-
|
|
391
|
-
`):(n+=`export function ${se}(
|
|
392
|
-
`,n+=` options?: Omit<UseQueryOptions<${j}>, 'queryKey' | 'queryFn'>
|
|
393
|
-
`,n+=`) {
|
|
394
|
-
`,n+=` return useQuery({
|
|
395
|
-
`,n+=` queryKey: ['${f.name}'],
|
|
396
|
-
`,n+=` queryFn: () => apiClient.${f.name}(),
|
|
397
|
-
`,n+=` ...options,
|
|
398
|
-
`,n+=` });
|
|
399
|
-
`,n+=`}
|
|
400
|
-
|
|
401
|
-
`),ce){let ie=`${se}Infinite`;L||k?(n+=`export function ${ie}(
|
|
402
|
-
`,n+=` params: {
|
|
403
|
-
`,L&&(n+=` url: {
|
|
404
|
-
`,O.forEach(pe=>{let le={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[pe.type||"string"]||"any",Pe=pe.required?"":"?";n+=` ${pe.name}${Pe}: ${le};
|
|
405
|
-
`;}),n+=` };
|
|
406
|
-
`),k&&(n+=` query: ${f.queryType||"Record<string, any>"};
|
|
407
|
-
`),n+=` },
|
|
408
|
-
`,n+=` options?: Omit<UseInfiniteQueryOptions<${j}, Error, ${j}>, 'queryKey' | 'queryFn'>
|
|
409
|
-
`,n+=`) {
|
|
410
|
-
`,n+=` return useInfiniteQuery({
|
|
411
|
-
`,n+=` queryKey: ['${f.name}', params],
|
|
412
|
-
`,n+=` queryFn: ({ pageParam = 1 }) => apiClient.${f.name}({ ...params, query: { ...(params.query || {}), page: pageParam } }),
|
|
413
|
-
`,n+=` getNextPageParam: (lastPage) => lastPage?.nextPage ?? lastPage?.nextCursor ?? null,
|
|
414
|
-
`,n+=` ...options,
|
|
415
|
-
`,n+=` });
|
|
416
|
-
`,n+=`}
|
|
417
|
-
|
|
418
|
-
`):(n+=`export function ${ie}(
|
|
419
|
-
`,n+=` options?: Omit<UseInfiniteQueryOptions<${j}, Error, ${j}>, 'queryKey' | 'queryFn'>
|
|
420
|
-
`,n+=`) {
|
|
421
|
-
`,n+=` return useInfiniteQuery({
|
|
422
|
-
`,n+=` queryKey: ['${f.name}'],
|
|
423
|
-
`,n+=` queryFn: ({ pageParam = 1 }) => apiClient.${f.name}({ query: { page: pageParam } }),
|
|
424
|
-
`,n+=` getNextPageParam: (lastPage) => lastPage?.nextPage ?? lastPage?.nextCursor ?? null,
|
|
425
|
-
`,n+=` ...options,
|
|
426
|
-
`,n+=` });
|
|
427
|
-
`,n+=`}
|
|
428
|
-
|
|
429
|
-
`);}}else if(R&&e){let F=`use${f.name.charAt(0).toUpperCase()+f.name.slice(1)}`;n+=`/**
|
|
430
|
-
`,f.summary&&(n+=` * ${f.summary}
|
|
431
|
-
`),n+=` * @method ${w}
|
|
432
|
-
`,n+=` * @path ${f.path}
|
|
433
|
-
`,f.tags&&f.tags.length>0&&(n+=` * @tags ${f.tags.join(", ")}
|
|
434
|
-
`),n+=` */
|
|
435
|
-
`;let W="void";(L||k||B)&&(W=`{
|
|
436
|
-
`,L&&(W+=` url: {
|
|
437
|
-
`,O.forEach(ce=>{let ie={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[ce.type||"string"]||"any",pe=ce.required?"":"?";W+=` ${ce.name}${pe}: ${ie};
|
|
438
|
-
`;}),W+=` };
|
|
439
|
-
`),k&&(W+=` query: ${f.queryType||"Record<string, any>"};
|
|
440
|
-
`),B&&(W+=` data: ${f.dtoType||"any"};
|
|
441
|
-
`),W+=" }"),n+=`export function ${F}(
|
|
442
|
-
`,n+=` options?: Omit<UseMutationOptions<${j}, Error, ${W}>, 'mutationFn'>
|
|
443
|
-
`,n+=`) {
|
|
444
|
-
`,n+=` return useMutation({
|
|
445
|
-
`,n+=" mutationFn: (",W!=="void"&&(n+=`variables: ${W}`),n+=`) => {
|
|
446
|
-
`,n+=` return apiClient.${f.name}(${W!=="void"?"variables":""});
|
|
447
|
-
`,n+=` },
|
|
448
|
-
`,n+=` ...options,
|
|
449
|
-
`,n+=` });
|
|
450
|
-
`,n+=`}
|
|
451
|
-
|
|
452
|
-
`;}}),n},De=(l,i)=>{var p;let c=((p=i.swr)==null?void 0:p.mutations)!==false,e=`// Generated SWR Hooks
|
|
453
|
-
`;e+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
454
|
-
|
|
455
|
-
`,e+=`/**
|
|
456
|
-
`,e+=` * SWR Hooks - Complete Usage Guide
|
|
457
|
-
`,e+=` *
|
|
458
|
-
`,e+=` * This file contains type-safe SWR hooks generated from your OpenAPI specification.
|
|
459
|
-
`,e+=` *
|
|
460
|
-
`,e+=` * ## Quick Start
|
|
461
|
-
`,e+=` *
|
|
462
|
-
`,e+=` * 1. Configure SWR globally:
|
|
463
|
-
`,e+=` *
|
|
464
|
-
`,e+=" * ```typescript\n",e+=` * // app/providers.tsx
|
|
465
|
-
`,e+=` * import { SWRConfig } from 'swr';
|
|
466
|
-
`,e+=` *
|
|
467
|
-
`,e+=` * export function Providers({ children }) {
|
|
468
|
-
`,e+=` * return (
|
|
469
|
-
`,e+=` * <SWRConfig value={{
|
|
470
|
-
`,e+=` * revalidateOnFocus: false,
|
|
471
|
-
`,e+=` * shouldRetryOnError: true,
|
|
472
|
-
`,e+=` * errorRetryCount: 3,
|
|
473
|
-
`,e+=` * }}>
|
|
474
|
-
`,e+=` * {children}
|
|
475
|
-
`,e+=` * </SWRConfig>
|
|
476
|
-
`,e+=` * );
|
|
477
|
-
`,e+=` * }
|
|
478
|
-
`,e+=" * ```\n",e+=` *
|
|
479
|
-
`,e+=` * 2. Use the hooks in your components:
|
|
480
|
-
`,e+=` *
|
|
481
|
-
`,e+=` * ### Reading Data (GET)
|
|
482
|
-
`,e+=` *
|
|
483
|
-
`,e+=" * ```typescript\n",e+=` * import { useGetItems } from './hooks';
|
|
484
|
-
`,e+=` *
|
|
485
|
-
`,e+=` * function ItemList() {
|
|
486
|
-
`,e+=` * const { data, error, isLoading, mutate } = useGetItems();
|
|
487
|
-
`,e+=` *
|
|
488
|
-
`,e+=` * if (isLoading) return <div>Loading...</div>;
|
|
489
|
-
`,e+=` * if (error) return <div>Error: {error.message}</div>;
|
|
490
|
-
`,e+=` *
|
|
491
|
-
`,e+=` * return (
|
|
492
|
-
`,e+=` * <div>
|
|
493
|
-
`,e+=` * {data?.map(item => <div key={item.id}>{item.name}</div>)}
|
|
494
|
-
`,e+=` * <button onClick={() => mutate()}>Refresh</button>
|
|
495
|
-
`,e+=` * </div>
|
|
496
|
-
`,e+=` * );
|
|
497
|
-
`,e+=` * }
|
|
498
|
-
`,e+=" * ```\n",e+=` *
|
|
499
|
-
`,e+=` * ### With Path Parameters
|
|
500
|
-
`,e+=` *
|
|
501
|
-
`,e+=" * ```typescript\n",e+=` * function ItemDetail({ id }: { id: string }) {
|
|
502
|
-
`,e+=` * const { data } = useGetItemById({ url: { id } });
|
|
503
|
-
`,e+=` * return <div>{data?.name}</div>;
|
|
504
|
-
`,e+=` * }
|
|
505
|
-
`,e+=" * ```\n",e+=` *
|
|
506
|
-
`,e+=` * ### Creating Data (POST)
|
|
507
|
-
`,e+=` *
|
|
508
|
-
`,e+=" * ```typescript\n",e+=` * import { useCreateItem, useGetItems } from './hooks';
|
|
509
|
-
`,e+=` *
|
|
510
|
-
`,e+=` * function CreateItem() {
|
|
511
|
-
`,e+=` * const { trigger, isMutating, error } = useCreateItem();
|
|
512
|
-
`,e+=` * const { mutate: revalidateList } = useGetItems();
|
|
513
|
-
`,e+=` *
|
|
514
|
-
`,e+=` * const handleSubmit = async (name: string) => {
|
|
515
|
-
`,e+=` * try {
|
|
516
|
-
`,e+=` * const result = await trigger({
|
|
517
|
-
`,e+=` * arg: { data: { name } }
|
|
518
|
-
`,e+=` * });
|
|
519
|
-
`,e+=` * await revalidateList(); // Refresh the list
|
|
520
|
-
`,e+=` * alert('Created!');
|
|
521
|
-
`,e+=` * } catch (err) {
|
|
522
|
-
`,e+=` * console.error('Failed:', err);
|
|
523
|
-
`,e+=` * }
|
|
524
|
-
`,e+=` * };
|
|
525
|
-
`,e+=` *
|
|
526
|
-
`,e+=` * return (
|
|
527
|
-
`,e+=` * <button onClick={() => handleSubmit('New Item')} disabled={isMutating}>
|
|
528
|
-
`,e+=` * {isMutating ? 'Creating...' : 'Create'}
|
|
529
|
-
`,e+=` * </button>
|
|
530
|
-
`,e+=` * );
|
|
531
|
-
`,e+=` * }
|
|
532
|
-
`,e+=" * ```\n",e+=` *
|
|
533
|
-
`,e+=` * ### Updating Data (PUT/PATCH)
|
|
534
|
-
`,e+=` *
|
|
535
|
-
`,e+=" * ```typescript\n",e+=` * function UpdateItem({ id }: { id: string }) {
|
|
536
|
-
`,e+=` * const { data, mutate: revalidate } = useGetItemById({ url: { id } });
|
|
537
|
-
`,e+=` * const { trigger } = useUpdateItem();
|
|
538
|
-
`,e+=` *
|
|
539
|
-
`,e+=` * const handleUpdate = async (newName: string) => {
|
|
540
|
-
`,e+=` * await trigger({
|
|
541
|
-
`,e+=` * arg: {
|
|
542
|
-
`,e+=` * url: { id },
|
|
543
|
-
`,e+=` * data: { name: newName }
|
|
544
|
-
`,e+=` * }
|
|
545
|
-
`,e+=` * });
|
|
546
|
-
`,e+=` * await revalidate(); // Refresh the detail view
|
|
547
|
-
`,e+=` * };
|
|
548
|
-
`,e+=` *
|
|
549
|
-
`,e+=` * return <button onClick={() => handleUpdate('Updated')}>Update</button>;
|
|
550
|
-
`,e+=` * }
|
|
551
|
-
`,e+=" * ```\n",e+=` *
|
|
552
|
-
`,e+=` * ### Deleting Data (DELETE)
|
|
553
|
-
`,e+=` *
|
|
554
|
-
`,e+=" * ```typescript\n",e+=` * function DeleteItem({ id }: { id: string }) {
|
|
555
|
-
`,e+=` * const { trigger, isMutating } = useDeleteItem();
|
|
556
|
-
`,e+=` * const { mutate: revalidateList } = useGetItems();
|
|
557
|
-
`,e+=` *
|
|
558
|
-
`,e+=` * const handleDelete = async () => {
|
|
559
|
-
`,e+=` * if (confirm('Delete?')) {
|
|
560
|
-
`,e+=` * await trigger({ arg: { url: { id } } });
|
|
561
|
-
`,e+=` * await revalidateList();
|
|
562
|
-
`,e+=` * }
|
|
563
|
-
`,e+=` * };
|
|
564
|
-
`,e+=` *
|
|
565
|
-
`,e+=` * return (
|
|
566
|
-
`,e+=` * <button onClick={handleDelete} disabled={isMutating}>
|
|
567
|
-
`,e+=` * {isMutating ? 'Deleting...' : 'Delete'}
|
|
568
|
-
`,e+=` * </button>
|
|
569
|
-
`,e+=` * );
|
|
570
|
-
`,e+=` * }
|
|
571
|
-
`,e+=" * ```\n",e+=` *
|
|
572
|
-
`,e+=` * ## Advanced Patterns
|
|
573
|
-
`,e+=` *
|
|
574
|
-
`,e+=` * ### Optimistic Updates
|
|
575
|
-
`,e+=` *
|
|
576
|
-
`,e+=" * ```typescript\n",e+=` * function OptimisticUpdate({ id }: { id: string }) {
|
|
577
|
-
`,e+=` * const { data, mutate: revalidate } = useGetItemById({ url: { id } });
|
|
578
|
-
`,e+=` * const { trigger } = useUpdateItem();
|
|
579
|
-
`,e+=` *
|
|
580
|
-
`,e+=` * const handleUpdate = async (newName: string) => {
|
|
581
|
-
`,e+=` * // Update UI immediately
|
|
582
|
-
`,e+=` * revalidate({ ...data!, name: newName }, false);
|
|
583
|
-
`,e+=` *
|
|
584
|
-
`,e+=` * try {
|
|
585
|
-
`,e+=` * await trigger({ arg: { url: { id }, data: { name: newName } } });
|
|
586
|
-
`,e+=` * await revalidate(); // Sync with server
|
|
587
|
-
`,e+=` * } catch (err) {
|
|
588
|
-
`,e+=` * await revalidate(); // Rollback on error
|
|
589
|
-
`,e+=` * }
|
|
590
|
-
`,e+=` * };
|
|
591
|
-
`,e+=` *
|
|
592
|
-
`,e+=` * return <button onClick={() => handleUpdate('New')}>Update</button>;
|
|
593
|
-
`,e+=` * }
|
|
594
|
-
`,e+=" * ```\n",e+=` *
|
|
595
|
-
`,e+=` * ### Conditional Fetching
|
|
596
|
-
`,e+=` *
|
|
597
|
-
`,e+=" * ```typescript\n",e+=` * function ConditionalFetch({ id, enabled }: { id: string; enabled: boolean }) {
|
|
598
|
-
`,e+=` * // Only fetch when enabled is true
|
|
599
|
-
`,e+=` * const { data } = useGetItemById(enabled ? { url: { id } } : null);
|
|
600
|
-
`,e+=` * return <div>{data?.name || 'Not loaded'}</div>;
|
|
601
|
-
`,e+=` * }
|
|
602
|
-
`,e+=" * ```\n",e+=` *
|
|
603
|
-
`,e+=` * ### Pagination
|
|
604
|
-
`,e+=` *
|
|
605
|
-
`,e+=" * ```typescript\n",e+=` * function PaginatedList() {
|
|
606
|
-
`,e+=` * const [page, setPage] = useState(1);
|
|
607
|
-
`,e+=` * const { data, isLoading } = useGetItems({ query: { page, limit: 10 } });
|
|
608
|
-
`,e+=` *
|
|
609
|
-
`,e+=` * return (
|
|
610
|
-
`,e+=` * <div>
|
|
611
|
-
`,e+=` * {data?.items.map(item => <div key={item.id}>{item.name}</div>)}
|
|
612
|
-
`,e+=` * <button onClick={() => setPage(p => p - 1)} disabled={page === 1}>
|
|
613
|
-
`,e+=` * Previous
|
|
614
|
-
`,e+=` * </button>
|
|
615
|
-
`,e+=` * <button onClick={() => setPage(p => p + 1)}>Next</button>
|
|
616
|
-
`,e+=` * </div>
|
|
617
|
-
`,e+=` * );
|
|
618
|
-
`,e+=` * }
|
|
619
|
-
`,e+=" * ```\n",e+=` *
|
|
620
|
-
`,e+=` * ### Custom Configuration
|
|
621
|
-
`,e+=` *
|
|
622
|
-
`,e+=" * ```typescript\n",e+=` * function CustomConfig({ id }: { id: string }) {
|
|
623
|
-
`,e+=` * const { data } = useGetItemById(
|
|
624
|
-
`,e+=` * { url: { id } },
|
|
625
|
-
`,e+=` * {
|
|
626
|
-
`,e+=` * refreshInterval: 5000, // Refresh every 5s
|
|
627
|
-
`,e+=` * revalidateOnFocus: true, // Refresh on window focus
|
|
628
|
-
`,e+=` * dedupingInterval: 2000, // Dedupe within 2s
|
|
629
|
-
`,e+=` * onError: (err) => console.error(err),
|
|
630
|
-
`,e+=` * onSuccess: (data) => console.log('Loaded:', data),
|
|
631
|
-
`,e+=` * }
|
|
632
|
-
`,e+=` * );
|
|
633
|
-
`,e+=` * return <div>{data?.name}</div>;
|
|
634
|
-
`,e+=` * }
|
|
635
|
-
`,e+=" * ```\n",e+=` *
|
|
636
|
-
`,e+=` * ## Hook Return Values
|
|
637
|
-
`,e+=` *
|
|
638
|
-
`,e+=` * ### Query Hooks (GET)
|
|
639
|
-
`,e+=" * - `data`: The response data (undefined while loading)\n",e+=" * - `error`: Error object if request failed\n",e+=" * - `isLoading`: True during initial load\n",e+=" * - `isValidating`: True during revalidation\n",e+=" * - `mutate()`: Manually trigger revalidation\n",e+=` *
|
|
640
|
-
`,e+=` * ### Mutation Hooks (POST/PUT/DELETE)
|
|
641
|
-
`,e+=" * - `trigger()`: Execute the mutation\n",e+=" * - `data`: The response data from the mutation\n",e+=" * - `error`: Error object if mutation failed\n",e+=" * - `isMutating`: True while mutation is in progress\n",e+=" * - `reset()`: Reset the mutation state\n",e+=` *
|
|
642
|
-
`,e+=` * @see https://swr.vercel.app/docs/getting-started
|
|
643
|
-
`,e+=` * @see https://swr.vercel.app/docs/mutation
|
|
644
|
-
`,e+=` */
|
|
645
|
-
|
|
646
|
-
`,e+=`import useSWR, { SWRConfiguration } from 'swr';
|
|
647
|
-
`,c&&l.some(t=>["POST","PUT","PATCH","DELETE"].includes(t.method.toUpperCase()))&&(e+=`import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation';
|
|
648
|
-
`),e+=`
|
|
649
|
-
`,e+=`import apiClient from './client';
|
|
650
|
-
`,e+=`import type {
|
|
651
|
-
`;let n=new Set;return l.forEach(t=>{t.queryType&&n.add(t.queryType),t.dtoType&&n.add(t.dtoType),t.responseType&&n.add(t.responseType);}),n.forEach(t=>{e+=` ${t},
|
|
652
|
-
`;}),e+=`} from '../types';
|
|
653
|
-
|
|
654
|
-
`,l.forEach(t=>{var k,B;let $=t.method.toUpperCase(),d=$==="GET",f=["POST","PUT","PATCH","DELETE"].includes($),w=((k=t.parameters)==null?void 0:k.filter(j=>j.in==="path"))||[],M=((B=t.parameters)==null?void 0:B.filter(j=>j.in==="query"))||[],R=w.length>0,O=M.length>0,U=!!t.requestBody,L=t.responseType||"any";if(d){let j=`use${t.name.charAt(0).toUpperCase()+t.name.slice(1)}`;e+=`/**
|
|
655
|
-
`,t.summary&&(e+=` * ${t.summary}
|
|
656
|
-
`),e+=` * @method ${$}
|
|
657
|
-
`,e+=` * @path ${t.path}
|
|
658
|
-
`,t.tags&&t.tags.length>0&&(e+=` * @tags ${t.tags.join(", ")}
|
|
659
|
-
`),e+=` */
|
|
660
|
-
`,R||O?(e+=`export function ${j}(
|
|
661
|
-
`,e+=` params: {
|
|
662
|
-
`,R&&(e+=` url: {
|
|
663
|
-
`,w.forEach(T=>{let F={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[T.type||"string"]||"any",W=T.required?"":"?";e+=` ${T.name}${W}: ${F};
|
|
664
|
-
`;}),e+=` };
|
|
665
|
-
`),O&&(e+=` query: ${t.queryType||"Record<string, any>"};
|
|
666
|
-
`),e+=` },
|
|
667
|
-
`,e+=` config?: SWRConfiguration<${L}>
|
|
668
|
-
`,e+=`) {
|
|
669
|
-
`,e+=` return useSWR(
|
|
670
|
-
`,e+=` ['${t.name}', params],
|
|
671
|
-
`,e+=` () => apiClient.${t.name}(params),
|
|
672
|
-
`,e+=` config
|
|
673
|
-
`,e+=` );
|
|
674
|
-
`):(e+=`export function ${j}(
|
|
675
|
-
`,e+=` config?: SWRConfiguration<${L}>
|
|
676
|
-
`,e+=`) {
|
|
677
|
-
`,e+=` return useSWR(
|
|
678
|
-
`,e+=` '${t.name}',
|
|
679
|
-
`,e+=` () => apiClient.${t.name}(),
|
|
680
|
-
`,e+=` config
|
|
681
|
-
`,e+=` );
|
|
682
|
-
`),e+=`}
|
|
683
|
-
|
|
684
|
-
`;}else if(f&&c){let j=`use${t.name.charAt(0).toUpperCase()+t.name.slice(1)}`;e+=`/**
|
|
685
|
-
`,t.summary&&(e+=` * ${t.summary}
|
|
686
|
-
`),e+=` * @method ${$}
|
|
687
|
-
`,e+=` * @path ${t.path}
|
|
688
|
-
`,t.tags&&t.tags.length>0&&(e+=` * @tags ${t.tags.join(", ")}
|
|
689
|
-
`),e+=` */
|
|
690
|
-
`;let T="void",ee="void";(R||O||U)&&(T=`{
|
|
691
|
-
`,R&&(T+=` url: {
|
|
692
|
-
`,w.forEach(F=>{let ce={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[F.type||"string"]||"any",se=F.required?"":"?";T+=` ${F.name}${se}: ${ce};
|
|
693
|
-
`;}),T+=` };
|
|
694
|
-
`),O&&(T+=` query: ${t.queryType||"Record<string, any>"};
|
|
695
|
-
`),U&&(T+=` data: ${t.dtoType||"any"};
|
|
696
|
-
`),T+=" }",ee=`{ arg: ${T} }`),e+=`export function ${j}(
|
|
697
|
-
`,e+=` config?: SWRMutationConfiguration<${L}, Error, string, ${T}>
|
|
698
|
-
`,e+=`) {
|
|
699
|
-
`,e+=` return useSWRMutation(
|
|
700
|
-
`,e+=` '${t.name}',
|
|
701
|
-
`,e+=" async (_, ",T!=="void"&&(e+=`{ arg }: ${ee}`),e+=`) => {
|
|
702
|
-
`,e+=` return apiClient.${t.name}(${T!=="void"?"arg":""});
|
|
703
|
-
`,e+=` },
|
|
704
|
-
`,e+=` config
|
|
705
|
-
`,e+=` );
|
|
706
|
-
`,e+=`}
|
|
707
|
-
|
|
708
|
-
`;}}),e},We=(l,i)=>{var p;let c=((p=i.rtkQuery)==null?void 0:p.apiName)||"api",e=i.baseURL||"",s=`// Generated RTK Query API Slice
|
|
709
|
-
`;s+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
710
|
-
|
|
711
|
-
`,s+=`import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
|
|
712
|
-
|
|
713
|
-
`,s+=`import type {
|
|
714
|
-
`;let n=new Set;return l.forEach(t=>{t.queryType&&n.add(t.queryType),t.dtoType&&n.add(t.dtoType),t.responseType&&n.add(t.responseType);}),n.forEach(t=>{s+=` ${t},
|
|
715
|
-
`;}),s+=`} from '../types';
|
|
716
|
-
|
|
717
|
-
`,s+=`import {
|
|
718
|
-
`,l.forEach(t=>{s+=` ${t.name},
|
|
719
|
-
`;}),s+=`} from '../endpoints';
|
|
720
|
-
|
|
721
|
-
`,s+=`const ${c}Api = createApi({
|
|
722
|
-
`,s+=` reducerPath: '${c}Api',
|
|
723
|
-
`,s+=` baseQuery: fetchBaseQuery({
|
|
724
|
-
`,s+=` baseUrl: '${e}',
|
|
725
|
-
`,i.auth&&(s+=` prepareHeaders: (headers, { getState }) => {
|
|
726
|
-
`,s+=` // Get token from your auth state
|
|
727
|
-
`,s+=` // const token = (getState() as RootState).auth.token;
|
|
728
|
-
`,s+=` // if (token) {
|
|
729
|
-
`,i.auth.type==="bearer"?s+=" // headers.set('Authorization', `Bearer ${token}`);\n":i.auth.type==="apiKey"&&i.auth.in==="header"&&(s+=` // headers.set('${i.auth.name||"X-API-Key"}', token);
|
|
730
|
-
`),s+=` // }
|
|
731
|
-
`,s+=` return headers;
|
|
732
|
-
`,s+=` },
|
|
733
|
-
`),s+=` }),
|
|
734
|
-
`,s+=` tagTypes: [${[...new Set(l.flatMap(t=>t.tags||[]))].map(t=>`'${t}'`).join(", ")}],
|
|
735
|
-
`,s+=` endpoints: (builder) => ({
|
|
736
|
-
`,l.forEach((t,$)=>{var B,j;let d=t.method.toUpperCase(),f=d==="GET",w=((B=t.parameters)==null?void 0:B.filter(T=>T.in==="path"))||[],M=((j=t.parameters)==null?void 0:j.filter(T=>T.in==="query"))||[],R=w.length>0,O=M.length>0,U=!!t.requestBody,L=t.responseType||"any";s+=` ${t.name}: builder.${f?"query":"mutation"}<
|
|
737
|
-
`,s+=` ${L},
|
|
738
|
-
`;let k="void";if((R||O||U)&&(k=`{
|
|
739
|
-
`,R&&(k+=` url: {
|
|
740
|
-
`,w.forEach(T=>{let F={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[T.type||"string"]||"any",W=T.required?"":"?";k+=` ${T.name}${W}: ${F};
|
|
741
|
-
`;}),k+=` };
|
|
742
|
-
`),O&&(k+=` query: ${t.queryType||"Record<string, any>"};
|
|
743
|
-
`),U&&(k+=` data: ${t.dtoType||"any"};
|
|
744
|
-
`),k+=" }"),s+=` ${k}
|
|
745
|
-
`,s+=` >({
|
|
746
|
-
`,s+=" query: (",k!=="void"&&(s+="arg"),s+=`) => {
|
|
747
|
-
`,R){let T=w.map(ee=>`arg.url.${ee.name}`).join(", ");s+=` const url = ${t.name}(${T});
|
|
748
|
-
`;}else s+=` const url = ${t.name};
|
|
749
|
-
`;s+=` return {
|
|
750
|
-
`,s+=` url,
|
|
751
|
-
`,s+=` method: '${d}',
|
|
752
|
-
`,O&&(s+=` params: arg.query,
|
|
753
|
-
`),U&&(s+=` body: arg.data,
|
|
754
|
-
`),s+=` };
|
|
755
|
-
`,s+=` },
|
|
756
|
-
`,t.tags&&t.tags.length>0&&(f?s+=` providesTags: ['${t.tags[0]}'],
|
|
757
|
-
`:s+=` invalidatesTags: ['${t.tags[0]}'],
|
|
758
|
-
`),s+=` })${$<l.length-1?",":""}
|
|
759
|
-
`;}),s+=` }),
|
|
760
|
-
`,s+=`});
|
|
761
|
-
|
|
762
|
-
`,s+=`export default ${c}Api;
|
|
763
|
-
|
|
764
|
-
`,s};var kt=(l,i)=>{var c,e;if((c=i==null?void 0:i.folderSplit)!=null&&c.customFolder){let s=i.folderSplit.customFolder({method:l.method,path:l.path,tags:l.tags,operationId:l.operationId,summary:l.summary});if(s)return s}return (e=i==null?void 0:i.folderSplit)!=null&&e.byTags&&l.tags&&l.tags.length>0?l.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},ht=(l,i,c,e,s)=>d(null,null,function*(){let n=gt(l,c);if(n.length===0)return;let p=c.type||"fetch";c.outputDir||V.join(s,e,"client");let $=!!(i!=null&&i.folderSplit&&(i.folderSplit.byTags||i.folderSplit.customFolder));if(`${p}${n.length}`,$){let f={};n.forEach(R=>{let O=kt(R,i);f[O]||(f[O]=[]),f[O].push(R);});let w=Object.keys(f);for(let[R,O]of Object.entries(f)){let U=V.join(s,e,R);yield ue.promises.mkdir(U,{recursive:true}),`${p}${R}${O.length}`,yield St(O,i,c,U,p,R,true);}let M=V.join(s,e);yield Ut(M,w,p,i);return}let d=V.join(s,e);switch(yield ue.promises.mkdir(d,{recursive:true}),p){case "fetch":let f=Be(n,c);f=f.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield te(V.join(d,"clients.ts"),f,i);break;case "axios":let w=Ie(n,c,false);w=w.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield te(V.join(d,"clients.ts"),w,i);break;case "react-query":let M=Ie(n,c,false);M=M.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield te(V.join(d,"clients.ts"),M,i);let R=ze(n,c);R=R.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield te(V.join(d,"hooks.ts"),R,i);break;case "swr":let O=Ie(n,c,false);O=O.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield te(V.join(d,"clients.ts"),O,i);let U=De(n,c);U=U.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield te(V.join(d,"hooks.ts"),U,i);break;case "rtk-query":let L=We(n,c);L=L.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield te(V.join(d,"api.ts"),L,i);break;default:throw new Error(`Unknown client type: ${p}`)}}),te=(l,i,c)=>d(null,null,function*(){var p,t,$,d;if(!(((p=c==null?void 0:c.customCode)==null?void 0:p.enabled)!==false)){yield ue.promises.writeFile(l,i);return}let s=null;try{s=yield ue.promises.readFile(l,"utf-8");}catch(f){}let n=qe(i,s,{position:((t=c==null?void 0:c.customCode)==null?void 0:t.position)||"bottom",markerText:($=c==null?void 0:c.customCode)==null?void 0:$.markerText,includeInstructions:(d=c==null?void 0:c.customCode)==null?void 0:d.includeInstructions});yield ue.promises.writeFile(l,n);});var St=(l,i,c,e,s,n,p=false)=>d(null,null,function*(){let t="",$="",d=p?"./types":"../types",f=p?"./endpoints":"../endpoints";switch(s){case "fetch":t=Be(l,c,p),t=t.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),yield te(V.join(e,"client.ts"),t,i);break;case "axios":t=Ie(l,c,p),t=t.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),yield te(V.join(e,"client.ts"),t,i);break;case "react-query":if(t=Ie(l,c,p),t=t.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),yield te(V.join(e,"client.ts"),t,i),$=ze(l,c),$=$.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),p){let M=n.replace(/-/g,"_");$=$.replace("import apiClient from './client';",`import { ${M}Client as apiClient } from '../clients';`);}yield te(V.join(e,"hooks.ts"),$,i);break;case "swr":if(t=Ie(l,c,p),t=t.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),yield te(V.join(e,"client.ts"),t,i),$=De(l,c),$=$.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),p){let M=n.replace(/-/g,"_");$=$.replace("import apiClient from './client';",`import { ${M}Client as apiClient } from '../clients';`);}yield te(V.join(e,"hooks.ts"),$,i);break;case "rtk-query":let w=p?b(a({},c),{rtkQuery:b(a({},c.rtkQuery),{apiName:n.replace(/-/g,"_")})}):c;$=We(l,w),$=$.replace("} from '../types';",`} from '${d}';`).replace("} from '../endpoints';",`} from '${f}';`),yield te(V.join(e,"api.ts"),$,i);break;default:throw new Error(`Unknown client type: ${s}`)}}),Ut=(l,i,c,e)=>d(null,null,function*(){var n;if(c==="rtk-query"){let p=`// Generated RTK Query APIs
|
|
765
|
-
`;p+=`// This file was auto-generated.
|
|
766
|
-
`,p+=`// Aggregates all API slices for easy Redux store setup
|
|
767
|
-
|
|
768
|
-
`,i.forEach(t=>{let $=t.replace(/-/g,"_");p+=`import ${$}Api from './${t}/api';
|
|
769
|
-
`;}),p+=`
|
|
770
|
-
// Export all API slices
|
|
771
|
-
`,i.forEach(t=>{let $=t.replace(/-/g,"_");p+=`export { default as ${$}Api } from './${t}/api';
|
|
772
|
-
`;}),p+=`
|
|
773
|
-
/**
|
|
774
|
-
`,p+=` * Configure Redux store with all API slices
|
|
775
|
-
`,p+=` *
|
|
776
|
-
`,p+=` * @example
|
|
777
|
-
`,p+=` * import { configureStore } from '@reduxjs/toolkit';
|
|
778
|
-
`,p+=` * import { setupApiStore } from './apis';
|
|
779
|
-
`,p+=` *
|
|
780
|
-
`,p+=` * export const store = configureStore({
|
|
781
|
-
`,p+=` * reducer: setupApiStore.reducer,
|
|
782
|
-
`,p+=` * middleware: (getDefaultMiddleware) =>
|
|
783
|
-
`,p+=` * getDefaultMiddleware().concat(setupApiStore.middleware),
|
|
784
|
-
`,p+=` * });
|
|
785
|
-
`,p+=` */
|
|
786
|
-
`,p+=`export const setupApiStore = {
|
|
787
|
-
`,p+=` reducer: {
|
|
788
|
-
`,i.forEach(t=>{let $=t.replace(/-/g,"_");p+=` [${$}Api.reducerPath]: ${$}Api.reducer,
|
|
789
|
-
`;}),p+=` },
|
|
790
|
-
`,p+=` middleware: [
|
|
791
|
-
`,i.forEach(t=>{let $=t.replace(/-/g,"_");p+=` ${$}Api.middleware,
|
|
792
|
-
`;}),p+=` ],
|
|
793
|
-
`,p+=`};
|
|
794
|
-
`,yield te(V.join(l,"apis.ts"),p,e);return}let s=`// Generated API Clients
|
|
795
|
-
`;if(s+=`// This file was auto-generated.
|
|
796
|
-
`,s+=`// Centralized client instances and configuration
|
|
797
|
-
|
|
798
|
-
`,c==="fetch"?i.forEach(p=>{let t=p.replace(/-/g,"_");s+=`export { default as ${t}Client } from './${p}/client';
|
|
799
|
-
`;}):(i.forEach(p=>{let t=p.replace(/-/g,"_"),$=`${t.charAt(0).toUpperCase()+t.slice(1)}ApiClient`;s+=`import ${$} from './${p}/client';
|
|
800
|
-
`;}),s+=`
|
|
801
|
-
// Create client instances
|
|
802
|
-
`,i.forEach(p=>{let t=p.replace(/-/g,"_"),$=`${t.charAt(0).toUpperCase()+t.slice(1)}ApiClient`;s+=`export const ${t}Client = new ${$}();
|
|
803
|
-
`;})),c==="fetch"&&(s+=`
|
|
804
|
-
// Import clients for aggregation
|
|
805
|
-
`,i.forEach(p=>{let t=p.replace(/-/g,"_");s+=`import ${t}_client from './${p}/client';
|
|
806
|
-
`;})),s+=`
|
|
807
|
-
// Aggregate all client instances
|
|
808
|
-
`,s+=`export const clients = {
|
|
809
|
-
`,i.forEach(p=>{let t=p.replace(/-/g,"_");c==="fetch"?s+=` ${t}: ${t}_client,
|
|
810
|
-
`:s+=` ${t}: ${t}Client,
|
|
811
|
-
`;}),s+=`};
|
|
812
|
-
|
|
813
|
-
`,c==="axios"?(s+=`
|
|
814
|
-
/**
|
|
815
|
-
`,s+=` * Configure all API clients at once
|
|
816
|
-
`,s+=` * @param config - Configuration to apply to all clients
|
|
817
|
-
`,s+=` */
|
|
818
|
-
`,s+=`export const configureAllClients = (config: {
|
|
819
|
-
`,s+=` baseURL?: string;
|
|
820
|
-
`,s+=` headers?: Record<string, string>;
|
|
821
|
-
`,s+=` timeout?: number;
|
|
822
|
-
`,s+=`}) => {
|
|
823
|
-
`,i.forEach(p=>{let t=p.replace(/-/g,"_");s+=` ${t}Client.updateConfig(config);
|
|
824
|
-
`;}),s+=`};
|
|
825
|
-
|
|
826
|
-
`):c==="fetch"&&(s+=`
|
|
827
|
-
/**
|
|
828
|
-
`,s+=` * Configure all API clients at once
|
|
829
|
-
`,s+=` * @param config - Configuration to apply to all clients
|
|
830
|
-
`,s+=` */
|
|
831
|
-
`,s+=`export const configureAllClients = (config: {
|
|
832
|
-
`,s+=` baseURL?: string;
|
|
833
|
-
`,s+=` headers?: Record<string, string>;
|
|
834
|
-
`,s+=` auth?: { token?: string };
|
|
835
|
-
`,s+=`}) => {
|
|
836
|
-
`,i.forEach(p=>{let t=p.replace(/-/g,"_");s+=` ${t}_client.setApiConfig(config);
|
|
837
|
-
`;}),s+=`};
|
|
838
|
-
|
|
839
|
-
`),s+=`// Example usage:
|
|
840
|
-
`,s+=`// import { configureAllClients, clients } from './clients';
|
|
841
|
-
`,s+=`//
|
|
842
|
-
`,s+=`// // Configure all clients at once
|
|
843
|
-
`,s+=`// configureAllClients({
|
|
844
|
-
`,s+=`// baseURL: 'https://api.example.com',
|
|
845
|
-
`,s+=`// timeout: 10000,
|
|
846
|
-
`,s+=`// });
|
|
847
|
-
`,s+=`//
|
|
848
|
-
`,s+=`// // Use specific client
|
|
849
|
-
`,s+=`// const data = await clients.${(n=i[0])==null?void 0:n.replace(/-/g,"_")}.someMethod(...);
|
|
850
|
-
`,yield te(V.join(l,"clients.ts"),s,e),c==="react-query"||c==="swr"){let p=`// Generated Hooks Aggregator
|
|
851
|
-
`;p+=`// This file was auto-generated.
|
|
852
|
-
`,p+=`// Aggregates all folder-split hooks
|
|
853
|
-
|
|
854
|
-
`,i.forEach(t=>{p+=`export * from './${t}/hooks';
|
|
855
|
-
`;}),p+=`
|
|
856
|
-
// Example usage:
|
|
857
|
-
`,p+=`// import { useGetSomething } from './hooks';
|
|
858
|
-
`,yield te(V.join(l,"hooks.ts"),p,e);}});var Ue=process.cwd(),$t=()=>{let l;try{c("esbuild-register");}catch(p){throw p}let i=V.join(Ue,"openapi.sync.js"),c$1=V.join(Ue,"openapi.sync.ts"),e=V.join(Ue,"openapi.sync.json"),s=[i,c$1,e];try{for(let p of s)ue.existsSync(p)&&(l=c(p),Object.keys(l).length===1&&l.default&&(l=l.default));}catch(p){}typeof l=="function"&&(l=l());let n=l;if(!n)throw new Error("No config found");return n},Er=l=>d(null,null,function*(){let i=$t(),c=Object.keys(i.api),e=l&&"refetchInterval"in l&&!isNaN(l==null?void 0:l.refetchInterval)?l.refetchInterval:i.refetchInterval;Ge();for(let s=0;s<c.length;s+=1){let n=c[s],p=i.api[n];yield Qe(p,n,i,e);}}),Tr=l=>d(null,null,function*(){let i=$t(),c=l.apiName?[l.apiName]:Object.keys(i.api);for(let s of c)if(!i.api[s])throw new Error(`API "${s}" not found in configuration. Available APIs: ${Object.keys(i.api).join(", ")}`);Ge();for(let s of c){let n=i.api[s];yield Qe(n,s,i);}let e=(i==null?void 0:i.folder)||"api";for(let s of c){let n=dt(s);if(n.length===0){continue}`${n.length}${s}`;let p=a(a(a(a(b(a({enabled:true},i.clientGeneration||{}),{type:l.type}),l.outputDir&&{outputDir:l.outputDir}),l.baseURL&&{baseURL:l.baseURL}),l.tags&&{tags:l.tags}),l.endpoints&&{endpoints:l.endpoints});yield ht(n,i,p,s,V.join(Ue,e));}}),Ar=()=>d(null,null,function*(){let{interactiveInit:l}=yield import('./interactive-init-DZKTNNQK.mjs');yield l();});export{Tr as GenerateClient,Er as Init,Ar as InteractiveInit,Te as JSONStringify,ye as capitalize,rt as createCustomCodeMarker,At as extractCustomCode,it as getEndpointDetails,Ft as getNestedValue,ot as isJson,Tt as isYamlString,qe as mergeCustomCode,ve as renderTypeRefMD,Lt as variableName,tt as variableNameChar,at as yamlStringToJson};
|
|
1
|
+
import {o}from'./chunk-TTLQP4UN.mjs';export{b as ConfigNotFoundError,c as ConfigParseError,d as ConfigValidationError,k as GenerateClient,h as GenerationError,j as Init,n as InteractiveInit,m as ListEndpoints,a as OpenApiSyncError,e as SpecFetchError,g as SpecParseError,f as SpecReadError,i as UnknownApiError,l as ValidateConfig}from'./chunk-TTLQP4UN.mjs';export{i as JSONStringify,g as capitalize,m as createCustomCodeMarker,l as extractCustomCode,h as getEndpointDetails,k as getNestedValue,d as isJson,e as isYamlString,n as mergeCustomCode,j as renderTypeRefMD,a as variableName,b as variableNameChar,f as yamlStringToJson}from'./chunk-L52BXDAC.mjs';import'./chunk-VLACEFT4.mjs';o();
|