@redocly/cli 2.60.0 → 2.62.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.
Files changed (141) hide show
  1. package/THIRD_PARTY_NOTICES +24 -3
  2. package/lib/chunks/{AP2GA7RS.js → 22EANOP2.js} +87 -87
  3. package/lib/chunks/{B5GZ7KU2.js → 2EP764NP.js} +1 -1
  4. package/lib/chunks/2OVI7BIW.js +105 -0
  5. package/lib/chunks/{GYKYFMW3.js → 2XK7ML3U.js} +1 -1
  6. package/lib/chunks/{DAAOXDSB.js → 37WWN4MA.js} +1 -1
  7. package/lib/chunks/{IAN3UOJT.js → 3C6UUCEW.js} +1 -1
  8. package/lib/chunks/{S27TE7KZ.js → 3DEJQSYG.js} +1 -1
  9. package/lib/chunks/{SDNESV5E.js → 3JYY42DL.js} +1 -1
  10. package/lib/chunks/{SNR3DAVL.js → 4WO6ZSKT.js} +1 -1
  11. package/lib/chunks/53INGMTO.js +20 -0
  12. package/lib/chunks/5NOJ76EP.js +9 -0
  13. package/lib/chunks/{SXOXAG7R.js → 5PG3ST2N.js} +2 -2
  14. package/lib/chunks/{BHUCIWQF.js → 66GKT2TZ.js} +1 -1
  15. package/lib/chunks/{V46KUEYR.js → 6DO6IN4A.js} +1 -1
  16. package/lib/chunks/{2F2YM4RD.js → 6EGJEFXO.js} +1 -1
  17. package/lib/chunks/{MJYI42E6.js → 6NB3FKVN.js} +8 -8
  18. package/lib/chunks/{GHPOEF7A.js → 75SLMDAN.js} +1 -1
  19. package/lib/chunks/{CAJM6OL3.js → AB2EMYEK.js} +1 -1
  20. package/lib/chunks/{PKYNMOKV.js → AZO6SCNH.js} +1 -1
  21. package/lib/chunks/{LF35KJ5M.js → B2J7WNDG.js} +1 -1
  22. package/lib/chunks/C67OKMFJ.js +11 -0
  23. package/lib/chunks/{ZJAFKITR.js → DC2HDHGE.js} +1 -1
  24. package/lib/chunks/{XZKUPNLZ.js → DFWXX7E2.js} +1 -1
  25. package/lib/chunks/{HFGKPU2P.js → FDMXHRDK.js} +1 -1
  26. package/lib/chunks/{SL6UQOKE.js → G5N3UXMR.js} +1 -1
  27. package/lib/chunks/{HVO5F4MP.js → GVQMC2WB.js} +1 -1
  28. package/lib/chunks/{RDMFHSDB.js → HBENVUR4.js} +1 -1
  29. package/lib/chunks/HN2ZK7LZ.js +20 -0
  30. package/lib/chunks/I6AAWNTY.js +20 -0
  31. package/lib/chunks/{HSHAARAO.js → KPPPJNVL.js} +1 -1
  32. package/lib/chunks/{52MW7SRF.js → KRCCY64H.js} +1 -1
  33. package/lib/chunks/LNYTDBAU.js +12 -0
  34. package/lib/chunks/{4XDEFJCF.js → LRLGVYCG.js} +1 -1
  35. package/lib/chunks/{3MPID4OC.js → LVGVWPDB.js} +1 -1
  36. package/lib/chunks/{XHDOW23C.js → MNH2K4WM.js} +1 -1
  37. package/lib/chunks/{J4NCFMOR.js → N3GO4LRW.js} +1 -1
  38. package/lib/chunks/{GD6WKI2C.js → NBI4EQPC.js} +1 -1
  39. package/lib/chunks/{G4ZIYGF5.js → NENSYJQB.js} +1 -1
  40. package/lib/chunks/NFRA6IE2.js +7 -0
  41. package/lib/chunks/{O5WCU6SC.js → OMIM3KH6.js} +10 -10
  42. package/lib/chunks/{YNPWONFN.js → OP7NIAI7.js} +1 -1
  43. package/lib/chunks/{CKZ35ARL.js → OT7Y7FIM.js} +1 -1
  44. package/lib/chunks/{ACVFQG4D.js → PTNNX4IU.js} +1 -1
  45. package/lib/chunks/{UPHYYNN3.js → PXCT44HL.js} +5 -5
  46. package/lib/chunks/{HQUG6XPO.js → QAUXTHD6.js} +2 -2
  47. package/lib/chunks/{N4AA4DRD.js → R2TPTKNR.js} +1 -1
  48. package/lib/chunks/{UXSV2J6V.js → REIGI2Y7.js} +1 -1
  49. package/lib/chunks/{S5G22GL5.js → RGU6OZYB.js} +1 -1
  50. package/lib/chunks/{W3K4YAMS.js → RPHIT72T.js} +1 -1
  51. package/lib/chunks/{7C244K4X.js → RUIEI3YV.js} +1 -1
  52. package/lib/chunks/{NADFEIIN.js → S3STDXJN.js} +1 -1
  53. package/lib/chunks/{DJWI7SF7.js → S6NFOZ34.js} +1 -1
  54. package/lib/chunks/{VCV3FKMW.js → SLQPKXO2.js} +1 -1
  55. package/lib/chunks/{4WAQNM63.js → SS6PCAMM.js} +58 -12
  56. package/lib/chunks/{CEPC3LL4.js → SXBAAS4M.js} +1 -1
  57. package/lib/chunks/{7ED6ZTTH.js → SYWAPWW7.js} +1 -1
  58. package/lib/chunks/{S46ENZHC.js → T4Y6M5MJ.js} +1 -1
  59. package/lib/chunks/{O4RAFGZA.js → TBZEEKTV.js} +1 -1
  60. package/lib/chunks/{HNKSHJLU.js → TF4PPK4N.js} +1 -1
  61. package/lib/chunks/TWWNWQRB.js +7 -0
  62. package/lib/chunks/{EXCIOEBN.js → US7X4XPD.js} +1 -1
  63. package/lib/chunks/VGM6NIVC.js +8 -0
  64. package/lib/chunks/{QGUZ4KFX.js → VX2VONNO.js} +1 -1
  65. package/lib/chunks/{DTMC35L3.js → VXLODB3S.js} +1 -1
  66. package/lib/chunks/{4HEJ6GQB.js → WEOCCL26.js} +2 -2
  67. package/lib/chunks/{Q526MFO3.js → WQ3XMPU7.js} +1 -1
  68. package/lib/chunks/{2U6O26CV.js → XJE2OFDN.js} +116 -16
  69. package/lib/chunks/{WFIIXHF3.js → XJTGJYVS.js} +1 -1
  70. package/lib/chunks/YDVWNFMS.js +24 -0
  71. package/lib/chunks/{HZZP3BZQ.js → YPYZCXVX.js} +1 -1
  72. package/lib/chunks/{72ZX5WSN.js → ZYQDPQVA.js} +1 -1
  73. package/lib/eject-assets/AGENTS.md +24 -23
  74. package/lib/eject-assets/generators/cli/docs.ts +1 -1
  75. package/lib/eject-assets/generators/cli/engine-source.ts +1 -1
  76. package/lib/eject-assets/generators/cli/index.ts +2 -2
  77. package/lib/eject-assets/generators/cli/render.ts +1 -1
  78. package/lib/eject-assets/generators/go/client.ts +1 -1
  79. package/lib/eject-assets/generators/go/descriptor.ts +1 -1
  80. package/lib/eject-assets/generators/go/index.ts +2 -2
  81. package/lib/eject-assets/generators/go/models.ts +1 -1
  82. package/lib/eject-assets/generators/go/naming.ts +1 -1
  83. package/lib/eject-assets/generators/go/operations.ts +35 -3
  84. package/lib/eject-assets/generators/go/pagination.ts +1 -1
  85. package/lib/eject-assets/generators/go/types.ts +1 -1
  86. package/lib/eject-assets/generators/mock/faker.ts +1 -1
  87. package/lib/eject-assets/generators/mock/index.ts +2 -2
  88. package/lib/eject-assets/generators/mock/render.ts +1 -1
  89. package/lib/eject-assets/generators/mock/sample.ts +1 -1
  90. package/lib/eject-assets/generators/mock/values.ts +1 -1
  91. package/lib/eject-assets/generators/php/client.ts +1 -1
  92. package/lib/eject-assets/generators/php/descriptor.ts +1 -1
  93. package/lib/eject-assets/generators/php/index.ts +2 -2
  94. package/lib/eject-assets/generators/php/models.ts +1 -1
  95. package/lib/eject-assets/generators/php/naming.ts +1 -1
  96. package/lib/eject-assets/generators/php/operations.ts +21 -3
  97. package/lib/eject-assets/generators/php/pagination.ts +1 -1
  98. package/lib/eject-assets/generators/php/types.ts +1 -1
  99. package/lib/eject-assets/generators/python/client.ts +1 -1
  100. package/lib/eject-assets/generators/python/descriptor.ts +1 -1
  101. package/lib/eject-assets/generators/python/index.ts +2 -2
  102. package/lib/eject-assets/generators/python/models.ts +1 -1
  103. package/lib/eject-assets/generators/python/naming.ts +1 -1
  104. package/lib/eject-assets/generators/python/operations.ts +19 -6
  105. package/lib/eject-assets/generators/python/pagination.ts +1 -1
  106. package/lib/eject-assets/generators/python/types.ts +1 -1
  107. package/lib/eject-assets/generators/swr/index.ts +2 -2
  108. package/lib/eject-assets/generators/swr/render.ts +1 -1
  109. package/lib/eject-assets/generators/tanstack-query/index.ts +2 -2
  110. package/lib/eject-assets/generators/tanstack-query/render.ts +1 -1
  111. package/lib/eject-assets/generators/transformers/index.ts +2 -2
  112. package/lib/eject-assets/generators/transformers/render.ts +1 -1
  113. package/lib/eject-assets/generators/typescript/banner.ts +1 -1
  114. package/lib/eject-assets/generators/typescript/client.ts +1 -1
  115. package/lib/eject-assets/generators/typescript/descriptor.ts +1 -1
  116. package/lib/eject-assets/generators/typescript/index.ts +2 -2
  117. package/lib/eject-assets/generators/typescript/inline-runtime.ts +1 -1
  118. package/lib/eject-assets/generators/typescript/operation-signature.ts +1 -1
  119. package/lib/eject-assets/generators/typescript/operation-types.ts +1 -1
  120. package/lib/eject-assets/generators/typescript/operations.ts +3 -4
  121. package/lib/eject-assets/generators/typescript/response-headers.ts +1 -1
  122. package/lib/eject-assets/generators/typescript/type-guards.ts +1 -1
  123. package/lib/eject-assets/generators/typescript/types.ts +1 -1
  124. package/lib/eject-assets/generators/zod/index.ts +2 -2
  125. package/lib/eject-assets/generators/zod/schemas.ts +1 -1
  126. package/lib/eject-assets/skills/client-generators/SKILL.md +24 -23
  127. package/lib/eject-assets/skills/go-generator/SKILL.md +11 -0
  128. package/lib/eject-assets/skills/php-generator/SKILL.md +16 -0
  129. package/lib/eject-assets/skills/python-generator/SKILL.md +13 -0
  130. package/lib/eject-assets/skills/typescript-generator/SKILL.md +16 -0
  131. package/lib/index.js +55 -55
  132. package/package.json +1 -1
  133. package/lib/chunks/BZBFESBB.js +0 -11
  134. package/lib/chunks/DJXBNZCO.js +0 -7
  135. package/lib/chunks/GC26XZYZ.js +0 -20
  136. package/lib/chunks/IJ43XWPG.js +0 -20
  137. package/lib/chunks/MCJLOALK.js +0 -22
  138. package/lib/chunks/OKTLNLO3.js +0 -7
  139. package/lib/chunks/PGZIUA7J.js +0 -105
  140. package/lib/chunks/W7VT3BOM.js +0 -9
  141. package/lib/chunks/XQA4EEZA.js +0 -20
@@ -1,9 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __pathDirname } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- var __filename = __fileURLToPath(import.meta.url);
6
- var __dirname = __pathDirname(__filename);
7
- import{a as ue}from"./LRUXN6H5.js";import{Aa as Y,j as b,l as A,o as z,oa as m,p as H,ta as q}from"./AP2GA7RS.js";import{e as ce}from"./RFWIIJFG.js";var S=ce(ue(),1);function V(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function K(n){let t=process.env.NO_PROXY||process.env.no_proxy;if(!t)return!1;let e=t.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!1;let r;try{r=new URL(n).hostname.toLowerCase()}catch{return!1}return e.some(o=>!!(o==="*"||r===o||o.startsWith(".")&&r.endsWith(o)||!o.startsWith(".")&&r.endsWith("."+o)))}var G=async(n,{timeout:t,...e}={})=>{let r=V(),o=r&&!K(n),s,i=t?{connect:{timeout:t}}:{};return o?s=new S.ProxyAgent({uri:r,...i}):t&&(s=new S.Agent(i)),await fetch(n,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:s})};var le=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function X(){let n=process.env.REDOCLY_ENVIRONMENT?.trim();return n&&le.test(n)?n:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},T=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=X(),o={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let s=await G(t,{...e,headers:o});return this.collectSunsetWarning(s),s}catch(s){let i="Failed to fetch.";throw s.cause&&(i+=` Caused by ${s.cause.message||s.cause.name}.`),(s.code||s.cause?.code)&&(i+=` Code: ${s.code||s.cause?.code}`),new Error(i)}}collectSunsetWarning(t){let e=this.getSunsetDate(t);if(!e)return;let r=new Date(e);e>Date.now()?this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!1}):this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!0})}getSunsetDate(t){let{headers:e}=t;if(!e)return;let r=e.get("sunset")||e.get("Sunset");if(r)return Date.parse(r)}},U=class{client;domain;apiKey;constructor(t,e,r){this.client=t,this.domain=e,this.apiKey=r}async getParsedResponse(t){let e=await t.json();if(t.ok)return e;throw new u(`${e.title||t.statusText||"Unknown error"}.`,t.status)}},N=class extends U{async find(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return r.status===404?void 0:await this.getParsedResponse(r)}catch(r){let o=`Failed to fetch project. ${r.message}`;throw r instanceof u?new u(o,r.status):new Error(o)}}},j=class extends U{async getDefaultBranch(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/source`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return(await this.getParsedResponse(r)).branchName}catch(r){let o=`Failed to fetch default branch. ${r.message}`;throw r instanceof u?new u(o,r.status):new Error(o)}}async upsert(t,e,r){try{let o=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/remotes`,{timeout:6e3,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(o)}catch(o){let s=`Failed to upsert remote. ${o.message}`;throw o instanceof u?new u(s,o.status):new Error(s)}}async push(t,e,r,o){let s=new globalThis.FormData;s.append("remoteId",r.remoteId),s.append("commit[message]",r.commit.message),s.append("commit[author][name]",r.commit.author.name),s.append("commit[author][email]",r.commit.author.email),s.append("commit[branchName]",r.commit.branchName),r.commit.url&&s.append("commit[url]",r.commit.url),r.commit.namespace&&s.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&s.append("commit[sha]",r.commit.sha),r.commit.repository&&s.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&s.append("commit[createdAt]",r.commit.createdAt);for(let i of o){let a=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await de(i.stream)]);s.append(`files[${i.path}]`,a,i.path)}r.isMainBranch&&s.append("isMainBranch","true"),r.replace&&s.append("replace","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:s});return await this.getParsedResponse(i)}catch(i){let a=`Failed to push. ${i.message}`;throw i instanceof u?new u(a,i.status):new Error(a)}}async getPush({organizationId:t,projectId:e,pushId:r}){try{let o=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes/${r}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return await this.getParsedResponse(o)}catch(o){let s=`Failed to get push status. ${o.message}`;throw o instanceof u?new u(s,o.status):new Error(s)}}},g=class{apiClient;projects;remotes;constructor({domain:t,apiKey:e,command:r,version:o}){this.apiClient=new T(r,o),this.projects=new N(this.apiClient,t,e),this.remotes=new j(this.apiClient,t,e)}getSunsetWarning(){return Z(this.apiClient.sunsetWarnings)}};function Z(n){let[t]=[...n].sort((e,r)=>e.isSunsetExpired!==r.isSunsetExpired?e.isSunsetExpired?-1:1:e.sunsetDate>r.sunsetDate?1:-1);return t}async function de(n){let t=[];for await(let e of n)t.push(e);return Buffer.concat(t)}function he(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var P={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function fe(){return process.env.REDOCLY_DOMAIN||P.us}var J=pe((n,t)=>{try{let e=t||n?.resolvedConfig.residency;return me(e)?P[e]:e?new URL(e).origin:n?.resolvedConfig.scorecard?.fromProjectUrl?new URL(n.resolvedConfig.scorecard.fromProjectUrl).origin:P.us}catch{throw new E}});function D(n){try{J(void 0,n)}catch{return!1}return!0}function pe(n){return(...t)=>{let e=n(...t);if(!e.startsWith("https://"))throw new E;return e}}var E=class extends Error{constructor(){super("Invalid Reunite URL")}};function me(n){return typeof n=="string"&&n in P}import{Buffer as O}from"node:buffer";import F from"node:crypto";import{mkdirSync as ge,existsSync as ee,writeFileSync as we,readFileSync as ye,rmSync as ve}from"node:fs";import{homedir as Te}from"node:os";import te from"node:path";import*as Q from"node:child_process";var w=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new T("login",e)}async run(t){let e=await this.getDeviceCode();t?.({verificationUri:e.verificationUri,verificationUriComplete:e.verificationUriComplete,userCode:e.userCode}),this.openBrowser(e.verificationUriComplete);let r=await this.pollingAccessToken(e.deviceCode,e.interval,e.expiresIn);return this.withResidency(r)}openBrowser(t){if(!/^https?:\/\//.test(t))return;let[e,r]=process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",t]]:process.platform==="darwin"?["open",[t]]:["xdg-open",[t]];Q.spawn(e,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}async verifyToken(t){try{return!!(await this.sendRequest("/session","GET",void 0,{Cookie:`accessToken=${t};`})).user}catch{return!1}}async verifyApiKey(t){try{return!!(await this.sendRequest("/api-keys-verify","POST",{apiKey:t})).success}catch{return!1}}async refreshToken(t){let e=await this.sendRequest("/device-rotate-token","POST",{grant_type:"refresh_token",client_name:this.clientName,refresh_token:t});if(!e.access_token)throw new Error("Failed to refresh token");return this.withResidency({access_token:e.access_token,refresh_token:e.refresh_token,expires_in:e.expires_in})}async pollingAccessToken(t,e,r){return new Promise((o,s)=>{let i=setInterval(async()=>{let c=await this.getAccessToken(t);c.access_token&&(clearInterval(i),clearTimeout(a),o(c)),c.error&&c.error!=="authorization_pending"&&(clearInterval(i),clearTimeout(a),s(c.error_description))},e*1e3),a=setTimeout(async()=>{clearInterval(i),clearTimeout(a),s("Authorization has expired. Please try again.")},r*1e3)})}async getAccessToken(t){return await this.sendRequest("/device-token","POST",{client_name:this.clientName,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}async getDeviceCode(){let{device_code:t,user_code:e,verification_uri:r,verification_uri_complete:o,interval:s=10,expires_in:i=300}=await this.sendRequest("/device-authorize","POST",{client_name:this.clientName});return{deviceCode:t,userCode:e,verificationUri:r,verificationUriComplete:o,interval:s,expiresIn:i}}async sendRequest(t,e="GET",r=void 0,o={}){let s=`${this.baseUrl}/api${t}`,i=await this.apiClient.request(s,{body:r&&JSON.stringify(r),method:e,headers:{"Content-Type":"application/json",...o},timeout:6e3});return i.status===204?{success:!0}:await i.json()}withResidency(t){return{...t,residency:this.baseUrl}}};var xe="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",re="aes-256-cbc",k=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=Te();this.credentialsFolderPath=te.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=te.join(this.credentialsFolderPath,this.credentialsFileName),this.key=F.createHash("sha256").update(`${this.credentialsFolderPath}${xe}`).digest(),this.iv=F.createHash("md5").update(this.credentialsFolderPath).digest(),ge(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let o=await new w(t,this.version).run(e);if(!o)throw new Error("Failed to login. No credentials received.");await this.saveCredentials(o)}async logout(){try{this.removeCredentials()}catch{}}async isAuthorized(t,e){return e?new w(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new w(t,this.version),r=await this.readCredentials();if(!r||!D(t)||r.residency&&r.residency!==t)return null;if(await e.verifyToken(r.access_token))return r.access_token;try{let s=await e.refreshToken(r.refresh_token);return await this.saveCredentials(s),s.access_token}catch{return null}};async saveCredentials(t){try{let e=this.encryptCredentials(t);we(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!ee(this.credentialsFilePath))return null;try{let t=ye(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){ee(this.credentialsFilePath)&&ve(this.credentialsFilePath)}encryptCredentials(t){let e=F.createCipheriv(re,this.key,this.iv);return O.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=F.createDecipheriv(re,this.key,this.iv),r=O.concat([e.update(O.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};import*as y from"node:fs";import*as h from"node:path";var Ce=/\/orgs\/([^/]+)\/projects\//,Pe=[401,403];async function x(n,{organization:t,project:e,onSlugDeprecated:r}){let o=await Ee(n,t,e);if(!o)return{organizationId:t,projectId:e};let s={organizationId:Re(o.uri),projectId:o.id};return(s.organizationId!==t||s.projectId!==e)&&r?.(s),s}async function Ee(n,t,e){try{let r=await n.projects.find(t,e);if(!r)throw new u(`Project "${e}" was not found in organization "${t}". Use the IDs from the organization and project settings in Reunite.`,404);return r}catch(r){if(r instanceof u&&Pe.includes(r.status))return;throw r}}function Re(n){let t=n.match(Ce)?.[1];if(!t)throw new Error(`Could not read the organization ID from the project URI "${n}".`);return t}async function $e({domain:n,apiKey:t,organization:e,project:r,mountPath:o,files:s,defaultBranch:i,commit:a,version:c,replace:R,onUploadStart:$,onSunsetWarning:v,onSlugDeprecated:I}){let f=new g({domain:n,apiKey:t,command:"push",version:c});try{let{organizationId:d,projectId:l}=await x(f,{organization:e,project:r,onSlugDeprecated:I}),M=await f.remotes.getDefaultBranch(d,l),p=await f.remotes.upsert(d,l,{mountBranchName:M,mountPath:o});$?.(p);let{id:C}=await f.remotes.push(d,l,{remoteId:p.id,commit:a,isMainBranch:i===a.branchName,replace:R},s.map(W=>({path:z(W.name),stream:y.createReadStream(W.path)})));return{pushId:C,organizationId:d,projectId:l}}finally{let d=f.getSunsetWarning();d&&v?.(d)}}function Se(n,t){let e={};for(let o of n)if(y.statSync(o).isDirectory()){let s=o;ne(s,[]).forEach(a=>r(a,s))}else r(o,h.dirname(o));function r(o,s){let i=h.relative(s,o);e[i]&&t?.(e[i],o),e[i]=o}return Object.entries(e).map(([o,s])=>({name:o,path:h.resolve(s)}))}function ne(n,t){let e=y.readdirSync(n);for(let r of e){let o=h.join(n,r);y.statSync(o).isDirectory()?t=ne(o,t):t.push(o)}return t}async function se({operation:n,condition:t,onConditionNotMet:e,startTime:r=Date.now(),retryTimeoutMs:o=6e5,retryIntervalMs:s=5e3}){async function i(){let a=await n();if(t(a))return a;if(Date.now()-r>o)throw new Error("Timeout exceeded.");return await e?.(a),await b(s),i()}return i()}var _e=1200,Ue=5e3,Fe=["pending","running"];async function Ie(n){let t=oe(n);try{let e=await x(t,n);return await ae(t,e,n.pushId)}finally{ie(t,n)}}async function Ae({buildType:n,maxExecutionTime:t=_e,retryIntervalMs:e=Ue,startTime:r=Date.now(),onRetry:o,...s}){let i=oe(s);try{let a=await x(i,s);return await se({operation:()=>ae(i,a,s.pushId),condition:c=>!Fe.includes(c.status[n].deploy.status),onConditionNotMet:o,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{ie(i,s)}}function oe({domain:n,apiKey:t,version:e}){return new g({domain:n,apiKey:t,command:"push-status",version:e})}function ie(n,{onSunsetWarning:t}){let e=n.getSunsetWarning();e&&t?.(e)}function ae(n,{organizationId:t,projectId:e},r){return n.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function Ne({projectUrl:n,auth:t,isApiKey:e=!1,onDebug:r}){let o=je(n);if(!o)throw new m(`Invalid project URL format: ${n}`);try{let s=await De({...o,auth:t,isApiKey:e,onDebug:r}),i=s.config.scorecardClassic||s.config.scorecard;if(!i)throw new Error("No scorecard configuration found.");let a=s.config.pluginsUrl,c=a?await Oe(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(s){throw new m(s instanceof Error?s.message:String(s))}}function je(n){let t=new URL(n),e=t.pathname.match(/\/org\/(?<orgSlug>[^/]+)\/project\/(?<projectSlug>[^/]+)/);if(!e?.groups)return;let{orgSlug:r,projectSlug:o}=e.groups;return{residency:t.origin,orgSlug:r,projectSlug:o}}async function De({residency:n,orgSlug:t,projectSlug:e,auth:r,isApiKey:o,onDebug:s}){let i=new URL(`${n}/api/orgs/${t}/projects/${e}`),a=await fetch(i,{headers:ke(r,o)});if(s?.(`Project fetch response status: ${a.status}`),a.status===401||a.status===403)throw s?.(`Authentication failed with status ${a.status}.`),s?.("Check that your credentials are valid and have the necessary permissions."),new Error(`Unauthorized access to project: ${e}. Please check your credentials.`);if(a.status!==200)throw new Error(`Failed to fetch project: ${e}. Status: ${a.status}`);return s?.("Successfully received project configuration."),a.json()}async function Oe(n,t){t?.(`Fetching plugins from: ${n}`);try{let e=await fetch(n);if(t?.(`Plugins fetch response status: ${e.status}`),e.status!==200){t?.("Failed to fetch plugins");return}return e.text()}catch(e){t?.(`Error fetching plugins: ${e instanceof Error?e.message:String(e)}`);return}}function ke(n,t){return t?{Authorization:`Bearer ${n}`}:{Cookie:`accessToken=${n}`}}async function L(n,t,e=[],r=[],o){let s={};for(let i of e){let a={[i.name]:{root:n,rules:t}},c=await q({apis:a,...i,plugins:r},{configPath:o});s[i.name]=c.forAlias(i.name)}return s}function B(n,t){if(n){for(let e of n)if(Object.entries(e.where?.metadata||{}).every(([o,s])=>Le(o,s,t)))return e}}function Le(n,t,e){if(t.match(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?\/(\d{4}-\d{2}-\d{2})?$/)){if(!e[n])return!1;let[r,o]=t.split("/"),s=new Date(e[n]);return!(s<new Date(r)||o&&s>new Date(o))}else if(t.match(/^\/.*\//)){if(!e[n])return!1;try{return H(t).test(e[n])}catch{throw new m(`Invalid regex in scorecard target "${n}": ${t}`)}}return e[n]===t}import{pathToFileURL as Be}from"node:url";async function Me(n,t){if(!n)return[];let e=Be(t??process.cwd()).href+"/",r=n.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var We=".redocly.com";function be(n){try{return new URL(n).hostname.toLowerCase().endsWith(We)}catch{return!1}}async function ze({apiPath:n,document:t,externalRefResolver:e,scorecardConfig:r,configPath:o,plugins:s=[],targetLevel:i,metadata:a={},onDebug:c}){let R=[],$=new Map,v=r.levels||[];if(i&&!v.some(l=>l.name===i))throw new m(`Target level "${i}" not found in the scorecard configuration levels.
8
- `);let I=B(r.targets,a)?.rules,f=await L(n,I,v,s,o||"");for(let l of v){c?.(`
9
- Validating level: "${l.name}"`),s.length>0&&c?.(`Using ${s.length} ${A("plugin",s.length)} for this level.`),c?.("Linting document against level rules...");let p=(await Y({document:t,externalRefResolver:e,config:f[l.name]})).filter(({ignored:C})=>!C).map(C=>({...C,scorecardLevel:l.name}));c?.(`Found ${p.length} ${A("problem",p.length)} for level "${l.name}".`),$.set(l.name,p),R.push(...p)}let d=He($,v,i);return{problems:R,achievedLevel:d,targetLevelAchieved:i?d===i:!0}}function He(n,t,e){let r=null;for(let o of t){if((n.get(o.name)||[]).some(a=>a.severity==="error"))return r||"Non Conformant";if(r=o.name,e&&o.name===e)return o.name}return r||"Non Conformant"}export{u as a,T as b,g as c,Z as d,he as e,P as f,fe as g,J as h,D as i,E as j,w as k,k as l,x as m,$e as n,Se as o,Ie as p,Ae as q,Ne as r,L as s,B as t,Me as u,be as v,ze as w};
@@ -1,20 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath as __fileURLToPath } from 'node:url';
3
- import { dirname as __pathDirname } from 'node:path';
4
- const require = __createRequire(import.meta.url);
5
- var __filename = __fileURLToPath(import.meta.url);
6
- var __dirname = __pathDirname(__filename);
7
- import{c as U}from"./2U6O26CV.js";import{b as R,c as L,d as Y,f as se,g as K,h as oe,i as re}from"./BZBFESBB.js";import{a as X,c as F,d as k,e as D,g as B,h as T,i as Z,j as ee,k as ne,l as H,n as te}from"./UW4UC7ZI.js";var M=F.python,j=class extends X{constructor(){super(" ")}typeName(n){return k(n,{style:"pascal",reserved:M})}memberName(n){let t=k(n,{style:"snake",reserved:M});return{identifier:t,renamed:t!==n}}identifier(n){return k(n,{style:"snake",reserved:M})}identifiers(n,t){return D(n,{style:"snake",reserved:M,taken:t})}constName(n){return k(n,{style:"screaming",reserved:M})}string(n){let t='"';for(let s of n){let r=s.codePointAt(0);s==="\\"?t+="\\\\":s==='"'?t+='\\"':s===`
8
- `?t+="\\n":s==="\r"?t+="\\r":s===" "?t+="\\t":r<32||r===127?t+=`\\x${r.toString(16).padStart(2,"0")}`:r>=55296&&r<=57343?t+=`\\u${r.toString(16).padStart(4,"0")}`:t+=s}return t+'"'}literal(n){return n==null?"None":n===!0?"True":n===!1?"False":typeof n=="number"?String(n):typeof n=="string"?this.string(n):Array.isArray(n)?`[${n.map(s=>this.literal(s)).join(", ")}]`:`{${Object.entries(n).map(([s,r])=>`${this.string(s)}: ${this.literal(r)}`).join(", ")}}`}comment(n){for(let t of H(n))this.line(t===""?"#":`# ${t}`);return this}doc(n){let t=H(n);if(t.length===0)return this;if(t.length===1)return this.line(`"""${t[0]}"""`);this.line(`"""${t[0]}`);for(let s of t.slice(1))this.line(s);return this.line('"""')}};var N=F.python,f=new j;function O(e){return f.typeName(e)}function q(e){let{identifier:n,renamed:t}=f.memberName(e);return{python:n,renamed:t}}function I(e){let n=e.services.flatMap(s=>s.operations),t=D(n.map(s=>s.name),{style:"snake",reserved:N});return n.map((s,r)=>({op:s,ident:t[r]}))}var W=["self","body","headers","timeout","retry","idempotency_key"];function ae(e){return f.literal(e)}function ie(e){if(e!==void 0)return{style:e.style,...e.param!==void 0?{param:e.param}:{},...e.nextCursor!==void 0?{next_cursor:e.nextCursor}:{},...e.hasMore!==void 0?{has_more:e.hasMore}:{},...e.limitParam!==void 0?{limit_param:e.limitParam}:{},...e.items!==void 0?{items:e.items}:{}}}function ce(e,n){let t=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let a=k(r.name,{style:"snake",reserved:N}),c=a,i=2;for(;t.has(c);)c=`${a}_${i++}`;t.add(c);let m=te(r.schema,n);return`(${f.string(r.name)}, ${f.string(c)}, ${f.string(m)})`}).join(", ")}]`}function y(e,n="string"){if(Z(e))return`Optional[${y(ee(e),n)}]`;switch(e.kind){case"scalar":if(n==="Date"&&e.scalar==="string"){if(e.metadata?.format==="date-time")return"datetime";if(e.metadata?.format==="date")return"date"}return{string:"str",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":return`List[${y(e.items,n)}]`;case"record":return`Dict[str, ${y(e.value,n)}]`;case"ref":return O(e.name);case"literal":return`Literal[${f.literal(e.value)}]`;case"enum":return{string:"str",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"union":return`Union[${e.members.map(t=>y(t,n)).join(", ")}]`;case"null":return"None";case"omit":return O(e.base);case"object":case"intersection":case"unknown":return"Any"}}function G(e,n,t,s,r,a,c,i=!1){let m=D([...n.pathParams,...n.queryParams].map(S=>S.name),{style:"snake",reserved:N,taken:W}),l=n.pathParams.map((S,v)=>({param:S,python:m[v]})),o=n.queryParams.map((S,v)=>({param:S,python:m[n.pathParams.length+v]})),d=l.map(({param:S,python:v})=>`${v}: ${y(S.schema,a)}`),u=n.requestBody?[`body: ${y(n.requestBody.schema,a)}`]:[],$=[...o.map(({param:S,python:v})=>{let A=y(S.schema,a),E=A.startsWith("Optional[")?A:`Optional[${A}]`;return`${v}: ${E} = None`}),"headers: Optional[Dict[str, str]] = None","timeout: Optional[float] = None","retry: Optional[Dict[str, Any]] = None","idempotency_key: Any = None"],h=R(n),g=L(n),x=i?`Envelope[${h===void 0?"None":y(h,a)}]`:g!==void 0?`${r?"AsyncIterator":"Iterator"}[ServerSentEvent]`:s==="result"?"Result":h===void 0?"None":y(h,a),P=r&&g===void 0?"async def":"def",p=r?"await ":"",_=r?"send_async":"send",b=["self",...d,...u,"*",...$].join(", "),w=i?`${t}_with_headers`:t;e.block(`${P} ${w}(${b}) -> ${x}:`,()=>{e.doc(i?`Like ${t}(), returning an Envelope with the declared response headers.`:n.summary),e.line(`op = _OPERATIONS["${t}"]`),e.line('auth_headers, auth_query = resolve_auth(op.get("security") or [], self._auth)'),e.line("params: Dict[str, Any] = dict(auth_query)");for(let{param:E,python:C}of o)e.block(`if ${C} is not None:`,()=>{e.line(`params[${f.string(E.name)}] = encode(${C})`)});let S=l.map(({param:E,python:C})=>`${f.string(E.name)}: ${C}`).join(", ");if(e.line(`url = build_url(self._server_url, op["path"], {${S}})`),g!==void 0){let E=g.schema!==void 0&&g.schema.kind!=="unknown"?"json":"text";e.block("def _open(extra_headers: Dict[str, str]):",()=>{e.line('return self._http.stream(op["method"], url, headers={**auth_headers, **(headers or {}), **extra_headers}, params=params, timeout=timeout)')}),e.line(`return ${r?"aiter_sse":"iter_sse"}(_open, data_kind="${E}")`);return}Y(n)&&e.line("form_data, form_files = to_multipart(body)");let v=n.requestBody?Y(n)?", data=form_data, files=form_files":", json_body=encode(body)":"";e.line(`response = ${p}${_}(self._http, self._config, op, url, method=op["method"], headers={**auth_headers, **(headers or {})}, params=params${v}, timeout=timeout, retry=retry, idempotency_key=idempotency_key)`);let A=h===void 0?"None":`decode(${y(h,a)}, _safe_json(response))`;i?(e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line(`return Envelope(data=${A}, headers=read_envelope_headers(response, ${ce(n,c)}), response=response)`)):s==="result"?(e.block("if not response.is_success:",()=>{e.line("return Result(data=None, error=_safe_json(response), response=response)")}),e.line(`return Result(data=${A}, error=None, response=response)`)):(e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line(h===void 0?"return None":`return ${A}`))}),e.blank()}function le(e,n,t,s,r,a){let c=R(n),i=c===void 0?"Any":y(c,a),m=D([...n.pathParams,...n.queryParams].map(p=>p.name),{style:"snake",reserved:N,taken:W}),l=n.pathParams.map((p,_)=>({param:p,python:m[_]})),o=n.queryParams.map((p,_)=>({param:p,python:m[n.pathParams.length+_]})),d=l.map(({param:p,python:_})=>`${_}: ${y(p.schema,a)}`),u=[...o.map(({param:p,python:_})=>{let b=y(p.schema,a),w=b.startsWith("Optional[")?b:`Optional[${b}]`;return`${_}: ${w} = None`}),"headers: Optional[Dict[str, str]] = None","timeout: Optional[float] = None","retry: Optional[Dict[str, Any]] = None"],$=["self",...d,"*",...u].join(", "),h=s?"AsyncIterator":"Iterator",g=s?"aiter_pages":"iter_pages",x=s?"aiter_items":"iter_items",P=()=>{e.line("base: Dict[str, Any] = {}");for(let{param:b,python:w}of o)e.block(`if ${w} is not None:`,()=>{e.line(`base[${f.string(b.name)}] = encode(${w})`)});let p=s?"async def":"def",_=s?"await ":"";e.block(`${p} _page(page_params: Dict[str, Any]) -> Tuple[Any, Any]:`,()=>{e.line('auth_headers, auth_query = resolve_auth(op.get("security") or [], self._auth)');let b=l.map(({param:w,python:S})=>`${f.string(w.name)}: ${S}`).join(", ");e.line(`url = build_url(self._server_url, op["path"], {${b}})`),e.line(`response = ${_}${s?"send_async":"send"}(self._http, self._config, op, url, method=op["method"], headers={**auth_headers, **(headers or {})}, params={**page_params, **auth_query}, timeout=timeout, retry=retry)`),e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line("return _safe_json(response), response")})};s?(e.block(`async def ${t}_pages(${$}) -> ${h}[${i}]:`,()=>{e.line(`op = _OPERATIONS["${t}"]`),P(),e.block(`async for page in ${g}(_page, op["pagination"], base):`,()=>{e.line(i==="Any"?"yield page":`yield decode(${i}, page)`)})}),e.blank(),e.block(`async def ${t}_items(${$}) -> ${h}[${r}]:`,()=>{e.line(`op = _OPERATIONS["${t}"]`),P(),e.block(`async for item in ${x}(_page, op["pagination"], base):`,()=>{e.line(r==="Any"?"yield item":`yield decode(${r}, item)`)})})):(e.block(`def ${t}_pages(${$}) -> ${h}[${i}]:`,()=>{e.line(`op = _OPERATIONS["${t}"]`),P(),e.line(i==="Any"?`return ${g}(_page, op["pagination"], base)`:`return (decode(${i}, page) for page in ${g}(_page, op["pagination"], base))`)}),e.blank(),e.block(`def ${t}_items(${$}) -> ${h}[${r}]:`,()=>{e.line(`op = _OPERATIONS["${t}"]`),P(),e.line(r==="Any"?`return ${x}(_page, op["pagination"], base)`:`return (decode(${r}, item) for item in ${x}(_page, op["pagination"], base))`)})),e.blank()}function me(e){return se(e).map(t=>t.kind==="literal"?f.string(t.value):q(t.name).python).join(" + ")}function de(e,n){let t=n.servers??[];if(t.length===0)return;let s=new Set;e.block("class Servers:",()=>{e.line('"""The declared servers; variables default to the values from the description."""'),e.blank(),t.forEach((r,a)=>{let c=k(r.description??`server${a+1}`,{style:"snake",reserved:N});s.has(c)&&(c=`${c}_${a+1}`),s.add(c);let i=r.variables.map(m=>`${q(m.name).python}: str = ${f.string(m.default)}`);a>0&&e.blank(),e.line("@staticmethod"),e.block(`def ${c}(${i.join(", ")}) -> str:`,()=>{e.line(`return ${me(r)}`)})})}),e.blank()}function V(e,n,t,s,r,a,c){let i=s?"AsyncClient":"Client",m=s?"httpx.AsyncClient":"httpx.Client";e.block(`class ${i}:`,()=>{e.doc(`${s?"Async ":""}client for ${n.title} (${n.version}).`),e.block(`def __init__(self, server_url: str = ${f.string(a)}, *, auth: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout: Optional[float] = None, retry: Optional[Dict[str, Any]] = None, middleware: Optional[List[Any]] = None, idempotency_key: Any = None, http_client: Optional[${m}] = None) -> None:`,()=>{e.line("self._server_url = server_url"),e.line("self._auth = auth or {}"),e.line("self._config: Dict[str, Any] = {"),e.indent(()=>{e.line('"headers": headers or {},'),e.line('"timeout": timeout,'),e.line('"retry": retry or {},'),e.line('"middleware": middleware or [],'),e.line('"idempotency_key": idempotency_key,')}),e.line("}"),e.line(`self._http = http_client or ${m}()`)}),e.blank();for(let{op:l,ident:o}of I(n)){G(e,l,o,t,s,c),L(l)===void 0&&(l.successResponseHeaders?.length??0)>0&&G(e,l,o,t,s,c,n,!0);let d=r.get(o);if(d!==void 0){let u=R(l),$=oe(u,typeof d.items=="string"?d.items:void 0,n);le(e,l,o,s,$===void 0?"Any":y($,c),c)}}}),e.blank()}function z(e){let n=new Map,t=new Set,s=[];for(let{name:a,schema:c}of e.schemas){let i=T(c,e);if(!(i===void 0||!i.cases.every(l=>B(l.schema,e)?.properties.some(o=>o.name===i.property)===!0))){for(let l of i.cases){let o=n.get(l.schemaName);if(o!==void 0&&o.value!==l.value){t.add(l.schemaName);continue}n.set(l.schemaName,{property:i.property,value:l.value})}s.push({name:a,property:i.property,members:i.cases.map(l=>l.schemaName)})}}let r=new Map;for(let a of s)a.members.some(c=>t.has(c))||r.set(a.name,q(a.property).python);for(let a of t)n.delete(a);return{pins:n,unions:r}}function fe(e,n,t,s,r,a,c){let i=r==="pydantic";i||e.line("@dataclass");let m=i?`class ${O(n)}(BaseModel):`:`class ${O(n)}:`;e.block(m,()=>{e.doc(a),i&&(e.line("model_config = ConfigDict(populate_by_name=True)"),e.blank());let l=[...t.filter(d=>d.required),...t.filter(d=>!d.required)],o=[];l.length===0&&e.line("pass");for(let d of l){let{python:u,renamed:$}=q(d.name);$&&!i&&o.push([u,d.name]);let h=$&&i?`alias=${f.string(d.name)}`:void 0,g=c?.property===d.name?`Literal[${f.literal(c.value)}]`:y(d.schema,s);if(d.required){let x=h===void 0?"":` = Field(${h})`;e.line(`${u}: ${g}${x}`)}else{let x=g.startsWith("Optional[")?g:`Optional[${g}]`,P=h===void 0?"None":`Field(default=None, ${h})`;e.line(`${u}: ${x} = ${P}`)}}if(o.length>0){e.blank(),e.line("# Python field name -> wire (JSON) name, for (de)serialization.");let d=o.map(([u,$])=>`"${u}": ${f.string($)}`).join(", ");e.line(`_field_map: ClassVar[Dict[str, str]] = {${d}}`)}}),e.blank(),e.blank()}function J(e,n="string",t="dataclass"){let s=new j,{pins:r,unions:a}=t==="pydantic"?z(e):{pins:new Map,unions:new Map};s.line("from __future__ import annotations"),s.blank(),t==="dataclass"&&s.line("from dataclasses import dataclass"),s.line("from enum import Enum");let c=["Any","AsyncIterator","Dict","Iterator","List","Literal","Optional","Tuple","Union"];t==="dataclass"&&c.splice(2,0,"ClassVar"),a.size>0&&c.unshift("Annotated"),s.line(`from typing import ${c.join(", ")}`),t==="pydantic"&&s.line("from pydantic import BaseModel, ConfigDict, Field"),n==="Date"&&s.line("from datetime import date, datetime"),s.blank(),s.blank();let i=[];for(let{name:m,schema:l}of e.schemas){let o=ne(l);if(o!==void 0){let d=o.scalar==="string"?"str, Enum":"int, Enum";s.block(`class ${O(m)}(${d}):`,()=>{s.doc(l.description),o.values.forEach((u,$)=>{s.line(`${o.memberNames[$]} = ${f.literal(u)}`)})}),s.blank(),s.blank();continue}if(l.kind==="object"||l.kind==="intersection"){let d=B(l,e);if(d!==void 0){fe(s,m,d.properties,n,t,d.description??l.description,r.get(m));continue}}i.push(()=>{let d=T(l,e);if(d!==void 0){let h=d.cases.map(g=>`${g.value} -> ${O(g.schemaName)}`).join(", ");s.line(`# Discriminated by "${d.property}": ${h}`)}let u=a.get(m),$=u===void 0?y(l,n):`Annotated[${y(l,n)}, Field(discriminator=${f.string(u)})]`;s.line(`${O(m)} = ${$}`),s.blank()})}for(let m of i)m();return s.toString()}function pe(e,n){let t=[];for(let{name:s,schema:r}of e.schemas){if(n.has(s))continue;let a=T(r,e);if(a===void 0)continue;let c=a.cases.map(i=>`${f.string(i.value)}: ${O(i.schemaName)}`).join(", ");t.push(`DISCRIMINATORS[${O(s)}] = (${f.string(a.property)}, {${c}})`)}return t}var nn={type:"object",properties:{models:{enum:["dataclass","pydantic"],default:"dataclass",description:"Model style: standard-library dataclasses (default, httpx is the only dependency), or pydantic BaseModel classes (adds pydantic)."}},additionalProperties:!1};function Q(e){let n=e.lastIndexOf("/")>=0?"/":"\\",t=e.lastIndexOf(n),s=t>=0?e.slice(0,t+1):"",r=(t>=0?e.slice(t+1):e).replace(/\.[^.]+$/,"");return`${s}${k(r,{style:"snake",reserved:N})}.py`}var tn=({model:e,output:n,banner:t,emit:s,options:r,pagination:a})=>{let c=s.errorMode??"throw",i=s.dateType??"string",m=r?.models??"dataclass",l=m==="pydantic"?z(e):void 0,o=new j;if(o.line(`# Generated by @redocly/client-generator (python) from "${e.title}" ${e.version}.`),o.line("# Do not edit by hand \u2014 regenerate with `redocly generate-client`."),o.line(m==="pydantic"?"# Requires Python >= 3.9, httpx, and pydantic: pip install httpx pydantic":"# Requires Python >= 3.9 and httpx: pip install httpx"),o.blank(),o.line(J(e,i,m).trimEnd()),o.blank(),o.blank(),de(o,e),s.runtime==="module"){o.line("# \u2500\u2500\u2500 Runtime (real modules beside this file, written by the same run) \u2500\u2500\u2500");for(let p of Object.keys(U))o.line(`from ${p.replace(/\.py$/,"")} import *`);o.blank(),o.blank()}else{o.line("# \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator python runtime) \u2500\u2500\u2500");for(let p of Object.values(U)){let _=p.split(`
9
- `).filter(b=>!b.startsWith("from __future__")&&!b.startsWith("from ._")).join(`
10
- `).trim();o.line(_),o.blank()}o.blank()}let d=pe(e,new Set(l?.unions.keys()));if(d.length>0){o.line("# Discriminated unions dispatch by their property inside decode().");for(let p of d)o.line(p);o.blank()}o.block("def _safe_json(response: httpx.Response) -> Any:",()=>{o.block("try:",()=>{o.line("return response.json()")}),o.block("except Exception:",()=>{o.line("return None")})}),o.blank();let u=new Map;for(let{op:p,ident:_}of I(e))u.set(_,ie(a?.get(p.name)?.spec));o.line("_OPERATIONS = {"),o.indent(()=>{for(let{op:p,ident:_}of I(e)){let b={id:p.specName??p.name,method:p.method.toUpperCase(),path:p.path,...K(p,e).length>0?{security:K(p,e)}:{},...u.get(_)!==void 0?{pagination:u.get(_)}:{}};o.line(`"${_}": ${ae(b)},`)}}),o.line("}"),o.blank(),o.blank();let $=s.serverUrl??e.serverUrl??"";V(o,e,c,!1,u,$,i),V(o,e,c,!0,u,$,i);let h={path:Q(n.path),content:o.toString()};if(s.runtime!=="module")return[h];let g=t.map(p=>`# ${p}`).join(`
11
- `),x=Q(n.path).replace(/[^\\/]+$/,""),P=Object.entries(U).map(([p,_])=>({path:`${x}${p}`,content:`${g}
12
-
13
- ${_.split(`
14
- `).map(b=>b.startsWith("from ._")?b.replace("from ._","from _"):b).join(`
15
- `).trim()}
16
- `}));return[h,...P]};function ue(e,n){let t=Q(n.outputPath).replace(/^.*[\\/]/,"").replace(/\.py$/,""),s=I(n.model).find(a=>a.op.name===e.name)?.ident??k(e.name,{style:"snake",reserved:N}),r=[...e.pathParams.map(a=>{let c=k(a.name,{style:"snake",reserved:N});return`${c}="<${c}>"`}),...e.queryParams.filter(a=>a.required).map(a=>`${k(a.name,{style:"snake",reserved:N})}=...`),...e.requestBody?["body=..."]:[]];return{lang:"python",label:"Python SDK",source:`from ${t} import Client
17
-
18
- client = Client()
19
- result = client.${s}(${r.join(", ")})
20
- `}}var sn=({model:e,output:n,emit:t,pagination:s})=>[{path:n.path.replace(/\.[^.\\/]+$/,".python.md"),content:re(e,{title:`${e.title} Python SDK reference`,frontmatter:t.docsFrontmatter===!0,language:{name:"python",label:"Python",fence:"python",requires:"The SDK needs `httpx`."},sample:r=>ue(r,{model:e,emit:t,outputPath:n.path}),paginated:new Set(s?.keys()??[])})}];export{y as a,J as b,nn as c,tn as d,ue as e,sn as f};