@redocly/cli 2.71.1 → 2.72.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 +1 -1
- package/THIRD_PARTY_NOTICES +29 -7
- package/lib/chunks/{Q3IJURM3.js → 2DXUH2SS.js} +1 -1
- package/lib/chunks/{UYZXI3NO.js → 2X2KHSF3.js} +1 -1
- package/lib/chunks/{CX76LEFC.js → 42X6IAVM.js} +1 -1
- package/lib/chunks/44US4AGQ.js +13 -0
- package/lib/chunks/{DP3T6VZX.js → 4AXMK6B2.js} +1 -1
- package/lib/chunks/4ZCKAKVF.js +199 -0
- package/lib/chunks/5F7XFPS7.js +8 -0
- package/lib/chunks/{WJ3YDHQA.js → 6234PJEZ.js} +1 -1
- package/lib/chunks/{TNRIBQHV.js → 62SOICN7.js} +1 -1
- package/lib/chunks/{BPSWCUZE.js → 6JFL6L56.js} +1 -1
- package/lib/chunks/{NEWT5A6S.js → 6RTITFQA.js} +1 -1
- package/lib/chunks/{2IUGP2IH.js → 6XDKNFYM.js} +3 -3
- package/lib/chunks/{IYV7EO2J.js → 76AJ5P4Y.js} +1 -1
- package/lib/chunks/{6TCEQRVX.js → 7HTKK26B.js} +1 -1
- package/lib/chunks/{BXXX3ZCV.js → A7XJ7Y3N.js} +1 -1
- package/lib/chunks/AB4FYNJN.js +22 -0
- package/lib/chunks/BJ6Z66KZ.js +7 -0
- package/lib/chunks/{3N7LKSDD.js → BL2KWYMY.js} +1 -1
- package/lib/chunks/{PBQOGZ5C.js → BTLP7Z6A.js} +1 -1
- package/lib/chunks/{5DW3QRJB.js → BXMYSHQY.js} +2 -2
- package/lib/chunks/{ILYXMZRT.js → BY22HEXP.js} +1 -1
- package/lib/chunks/D2BBHPMR.js +7 -0
- package/lib/chunks/{ACAPGKSR.js → D3C6XIMY.js} +3 -3
- package/lib/chunks/{INGAWMLB.js → DNDYWJHC.js} +1 -1
- package/lib/chunks/{KJIUDCYZ.js → E6QTRG6I.js} +1 -1
- package/lib/chunks/EHMG7I34.js +9 -0
- package/lib/chunks/{MH5X2EVH.js → EL6MGCYE.js} +1 -1
- package/lib/chunks/EVCSNWMN.js +7 -0
- package/lib/chunks/{RBNQC5ZB.js → FJBULQ4P.js} +1 -1
- package/lib/chunks/{Y5DDX2MU.js → FLL7MTDS.js} +1 -1
- package/lib/chunks/{X7C43UBI.js → FM7Y6KMP.js} +1 -1
- package/lib/chunks/{ZQTHHPK3.js → FMMOQ6SE.js} +2 -2
- package/lib/chunks/{FBEEMKTB.js → FRC2YJS4.js} +1 -1
- package/lib/chunks/{5SSWNONM.js → GHJGHHQP.js} +1 -1
- package/lib/chunks/{CHX7O5AM.js → GKPSJEG5.js} +1 -1
- package/lib/chunks/{TN3JQHMS.js → GMMFZFKJ.js} +1 -1
- package/lib/chunks/{DVLD4FET.js → GW4PLLFM.js} +1 -1
- package/lib/chunks/{L2O63VRM.js → HIMEF7J2.js} +1 -1
- package/lib/chunks/{Y3LDWYZD.js → HJ5KS42K.js} +1 -1
- package/lib/chunks/{IZMDARCL.js → HXOTKK2E.js} +1 -1
- package/lib/chunks/{HBWCMTP3.js → IFGXTL5P.js} +1 -1
- package/lib/chunks/{NLAPR7D4.js → IHUHQ7PO.js} +1 -1
- package/lib/chunks/{EO65RJ4Z.js → IJYEZR53.js} +1 -1
- package/lib/chunks/{BOWZV5S6.js → IKSSZYHA.js} +1 -1
- package/lib/chunks/{QZJAXPYF.js → IMNPDC6N.js} +1 -1
- package/lib/chunks/{25RSTUQA.js → IO7M7MGV.js} +1 -1
- package/lib/chunks/{QXHFS5G6.js → J3TXBQDL.js} +1 -1
- package/lib/chunks/{7HFLPQAB.js → JZV7EL4R.js} +1 -1
- package/lib/chunks/{2NYYNBAC.js → K6HV4EJS.js} +1 -1
- package/lib/chunks/{WLI2XLEP.js → KVXVR5Y4.js} +33 -33
- package/lib/chunks/{RNA6JDRC.js → L4HVZOFP.js} +1 -1
- package/lib/chunks/{WCJ2HAN3.js → L5AG5NJZ.js} +1 -1
- package/lib/chunks/{ZBB6PS6I.js → LTJXST6M.js} +1 -1
- package/lib/chunks/MO6NEDYO.js +17 -0
- package/lib/chunks/{S6W63XAS.js → NDECHUWV.js} +1 -1
- package/lib/chunks/{XZIK3H6V.js → NFGCHP5P.js} +1 -1
- package/lib/chunks/{W2CABGMW.js → NNBSSORJ.js} +1 -1
- package/lib/chunks/{XGPGFZMH.js → OLAN2CVV.js} +1 -1
- package/lib/chunks/{TZROZMVE.js → OOKU5T7P.js} +7 -7
- package/lib/chunks/{DURXFJ7H.js → OQRUWVII.js} +1 -1
- package/lib/chunks/{HWOL3HHR.js → Q5WCA45H.js} +8 -8
- package/lib/chunks/{HAGYQ4BK.js → QGKTPGO7.js} +1 -1
- package/lib/chunks/{UMN7TKTH.js → QQ2PGWE6.js} +2 -2
- package/lib/chunks/QYBWIG5Y.js +59 -0
- package/lib/chunks/{CJWIDJTB.js → RC4LK3ZS.js} +2 -2
- package/lib/chunks/{O53IFFP3.js → RL2EIWFM.js} +1 -1
- package/lib/chunks/{5BQNATJZ.js → RQMFL6Q4.js} +1 -1
- package/lib/chunks/S3B562IT.js +7 -0
- package/lib/chunks/{EQOFXQKD.js → SPIFPTTE.js} +1 -1
- package/lib/chunks/SUQ7ZWYJ.js +7 -0
- package/lib/chunks/{BE4Z5FOC.js → TFPMT2XD.js} +1603 -16
- package/lib/chunks/{AH6ANNYP.js → TVUYXOSQ.js} +1 -1
- package/lib/chunks/{ACECCMWJ.js → UFDBFVRI.js} +1 -1
- package/lib/chunks/UH4Q6U6X.js +7 -0
- package/lib/chunks/{YL3LVBZF.js → UKVHQIBO.js} +1 -1
- package/lib/chunks/{4DUOPCYP.js → VF2YOZ3U.js} +1 -1
- package/lib/chunks/{6ZNJ7RDX.js → VO775J6V.js} +2 -2
- package/lib/chunks/WKBXTA7Y.js +53 -0
- package/lib/chunks/{RUPTJCF5.js → WRGAJXOK.js} +1 -1
- package/lib/chunks/{EBHQXW6Z.js → XKENZH7W.js} +1 -1
- package/lib/chunks/{B5SUTVG4.js → YB52VXMW.js} +1 -1
- package/lib/chunks/{G6SB4ZP5.js → ZSQF6YOF.js} +1 -1
- package/lib/chunks/{54EKLNNI.js → ZYHLWT2C.js} +1 -1
- package/lib/eject-assets/AGENTS.md +1 -1
- package/lib/eject-assets/generators/cli/docs.ts +1 -1
- package/lib/eject-assets/generators/cli/engine-source.ts +1 -1
- package/lib/eject-assets/generators/cli/index.ts +2 -2
- package/lib/eject-assets/generators/cli/render.ts +1 -1
- package/lib/eject-assets/generators/go/client.ts +1 -1
- package/lib/eject-assets/generators/go/descriptor.ts +1 -1
- package/lib/eject-assets/generators/go/index.ts +2 -2
- package/lib/eject-assets/generators/go/models.ts +1 -1
- package/lib/eject-assets/generators/go/naming.ts +1 -1
- package/lib/eject-assets/generators/go/operations.ts +1 -1
- package/lib/eject-assets/generators/go/pagination.ts +1 -1
- package/lib/eject-assets/generators/go/types.ts +1 -1
- package/lib/eject-assets/generators/java/client.ts +66 -0
- package/lib/eject-assets/generators/java/descriptor.ts +72 -0
- package/lib/eject-assets/generators/java/index.ts +245 -0
- package/lib/eject-assets/generators/java/models.ts +362 -0
- package/lib/eject-assets/generators/java/naming.ts +135 -0
- package/lib/eject-assets/generators/java/operations.ts +300 -0
- package/lib/eject-assets/generators/java/pagination.ts +94 -0
- package/lib/eject-assets/generators/java/types.ts +103 -0
- package/lib/eject-assets/generators/mock/faker.ts +1 -1
- package/lib/eject-assets/generators/mock/index.ts +2 -2
- package/lib/eject-assets/generators/mock/render.ts +1 -1
- package/lib/eject-assets/generators/mock/sample.ts +1 -1
- package/lib/eject-assets/generators/mock/values.ts +1 -1
- package/lib/eject-assets/generators/php/client.ts +1 -1
- package/lib/eject-assets/generators/php/descriptor.ts +1 -1
- package/lib/eject-assets/generators/php/index.ts +2 -2
- package/lib/eject-assets/generators/php/models.ts +1 -1
- package/lib/eject-assets/generators/php/naming.ts +1 -1
- package/lib/eject-assets/generators/php/operations.ts +1 -1
- package/lib/eject-assets/generators/php/pagination.ts +1 -1
- package/lib/eject-assets/generators/php/types.ts +1 -1
- package/lib/eject-assets/generators/python/client.ts +1 -1
- package/lib/eject-assets/generators/python/descriptor.ts +1 -1
- package/lib/eject-assets/generators/python/index.ts +2 -2
- package/lib/eject-assets/generators/python/models.ts +1 -1
- package/lib/eject-assets/generators/python/naming.ts +1 -1
- package/lib/eject-assets/generators/python/operations.ts +1 -1
- package/lib/eject-assets/generators/python/pagination.ts +1 -1
- package/lib/eject-assets/generators/python/types.ts +1 -1
- package/lib/eject-assets/generators/swr/index.ts +2 -2
- package/lib/eject-assets/generators/swr/render.ts +1 -1
- package/lib/eject-assets/generators/tanstack-query/index.ts +2 -2
- package/lib/eject-assets/generators/tanstack-query/render.ts +1 -1
- package/lib/eject-assets/generators/transformers/index.ts +2 -2
- package/lib/eject-assets/generators/transformers/render.ts +1 -1
- package/lib/eject-assets/generators/typescript/banner.ts +1 -1
- package/lib/eject-assets/generators/typescript/client.ts +1 -1
- package/lib/eject-assets/generators/typescript/descriptor.ts +1 -1
- package/lib/eject-assets/generators/typescript/index.ts +2 -2
- package/lib/eject-assets/generators/typescript/inline-runtime.ts +1 -1
- package/lib/eject-assets/generators/typescript/operation-signature.ts +1 -1
- package/lib/eject-assets/generators/typescript/operation-types.ts +1 -1
- package/lib/eject-assets/generators/typescript/operations.ts +1 -1
- package/lib/eject-assets/generators/typescript/response-headers.ts +1 -1
- package/lib/eject-assets/generators/typescript/type-guards.ts +1 -1
- package/lib/eject-assets/generators/typescript/types.ts +1 -1
- package/lib/eject-assets/generators/zod/index.ts +2 -2
- package/lib/eject-assets/generators/zod/schemas.ts +1 -1
- package/lib/eject-assets/skills/client-generators/SKILL.md +1 -1
- package/lib/eject-assets/skills/java-generator/SKILL.md +161 -0
- package/lib/index.js +91 -90
- package/lib/skills/redocly-cli/SKILL.md +3 -1
- package/package.json +1 -1
- package/lib/chunks/DORXGE7Z.js +0 -199
- package/lib/chunks/EAFZ6DNQ.js +0 -53
- package/lib/chunks/FGJDZKD2.js +0 -13
- package/lib/chunks/GAKWND4S.js +0 -8
- package/lib/chunks/JOWPA3MJ.js +0 -7
- package/lib/chunks/RBJCAITC.js +0 -9
- package/lib/chunks/RNL7TC2W.js +0 -17
- package/lib/chunks/U5DIFWGH.js +0 -7
- package/lib/chunks/U7KIB7CD.js +0 -7
- package/lib/chunks/V34D5CUU.js +0 -7
|
@@ -4,6 +4,6 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as X}from"./KFQC57GK.js";import{j as z,k as O,la as g,n as G,o as V,qa as Y,xa as J}from"./DORXGE7Z.js";import{e as W}from"./RFWIIJFG.js";var te=W(X(),1);var C=W(X(),1);function Z(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function K(o){let t=process.env.NO_PROXY||process.env.no_proxy;if(!t)return!1;let e=t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!1;let r;try{r=new URL(o).hostname.toLowerCase()}catch{return!1}return e.some(s=>!!(s==="*"||r===s||s.startsWith(".")&&r.endsWith(s)||!s.startsWith(".")&&r.endsWith("."+s)))}var Q=async(o,{timeout:t,...e}={})=>{let r=Z(),s=r&&!K(o),n;s?n=new C.ProxyAgent({uri:r}):t&&(n=new C.Agent({connect:{timeout:t}}));try{return await(0,C.fetch)(o,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:n})}catch(i){throw await n?.destroy(),i}};var fe=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function ee(){let o=process.env.REDOCLY_ENVIRONMENT?.trim();return o&&fe.test(o)?o:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},h=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=ee(),s={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let n=await Q(t,{...e,headers:s});return this.collectSunsetWarning(n),n}catch(n){let i=n.cause??n,a=`Failed to fetch. Caused by ${i.message||i.name}.`;throw typeof i.code=="string"&&(a+=` Code: ${i.code}`),new Error(a)}}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)}},P=class{client;domain;authHeaders;constructor(t,e,r){this.client=t,this.domain=e,this.authHeaders=r}projectUrl(t,e){return`${this.domain}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}`}async fetchJson(t,e,r){try{let s=await this.client.request(t,{...e,headers:{"Content-Type":"application/json",...this.authHeaders}});return await this.getParsedResponse(s)}catch(s){let n=`${r}. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}async getParsedResponse(t){let e=await t.json();if(t.ok)return e;throw new u(`${e.title||t.statusText||"Unknown error"}.`,t.status)}},k=class extends P{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",...this.authHeaders}});return r.status===404?void 0:await this.getParsedResponse(r)}catch(r){let s=`Failed to fetch project. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}},D=class extends P{async getDefaultBranch(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/sources`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",...this.authHeaders}}),s=await this.getParsedResponse(r),[n]=s.data;if(!n)throw new Error("Project source not found.");return n.branchName}catch(r){let s=`Failed to fetch default branch. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}async upsert(t,e,r){try{let s=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/remotes`,{timeout:6e3,method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(s)}catch(s){let n=`Failed to upsert remote. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}async push(t,e,r,s){let n=new te.FormData;n.append("remoteId",r.remoteId),n.append("commit[message]",r.commit.message),n.append("commit[author][name]",r.commit.author.name),n.append("commit[author][email]",r.commit.author.email),n.append("commit[branchName]",r.commit.branchName),r.commit.url&&n.append("commit[url]",r.commit.url),r.commit.namespace&&n.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&n.append("commit[sha]",r.commit.sha),r.commit.repository&&n.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&n.append("commit[createdAt]",r.commit.createdAt);for(let i of s){let a=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await me(i.stream)]);n.append(`files[${i.path}]`,a,i.path)}r.isMainBranch&&n.append("isMainBranch","true"),r.replace&&n.append("replace","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes`,{method:"POST",headers:{...this.authHeaders},body:n});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 s=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes/${r}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",...this.authHeaders}});return await this.getParsedResponse(s)}catch(s){let n=`Failed to get push status. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}},F=class extends P{create(t,e,r){return this.fetchJson(`${this.projectUrl(t,e)}/pull-requests`,{method:"POST",body:JSON.stringify(r)},"Failed to open a pull request")}async findLatest(t,e,r){let s=new URLSearchParams({branchName:r,limit:"1"}),{data:n}=await this.fetchJson(`${this.projectUrl(t,e)}/pull-requests?${s}`,{method:"GET",timeout:6e3},"Failed to get the pull request");return n[0]}listChecks(t,e,r){return this.fetchJson(`${this.projectUrl(t,e)}/pull-requests/${encodeURIComponent(r)}/checks`,{method:"GET",timeout:6e3},"Failed to get the checks")}},j=class extends P{async findLatestByCommit(t,e,r){let s=new URLSearchParams({limit:"1",filter:`commitHash:${r}`}),{data:n}=await this.fetchJson(`${this.projectUrl(t,e)}/builds?${s}`,{method:"GET",timeout:6e3},"Failed to get the build");return n[0]}},y=class{apiClient;projects;remotes;constructor({domain:t,apiKey:e,command:r,version:s}){this.apiClient=new h(r,s);let n={Authorization:`Bearer ${e}`};this.projects=new k(this.apiClient,t,n),this.remotes=new D(this.apiClient,t,n)}getSunsetWarning(){return re(this.apiClient.sunsetWarnings)}};function re(o){let[t]=[...o].sort((e,r)=>e.isSunsetExpired!==r.isSunsetExpired?e.isSunsetExpired?-1:1:e.sunsetDate>r.sunsetDate?1:-1);return t}async function me(o){let t=[];for await(let e of o)t.push(e);return Buffer.concat(t)}function ge(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var we=/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/,E={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function ye(){return process.env.REDOCLY_DOMAIN||E.us}var ne=ve((o,t)=>{try{let e=t||o?.resolvedConfig.residency;return Te(e)?E[e]:e?new URL(e).origin:o?.resolvedConfig.scorecard?.fromProjectUrl?new URL(o.resolvedConfig.scorecard.fromProjectUrl).origin:E.us}catch{throw new $}});function S(o){try{ne(void 0,o)}catch{return!1}return!0}function ve(o){return(...t)=>{let e=o(...t);if(!e.startsWith("https://")&&!we.test(e))throw new $;return e}}var $=class extends Error{constructor(){super("Invalid Reunite URL")}};function Te(o){return typeof o=="string"&&o in E}import{Buffer as L}from"node:buffer";import A from"node:crypto";import{mkdirSync as Re,existsSync as oe,writeFileSync as Ce,readFileSync as Pe,rmSync as xe}from"node:fs";import{homedir as Ue}from"node:os";import ie from"node:path";import*as se from"node:child_process";var v=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new h("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]];se.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((s,n)=>{let i=setInterval(async()=>{let c=await this.getAccessToken(t);c.access_token&&(clearInterval(i),clearTimeout(a),s(c)),c.error&&c.error!=="authorization_pending"&&(clearInterval(i),clearTimeout(a),n(c.error_description))},e*1e3),a=setTimeout(async()=>{clearInterval(i),clearTimeout(a),n("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:s,interval:n=10,expires_in:i=300}=await this.sendRequest("/device-authorize","POST",{client_name:this.clientName});return{deviceCode:t,userCode:e,verificationUri:r,verificationUriComplete:s,interval:n,expiresIn:i}}async sendRequest(t,e="GET",r=void 0,s={}){let n=`${this.baseUrl}/api${t}`,i=await this.apiClient.request(n,{body:r&&JSON.stringify(r),method:e,headers:{"Content-Type":"application/json",...s},timeout:6e3});return i.status===204?{success:!0}:await i.json()}withResidency(t){return{...t,residency:this.baseUrl}}};var Ee="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",ae="aes-256-cbc",H=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=Ue();this.credentialsFolderPath=ie.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=ie.join(this.credentialsFolderPath,this.credentialsFileName),this.key=A.createHash("sha256").update(`${this.credentialsFolderPath}${Ee}`).digest(),this.iv=A.createHash("md5").update(this.credentialsFolderPath).digest(),Re(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let s=await new v(t,this.version).run(e);if(!s)throw new Error("Failed to login. No credentials received.");await this.saveCredentials(s)}async logout(){try{this.removeCredentials()}catch{}}async isAuthorized(t,e){return e?new v(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new v(t,this.version),r=await this.readCredentials();if(!r||!S(t)||r.residency&&r.residency!==t)return null;if(await e.verifyToken(r.access_token))return r.access_token;try{let n=await e.refreshToken(r.refresh_token);return await this.saveCredentials(n),n.access_token}catch{return null}};async saveCredentials(t){try{let e=this.encryptCredentials(t);Ce(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!oe(this.credentialsFilePath))return null;try{let t=Pe(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){oe(this.credentialsFilePath)&&xe(this.credentialsFilePath)}encryptCredentials(t){let e=A.createCipheriv(ae,this.key,this.iv);return L.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=A.createDecipheriv(ae,this.key,this.iv),r=L.concat([e.update(L.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};var $e=/^(https?:\/\/[^/]+)\/api\/orgs\/([^/]+)\/projects\/([^/]+)\/git\/?$/;function Se(o,t,e){return`${o}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}/git`}function _e(o){let[,t,e,r]=o.match($e)??[];if(!(!t||!e||!r||!S(t)))return{reuniteUrl:t,organization:decodeURIComponent(e),project:decodeURIComponent(r)}}async function Ie({branch:o,title:t,description:e,base:r,draft:s,...n}){let{pullRequests:i}=ce(n,"project pr create");return i.create(n.organization,n.project,{branchName:o,title:t,description:e,targetBranchName:r,isDraft:s})}async function Fe({branch:o,...t}){let{pullRequests:e,builds:r}=ce(t,"project pr status"),{organization:s,project:n}=t,i=await e.findLatest(s,n,o);if(!i)return;let[a,c]=await Promise.all([e.listChecks(s,n,i.id),i.headCommitHash?r.findLatestByCommit(s,n,i.headCommitHash):void 0]);return{pullRequest:i,checks:a,previewUrl:c?.deploymentStatus==="SUCCESS"?c.url:void 0}}function ce({reuniteUrl:o,accessToken:t,version:e},r){let s=new h(r,e),n={Cookie:`accessToken=${t}`};return{pullRequests:new F(s,o,n),builds:new j(s,o,n)}}import*as T from"node:fs";import*as p from"node:path";var je=/\/orgs\/([^/]+)\/projects\//,Ae=[401,403];async function x(o,{organization:t,project:e,onSlugDeprecated:r}){let s=await Ne(o,t,e);if(!s)return{organizationId:t,projectId:e};let n={organizationId:Oe(s.uri),projectId:s.id};return(n.organizationId!==t||n.projectId!==e)&&r?.(n),n}async function Ne(o,t,e){try{let r=await o.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&&Ae.includes(r.status))return;throw r}}function Oe(o){let t=o.match(je)?.[1];if(!t)throw new Error(`Could not read the organization ID from the project URI "${o}".`);return t}async function ke({domain:o,apiKey:t,organization:e,project:r,mountPath:s,files:n,defaultBranch:i,commit:a,version:c,replace:_,onUploadStart:I,onSunsetWarning:R,onSlugDeprecated:N}){let f=new y({domain:o,apiKey:t,command:"push",version:c});try{let{organizationId:d,projectId:l}=await x(f,{organization:e,project:r,onSlugDeprecated:N}),b=await f.remotes.getDefaultBranch(d,l),m=await f.remotes.upsert(d,l,{mountBranchName:b,mountPath:s});I?.(m);let{id:U}=await f.remotes.push(d,l,{remoteId:m.id,commit:a,isMainBranch:i===a.branchName,replace:_},n.map(M=>({path:G(M.name),stream:T.createReadStream(M.path)})));return{pushId:U,organizationId:d,projectId:l}}finally{let d=f.getSunsetWarning();d&&R?.(d)}}function De(o,t){let e={};for(let s of o)if(T.statSync(s).isDirectory()){let n=s;ue(n,[]).forEach(a=>r(a,n))}else r(s,p.dirname(s));function r(s,n){let i=p.relative(n,s);e[i]&&t?.(e[i],s),e[i]=s}return Object.entries(e).map(([s,n])=>({name:s,path:p.resolve(n)}))}function ue(o,t){let e=T.readdirSync(o);for(let r of e){let s=p.join(o,r);T.statSync(s).isDirectory()?t=ue(s,t):t.push(s)}return t}async function le({operation:o,condition:t,onConditionNotMet:e,startTime:r=Date.now(),retryTimeoutMs:s=6e5,retryIntervalMs:n=5e3}){async function i(){let a=await o();if(t(a))return a;if(Date.now()-r>s)throw new Error("Timeout exceeded.");return await e?.(a),await z(n),i()}return i()}var Le=1200,He=5e3,qe=["pending","running"];async function Be(o){let t=de(o);try{let e=await x(t,o);return await pe(t,e,o.pushId)}finally{he(t,o)}}async function be({buildType:o,maxExecutionTime:t=Le,retryIntervalMs:e=He,startTime:r=Date.now(),onRetry:s,...n}){let i=de(n);try{let a=await x(i,n);return await le({operation:()=>pe(i,a,n.pushId),condition:c=>!qe.includes(c.status[o].deploy.status),onConditionNotMet:s,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{he(i,n)}}function de({domain:o,apiKey:t,version:e}){return new y({domain:o,apiKey:t,command:"push-status",version:e})}function he(o,{onSunsetWarning:t}){let e=o.getSunsetWarning();e&&t?.(e)}function pe(o,{organizationId:t,projectId:e},r){return o.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function Me({projectUrl:o,auth:t,isApiKey:e=!1,onDebug:r}){let s=We(o);if(!s)throw new g(`Invalid project URL format: ${o}`);try{let n=await ze({...s,auth:t,isApiKey:e,onDebug:r}),i=n.config.scorecardClassic||n.config.scorecard;if(!i)throw new Error("No scorecard configuration found.");let a=n.config.pluginsUrl,c=a?await Ge(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(n){throw new g(n instanceof Error?n.message:String(n))}}function We(o){let t=new URL(o),e=t.pathname.match(/\/org\/(?<orgSlug>[^/]+)\/project\/(?<projectSlug>[^/]+)/);if(!e?.groups)return;let{orgSlug:r,projectSlug:s}=e.groups;return{residency:t.origin,orgSlug:r,projectSlug:s}}async function ze({residency:o,orgSlug:t,projectSlug:e,auth:r,isApiKey:s,onDebug:n}){let i=new URL(`${o}/api/orgs/${t}/projects/${e}`),a=await fetch(i,{headers:Ve(r,s)});if(n?.(`Project fetch response status: ${a.status}`),a.status===401||a.status===403)throw n?.(`Authentication failed with status ${a.status}.`),n?.("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 n?.("Successfully received project configuration."),a.json()}async function Ge(o,t){t?.(`Fetching plugins from: ${o}`);try{let e=await fetch(o);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 Ve(o,t){return t?{Authorization:`Bearer ${o}`}:{Cookie:`accessToken=${o}`}}async function q(o,t,e=[],r=[],s){let n={};for(let i of e){let a={[i.name]:{root:o,rules:t}},c=await Y({apis:a,...i,plugins:r},{configPath:s});n[i.name]=c.forAlias(i.name)}return n}function B(o,t){if(o){for(let e of o)if(Object.entries(e.where?.metadata||{}).every(([s,n])=>Ye(s,n,t)))return e}}function Ye(o,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[o])return!1;let[r,s]=t.split("/"),n=new Date(e[o]);return!(n<new Date(r)||s&&n>new Date(s))}else if(t.match(/^\/.*\//)){if(!e[o])return!1;try{return V(t).test(e[o])}catch{throw new g(`Invalid regex in scorecard target "${o}": ${t}`)}}return e[o]===t}import{pathToFileURL as Je}from"node:url";async function Xe(o,t){if(!o)return[];let e=Je(t??process.cwd()).href+"/",r=o.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var Ze=".redocly.com";function Ke(o){try{return new URL(o).hostname.toLowerCase().endsWith(Ze)}catch{return!1}}async function Qe({apiPath:o,document:t,externalRefResolver:e,scorecardConfig:r,configPath:s,plugins:n=[],targetLevel:i,metadata:a={},onDebug:c}){let _=[],I=new Map,R=r.levels||[];if(i&&!R.some(l=>l.name===i))throw new g(`Target level "${i}" not found in the scorecard configuration levels.
|
|
7
|
+
import{a as X}from"./KFQC57GK.js";import{Ca as J,j as z,k as O,n as G,o as V,qa as g,va as Y}from"./4ZCKAKVF.js";import{e as W}from"./RFWIIJFG.js";var te=W(X(),1);var C=W(X(),1);function Z(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function K(o){let t=process.env.NO_PROXY||process.env.no_proxy;if(!t)return!1;let e=t.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!1;let r;try{r=new URL(o).hostname.toLowerCase()}catch{return!1}return e.some(s=>!!(s==="*"||r===s||s.startsWith(".")&&r.endsWith(s)||!s.startsWith(".")&&r.endsWith("."+s)))}var Q=async(o,{timeout:t,...e}={})=>{let r=Z(),s=r&&!K(o),n;s?n=new C.ProxyAgent({uri:r}):t&&(n=new C.Agent({connect:{timeout:t}}));try{return await(0,C.fetch)(o,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:n})}catch(i){throw await n?.destroy(),i}};var fe=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function ee(){let o=process.env.REDOCLY_ENVIRONMENT?.trim();return o&&fe.test(o)?o:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},h=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=ee(),s={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let n=await Q(t,{...e,headers:s});return this.collectSunsetWarning(n),n}catch(n){let i=n.cause??n,a=`Failed to fetch. Caused by ${i.message||i.name}.`;throw typeof i.code=="string"&&(a+=` Code: ${i.code}`),new Error(a)}}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)}},P=class{client;domain;authHeaders;constructor(t,e,r){this.client=t,this.domain=e,this.authHeaders=r}projectUrl(t,e){return`${this.domain}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}`}async fetchJson(t,e,r){try{let s=await this.client.request(t,{...e,headers:{"Content-Type":"application/json",...this.authHeaders}});return await this.getParsedResponse(s)}catch(s){let n=`${r}. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}async getParsedResponse(t){let e=await t.json();if(t.ok)return e;throw new u(`${e.title||t.statusText||"Unknown error"}.`,t.status)}},k=class extends P{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",...this.authHeaders}});return r.status===404?void 0:await this.getParsedResponse(r)}catch(r){let s=`Failed to fetch project. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}},D=class extends P{async getDefaultBranch(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/sources`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",...this.authHeaders}}),s=await this.getParsedResponse(r),[n]=s.data;if(!n)throw new Error("Project source not found.");return n.branchName}catch(r){let s=`Failed to fetch default branch. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}async upsert(t,e,r){try{let s=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/remotes`,{timeout:6e3,method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(s)}catch(s){let n=`Failed to upsert remote. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}async push(t,e,r,s){let n=new te.FormData;n.append("remoteId",r.remoteId),n.append("commit[message]",r.commit.message),n.append("commit[author][name]",r.commit.author.name),n.append("commit[author][email]",r.commit.author.email),n.append("commit[branchName]",r.commit.branchName),r.commit.url&&n.append("commit[url]",r.commit.url),r.commit.namespace&&n.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&n.append("commit[sha]",r.commit.sha),r.commit.repository&&n.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&n.append("commit[createdAt]",r.commit.createdAt);for(let i of s){let a=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await me(i.stream)]);n.append(`files[${i.path}]`,a,i.path)}r.isMainBranch&&n.append("isMainBranch","true"),r.replace&&n.append("replace","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes`,{method:"POST",headers:{...this.authHeaders},body:n});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 s=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes/${r}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",...this.authHeaders}});return await this.getParsedResponse(s)}catch(s){let n=`Failed to get push status. ${s.message}`;throw s instanceof u?new u(n,s.status):new Error(n)}}},F=class extends P{create(t,e,r){return this.fetchJson(`${this.projectUrl(t,e)}/pull-requests`,{method:"POST",body:JSON.stringify(r)},"Failed to open a pull request")}async findLatest(t,e,r){let s=new URLSearchParams({branchName:r,limit:"1"}),{data:n}=await this.fetchJson(`${this.projectUrl(t,e)}/pull-requests?${s}`,{method:"GET",timeout:6e3},"Failed to get the pull request");return n[0]}listChecks(t,e,r){return this.fetchJson(`${this.projectUrl(t,e)}/pull-requests/${encodeURIComponent(r)}/checks`,{method:"GET",timeout:6e3},"Failed to get the checks")}},j=class extends P{async findLatestByCommit(t,e,r){let s=new URLSearchParams({limit:"1",filter:`commitHash:${r}`}),{data:n}=await this.fetchJson(`${this.projectUrl(t,e)}/builds?${s}`,{method:"GET",timeout:6e3},"Failed to get the build");return n[0]}},y=class{apiClient;projects;remotes;constructor({domain:t,apiKey:e,command:r,version:s}){this.apiClient=new h(r,s);let n={Authorization:`Bearer ${e}`};this.projects=new k(this.apiClient,t,n),this.remotes=new D(this.apiClient,t,n)}getSunsetWarning(){return re(this.apiClient.sunsetWarnings)}};function re(o){let[t]=[...o].sort((e,r)=>e.isSunsetExpired!==r.isSunsetExpired?e.isSunsetExpired?-1:1:e.sunsetDate>r.sunsetDate?1:-1);return t}async function me(o){let t=[];for await(let e of o)t.push(e);return Buffer.concat(t)}function ge(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var we=/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/,E={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function ye(){return process.env.REDOCLY_DOMAIN||E.us}var ne=ve((o,t)=>{try{let e=t||o?.resolvedConfig.residency;return Te(e)?E[e]:e?new URL(e).origin:o?.resolvedConfig.scorecard?.fromProjectUrl?new URL(o.resolvedConfig.scorecard.fromProjectUrl).origin:E.us}catch{throw new $}});function S(o){try{ne(void 0,o)}catch{return!1}return!0}function ve(o){return(...t)=>{let e=o(...t);if(!e.startsWith("https://")&&!we.test(e))throw new $;return e}}var $=class extends Error{constructor(){super("Invalid Reunite URL")}};function Te(o){return typeof o=="string"&&o in E}import{Buffer as L}from"node:buffer";import A from"node:crypto";import{mkdirSync as Re,existsSync as oe,writeFileSync as Ce,readFileSync as Pe,rmSync as xe}from"node:fs";import{homedir as Ue}from"node:os";import ie from"node:path";import*as se from"node:child_process";var v=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new h("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]];se.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((s,n)=>{let i=setInterval(async()=>{let c=await this.getAccessToken(t);c.access_token&&(clearInterval(i),clearTimeout(a),s(c)),c.error&&c.error!=="authorization_pending"&&(clearInterval(i),clearTimeout(a),n(c.error_description))},e*1e3),a=setTimeout(async()=>{clearInterval(i),clearTimeout(a),n("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:s,interval:n=10,expires_in:i=300}=await this.sendRequest("/device-authorize","POST",{client_name:this.clientName});return{deviceCode:t,userCode:e,verificationUri:r,verificationUriComplete:s,interval:n,expiresIn:i}}async sendRequest(t,e="GET",r=void 0,s={}){let n=`${this.baseUrl}/api${t}`,i=await this.apiClient.request(n,{body:r&&JSON.stringify(r),method:e,headers:{"Content-Type":"application/json",...s},timeout:6e3});return i.status===204?{success:!0}:await i.json()}withResidency(t){return{...t,residency:this.baseUrl}}};var Ee="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",ae="aes-256-cbc",H=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=Ue();this.credentialsFolderPath=ie.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=ie.join(this.credentialsFolderPath,this.credentialsFileName),this.key=A.createHash("sha256").update(`${this.credentialsFolderPath}${Ee}`).digest(),this.iv=A.createHash("md5").update(this.credentialsFolderPath).digest(),Re(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let s=await new v(t,this.version).run(e);if(!s)throw new Error("Failed to login. No credentials received.");await this.saveCredentials(s)}async logout(){try{this.removeCredentials()}catch{}}async isAuthorized(t,e){return e?new v(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new v(t,this.version),r=await this.readCredentials();if(!r||!S(t)||r.residency&&r.residency!==t)return null;if(await e.verifyToken(r.access_token))return r.access_token;try{let n=await e.refreshToken(r.refresh_token);return await this.saveCredentials(n),n.access_token}catch{return null}};async saveCredentials(t){try{let e=this.encryptCredentials(t);Ce(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!oe(this.credentialsFilePath))return null;try{let t=Pe(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){oe(this.credentialsFilePath)&&xe(this.credentialsFilePath)}encryptCredentials(t){let e=A.createCipheriv(ae,this.key,this.iv);return L.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=A.createDecipheriv(ae,this.key,this.iv),r=L.concat([e.update(L.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};var $e=/^(https?:\/\/[^/]+)\/api\/orgs\/([^/]+)\/projects\/([^/]+)\/git\/?$/;function Se(o,t,e){return`${o}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}/git`}function _e(o){let[,t,e,r]=o.match($e)??[];if(!(!t||!e||!r||!S(t)))return{reuniteUrl:t,organization:decodeURIComponent(e),project:decodeURIComponent(r)}}async function Ie({branch:o,title:t,description:e,base:r,draft:s,...n}){let{pullRequests:i}=ce(n,"project pr create");return i.create(n.organization,n.project,{branchName:o,title:t,description:e,targetBranchName:r,isDraft:s})}async function Fe({branch:o,...t}){let{pullRequests:e,builds:r}=ce(t,"project pr status"),{organization:s,project:n}=t,i=await e.findLatest(s,n,o);if(!i)return;let[a,c]=await Promise.all([e.listChecks(s,n,i.id),i.headCommitHash?r.findLatestByCommit(s,n,i.headCommitHash):void 0]);return{pullRequest:i,checks:a,previewUrl:c?.deploymentStatus==="SUCCESS"?c.url:void 0}}function ce({reuniteUrl:o,accessToken:t,version:e},r){let s=new h(r,e),n={Cookie:`accessToken=${t}`};return{pullRequests:new F(s,o,n),builds:new j(s,o,n)}}import*as T from"node:fs";import*as p from"node:path";var je=/\/orgs\/([^/]+)\/projects\//,Ae=[401,403];async function x(o,{organization:t,project:e,onSlugDeprecated:r}){let s=await Ne(o,t,e);if(!s)return{organizationId:t,projectId:e};let n={organizationId:Oe(s.uri),projectId:s.id};return(n.organizationId!==t||n.projectId!==e)&&r?.(n),n}async function Ne(o,t,e){try{let r=await o.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&&Ae.includes(r.status))return;throw r}}function Oe(o){let t=o.match(je)?.[1];if(!t)throw new Error(`Could not read the organization ID from the project URI "${o}".`);return t}async function ke({domain:o,apiKey:t,organization:e,project:r,mountPath:s,files:n,defaultBranch:i,commit:a,version:c,replace:_,onUploadStart:I,onSunsetWarning:R,onSlugDeprecated:N}){let f=new y({domain:o,apiKey:t,command:"push",version:c});try{let{organizationId:d,projectId:l}=await x(f,{organization:e,project:r,onSlugDeprecated:N}),b=await f.remotes.getDefaultBranch(d,l),m=await f.remotes.upsert(d,l,{mountBranchName:b,mountPath:s});I?.(m);let{id:U}=await f.remotes.push(d,l,{remoteId:m.id,commit:a,isMainBranch:i===a.branchName,replace:_},n.map(M=>({path:G(M.name),stream:T.createReadStream(M.path)})));return{pushId:U,organizationId:d,projectId:l}}finally{let d=f.getSunsetWarning();d&&R?.(d)}}function De(o,t){let e={};for(let s of o)if(T.statSync(s).isDirectory()){let n=s;ue(n,[]).forEach(a=>r(a,n))}else r(s,p.dirname(s));function r(s,n){let i=p.relative(n,s);e[i]&&t?.(e[i],s),e[i]=s}return Object.entries(e).map(([s,n])=>({name:s,path:p.resolve(n)}))}function ue(o,t){let e=T.readdirSync(o);for(let r of e){let s=p.join(o,r);T.statSync(s).isDirectory()?t=ue(s,t):t.push(s)}return t}async function le({operation:o,condition:t,onConditionNotMet:e,startTime:r=Date.now(),retryTimeoutMs:s=6e5,retryIntervalMs:n=5e3}){async function i(){let a=await o();if(t(a))return a;if(Date.now()-r>s)throw new Error("Timeout exceeded.");return await e?.(a),await z(n),i()}return i()}var Le=1200,He=5e3,qe=["pending","running"];async function Be(o){let t=de(o);try{let e=await x(t,o);return await pe(t,e,o.pushId)}finally{he(t,o)}}async function be({buildType:o,maxExecutionTime:t=Le,retryIntervalMs:e=He,startTime:r=Date.now(),onRetry:s,...n}){let i=de(n);try{let a=await x(i,n);return await le({operation:()=>pe(i,a,n.pushId),condition:c=>!qe.includes(c.status[o].deploy.status),onConditionNotMet:s,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{he(i,n)}}function de({domain:o,apiKey:t,version:e}){return new y({domain:o,apiKey:t,command:"push-status",version:e})}function he(o,{onSunsetWarning:t}){let e=o.getSunsetWarning();e&&t?.(e)}function pe(o,{organizationId:t,projectId:e},r){return o.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function Me({projectUrl:o,auth:t,isApiKey:e=!1,onDebug:r}){let s=We(o);if(!s)throw new g(`Invalid project URL format: ${o}`);try{let n=await ze({...s,auth:t,isApiKey:e,onDebug:r}),i=n.config.scorecardClassic||n.config.scorecard;if(!i)throw new Error("No scorecard configuration found.");let a=n.config.pluginsUrl,c=a?await Ge(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(n){throw new g(n instanceof Error?n.message:String(n))}}function We(o){let t=new URL(o),e=t.pathname.match(/\/org\/(?<orgSlug>[^/]+)\/project\/(?<projectSlug>[^/]+)/);if(!e?.groups)return;let{orgSlug:r,projectSlug:s}=e.groups;return{residency:t.origin,orgSlug:r,projectSlug:s}}async function ze({residency:o,orgSlug:t,projectSlug:e,auth:r,isApiKey:s,onDebug:n}){let i=new URL(`${o}/api/orgs/${t}/projects/${e}`),a=await fetch(i,{headers:Ve(r,s)});if(n?.(`Project fetch response status: ${a.status}`),a.status===401||a.status===403)throw n?.(`Authentication failed with status ${a.status}.`),n?.("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 n?.("Successfully received project configuration."),a.json()}async function Ge(o,t){t?.(`Fetching plugins from: ${o}`);try{let e=await fetch(o);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 Ve(o,t){return t?{Authorization:`Bearer ${o}`}:{Cookie:`accessToken=${o}`}}async function q(o,t,e=[],r=[],s){let n={};for(let i of e){let a={[i.name]:{root:o,rules:t}},c=await Y({apis:a,...i,plugins:r},{configPath:s});n[i.name]=c.forAlias(i.name)}return n}function B(o,t){if(o){for(let e of o)if(Object.entries(e.where?.metadata||{}).every(([s,n])=>Ye(s,n,t)))return e}}function Ye(o,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[o])return!1;let[r,s]=t.split("/"),n=new Date(e[o]);return!(n<new Date(r)||s&&n>new Date(s))}else if(t.match(/^\/.*\//)){if(!e[o])return!1;try{return V(t).test(e[o])}catch{throw new g(`Invalid regex in scorecard target "${o}": ${t}`)}}return e[o]===t}import{pathToFileURL as Je}from"node:url";async function Xe(o,t){if(!o)return[];let e=Je(t??process.cwd()).href+"/",r=o.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var Ze=".redocly.com";function Ke(o){try{return new URL(o).hostname.toLowerCase().endsWith(Ze)}catch{return!1}}async function Qe({apiPath:o,document:t,externalRefResolver:e,scorecardConfig:r,configPath:s,plugins:n=[],targetLevel:i,metadata:a={},onDebug:c}){let _=[],I=new Map,R=r.levels||[];if(i&&!R.some(l=>l.name===i))throw new g(`Target level "${i}" not found in the scorecard configuration levels.
|
|
8
8
|
`);let N=B(r.targets,a)?.rules,f=await q(o,N,R,n,s||"");for(let l of R){c?.(`
|
|
9
9
|
Validating level: "${l.name}"`),n.length>0&&c?.(`Using ${n.length} ${O("plugin",n.length)} for this level.`),c?.("Linting document against level rules...");let m=(await J({document:t,externalRefResolver:e,config:f[l.name]})).filter(({ignored:U})=>!U).map(U=>({...U,scorecardLevel:l.name}));c?.(`Found ${m.length} ${O("problem",m.length)} for level "${l.name}".`),I.set(l.name,m),_.push(...m)}let d=et(I,R,i);return{problems:_,achievedLevel:d,targetLevelAchieved:i?d===i:!0}}function et(o,t,e){let r=null;for(let s of t){if((o.get(s.name)||[]).some(a=>a.severity==="error"))return r||"Non Conformant";if(r=s.name,e&&s.name===e)return s.name}return r||"Non Conformant"}export{u as a,h as b,y as c,re as d,ge as e,E as f,ye as g,ne as h,S as i,$ as j,v as k,H as l,Se as m,_e as n,Ie as o,Fe as p,x as q,ke as r,De as s,Be as t,be as u,Me as v,q as w,B as x,Xe as y,Ke as z,Qe as A};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{e as y,k as D}from"./
|
|
7
|
+
import{e as y,k as D}from"./4AXMK6B2.js";import{g as _}from"./D3C6XIMY.js";import{join as z}from"node:path";var a=" ";function k(t){return`transform${D(t)}`}var W="type __Writable<T> = { -readonly [K in keyof T]: T[K] };",v=!1;function E(t){return{text:t,path:[t]}}function B(t,r){return{text:`${t.text}[${JSON.stringify(r)}]`,path:[...t.path,r]}}function d(t,r,n){if(w(t))return!0;switch(t.kind){case"array":return d(t.items,r,n);case"union":return t.members.some(o=>d(o,r,n));case"ref":{if(n.has(t.name))return!1;let o=r.get(t.name);return o!==void 0&&d(o,r,new Set(n).add(t.name))}default:return!1}}function w(t){return t.kind==="scalar"&&t.scalar==="string"&&(t.metadata?.format==="date-time"||t.metadata?.format==="date")}function $(t,r,n){if(w(t))return!0;switch(t.kind){case"array":return $(t.items,r,n);case"record":return $(t.value,r,n);case"object":return t.properties.some(o=>$(o.schema,r,n));case"union":case"intersection":return t.members.some(o=>$(o,r,n));case"ref":{let o=r.get(t.name);return o!==void 0&&!n.has(t.name)?$(o,r,new Set(n).add(t.name)):!1}default:return!1}}function l(t,r,n,o=!1){return o?[`${n}if (${t}) {`,...r(n+a),`${n}}`]:[`${n}if (${t})`,...r(n+a)]}function O(t,r,n=!1){let o=n?G(t):t.text;return i=>[`${i}${o} = ${r};`]}function T(t){return r=>[`${r}${t};`]}function G(t){if(t.path.length<2)return t.text;v=!0;let r={text:t.text.slice(0,t.text.lastIndexOf("[")),path:t.path.slice(0,-1)},n=t.path[t.path.length-1];return`(${r.text} as __Writable<${K(r)}>)[${JSON.stringify(n)}]`}function K(t){let r=`typeof ${t.path[0]}`;for(let n of t.path.slice(1))r=`NonNullable<${r}>[${JSON.stringify(n)}]`;return`NonNullable<${r}>`}function U(t){return t==="data"?"item":`item${Number(t.slice(4))+1}`}function p(t,r,n,o,i,e,u=!1){if(w(r))return l(`typeof ${t.text} === "string"`,O(t,`new Date(${t.text})`,u),e);switch(r.kind){case"ref":return h(t,r.name,n,o,e,u);case"object":{let f=[];for(let s of r.properties)f.push(...P(B(t,s.name),s.schema,n,o,i,e,s.readOnly===!0));return f}case"array":return R(t,r.items,n,o,i,e,u);case"record":return J(t,r.value,n,o,i,e,!0);case"intersection":{let f=[];for(let s of r.members)f.push(...p(t,s,n,o,i,e,u));return f}case"union":return b(t,r.members,n,o,i,e,u);default:return[]}}function b(t,r,n,o,i,e,u=!1){let f=[],s=e+a,x=[];for(let c of r)if(w(c))f.push(...p(t,c,n,o,i,e,u));else if(c.kind==="ref"){if(!$(c,n,o))continue;let j=`${k(c.name)}(${t.text} as ${c.name})`,m=d(c,n,o)?O(t,j,u):T(j);x.push(...m(s))}else x.push(...p(t,c,n,o,i,s,u));return x.length>0&&f.push(...l(`${t.text} && typeof ${t.text} === "object"`,()=>x,e,!0)),f}function h(t,r,n,o,i,e=!1){let u={kind:"ref",name:r};if(!$(u,n,o))return[];let f=`${k(r)}(${t.text})`;return l(t.text,d(u,n,o)?O(t,f,e):T(f),i)}function P(t,r,n,o,i,e,u=!1){if(r.kind==="ref")return h(t,r.name,n,o,e,u);if(r.kind==="object"){let f=p(t,r,n,o,i,e+a);return f.length===0?[]:l(t.text,()=>f,e,!0)}return p(t,r,n,o,i,e,u)}function A(t,r,n,o,i=0){if(w(r))return`new Date(${t})`;if(r.kind==="ref"&&d(r,n,o))return`${k(r.name)}(${t})`;if(r.kind==="array"){let e=r.items.kind==="array"?I(i+1):"v",u=A(e,r.items,n,o,i+1);return u===null?null:`${t}.map(${e} => ${u})`}return null}function I(t){return t<=1?"row":`row${t}`}function R(t,r,n,o,i,e,u=!1){let f=r.kind==="array"?I(1):"v",s=A(f,r,n,o,1);return s!==null?l(`Array.isArray(${t.text})`,O(t,`${t.text}.map(${f} => ${s})`,u),e):r.kind==="ref"?$(r,n,o)?l(`Array.isArray(${t.text})`,T(`${t.text}.forEach(${k(r.name)})`),e):[]:J(t,r,n,o,i,e,!1)}function J(t,r,n,o,i,e,u){if(u){let c={text:`${t.text}[__k]`,path:[...t.path,"__k"]},j=A(c.text,r,n,o);if(j!==null){let m=w(r)?`typeof ${c.text} === "string"`:`Array.isArray(${c.text})`;return l(t.text,S=>[`${S}for (const __k of Object.keys(${t.text}))`,...l(m,C=>[`${C}${c.text} = ${j};`],S+a)],e)}}let f=U(i),s=p(E(f),r,n,o,f,e+a+a);if(s.length===0)return[];let x=u?`Object.values(${t.text})`:t.text;return l(u?t.text:`Array.isArray(${t.text})`,c=>[`${c}${x}.forEach(${f} => {`,...s,`${c}});`],e)}function q(t,r,n){let o=t.name,i=E("data"),e=t.schema.kind==="ref"?h(i,t.schema.name,n,new Set,a):p(i,t.schema,n,new Set,"data",a),u=(_(t.schema,r)?.properties??[]).filter(s=>s.writeOnly).map(s=>JSON.stringify(s.name));if(u.length===0)return[`export const ${k(t.name)} = (data: ${o}): ${o} => {`,...e,`${a}return data;`,"};"].join(`
|
|
8
8
|
`);let f=`Omit<${o}, ${u.join(" | ")}>`;return[`export const ${k(t.name)} = <T extends ${f}>(input: T): T => {`,`${a}const data: ${f} = input;`,...e,`${a}return input;`,"};"].join(`
|
|
9
9
|
`)}function M(t,r){let n=new Map(t.schemas.map(f=>[f.name,f.schema])),o=t.schemas.filter(f=>$(f.schema,n,new Set));if(o.length===0)return"";let i=o.map(f=>y(f.name)).join(", ");v=!1;let e=o.map(f=>q(f,t,n));return[`import type { ${i} } from ${JSON.stringify(r.sdkModule)};`,...v?[W]:[],...e].join(`
|
|
10
10
|
|
|
@@ -0,0 +1,7 @@
|
|
|
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}from"./BY22HEXP.js";import"./HIMEF7J2.js";import"./76AJ5P4Y.js";import"./QQ2PGWE6.js";import"./4AXMK6B2.js";import"./D3C6XIMY.js";import"./WZXA5XPB.js";import"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";export{a as swrGenerator};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as o,c as n}from"./HBUZKWXC.js";import{
|
|
7
|
+
import{a as o,c as n}from"./HBUZKWXC.js";import{ka as t}from"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";import{spawn as m}from"node:child_process";var j=async({argv:e})=>{t.info(`
|
|
8
8
|
Launching eject using NPX.
|
|
9
9
|
|
|
10
10
|
`);let{npxExecutableName:c,sanitize:r,shell:i}=n(),p=r(e.path,o),a=r(e["project-dir"],o);m(c,["-y","@redocly/realm","eject",`${e.type}`,p,`-d=${a}`,e.force?`--force=${e.force}`:""],{stdio:"inherit",shell:i}).on("error",s=>{throw t.info(`Eject launch failed: ${s.message}`),new Error("Eject launch failed.")})};export{j as handleEject};
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as a,c as b,d as c}from"./
|
|
7
|
+
import{b as a,c as b,d as c}from"./IMNPDC6N.js";import"./TFPMT2XD.js";import"./HIMEF7J2.js";import"./76AJ5P4Y.js";import"./QQ2PGWE6.js";import"./4AXMK6B2.js";import"./D3C6XIMY.js";import"./WZXA5XPB.js";import"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";export{b as cliDocs,a as cliGenerator,c as cliSample};
|
|
@@ -4,5 +4,5 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as C,e as P,g as L,h as v,i as R,k as V}from"./
|
|
8
|
-
`)}import{execSync as ne}from"node:child_process";import*as p from"node:fs";import{existsSync as re,writeFileSync as oe,readFileSync as M}from"node:fs";import*as $ from"node:os";import{tmpdir as U}from"node:os";import{dirname as J,join as A}from"node:path";async function F(e=L){try{let{fetchWithTimeout:t}=await import("./QXBSAWH3.js");return await t(P,{timeout:e}),!0}catch{return!1}}var y="***";function be(e){return process.env.REDOCLY_TELEMETRY!=="off"&&e?.resolvedConfig.telemetry!=="off"}async function Oe({config:e,argv:t,exit_code:n,execution_time:r,spec_version:o,spec_keyword:i,spec_full_version:s,respect_x_security_auth_types:c,respect_source_description_types:f,respect_criterion_object_types:N,lint_rules_with_errors:T,lint_rules_with_warnings:b,lint_rules_with_ignored_problems:O,generate_client:a,eject_generator:l,bundle:G}){try{if(!t||!await F(1e3))return;let{_:[h],$0:pe,...D}=t,{RedoclyOAuthClient:K,getReuniteUrl:H}=await import("./
|
|
7
|
+
import{a as C,e as P,g as L,h as v,i as R,k as V}from"./D2BBHPMR.js";import{u as S}from"./GKPSJEG5.js";import{c as m,da as u,la as k,u as I}from"./4ZCKAKVF.js";var _=" ",z=" ";function _e(e){let t=Math.max(...e.map(o=>S(o).length)),n=t+z.length*2,r=_+u("\u2551"+" ".repeat(n)+"\u2551");return["",_+u("\u2554"+"\u2550".repeat(n)+"\u2557"),r,...e.map(o=>{let i=" ".repeat(t-S(o).length);return`${_}${u("\u2551")}${z}${o}${i}${z}${u("\u2551")}`}),r,_+u("\u255A"+"\u2550".repeat(n)+"\u255D"),"",""].join(`
|
|
8
|
+
`)}import{execSync as ne}from"node:child_process";import*as p from"node:fs";import{existsSync as re,writeFileSync as oe,readFileSync as M}from"node:fs";import*as $ from"node:os";import{tmpdir as U}from"node:os";import{dirname as J,join as A}from"node:path";async function F(e=L){try{let{fetchWithTimeout:t}=await import("./QXBSAWH3.js");return await t(P,{timeout:e}),!0}catch{return!1}}var y="***";function be(e){return process.env.REDOCLY_TELEMETRY!=="off"&&e?.resolvedConfig.telemetry!=="off"}async function Oe({config:e,argv:t,exit_code:n,execution_time:r,spec_version:o,spec_keyword:i,spec_full_version:s,respect_x_security_auth_types:c,respect_source_description_types:f,respect_criterion_object_types:N,lint_rules_with_errors:T,lint_rules_with_warnings:b,lint_rules_with_ignored_problems:O,generate_client:a,eject_generator:l,bundle:G}){try{if(!t||!await F(1e3))return;let{_:[h],$0:pe,...D}=t,{RedoclyOAuthClient:K,getReuniteUrl:H}=await import("./IO7M7MGV.js"),q=new K(C),Q=H(e,D.residency),Z=await q.isAuthorized(Q),g=de();g||(g=`ann_${V()}`,ue(g));let E=k(o),X=[{id:h,object:"command",uri:`urn:redocly:cli:command:${h}`,logged_in:Z?"yes":"no",command:h,...ae(D,process.argv.slice(2)),node_version:process.version,npm_version:le(),version:C,exit_code:n,execution_time:r,metadata:process.env.REDOCLY_CLI_TELEMETRY_METADATA,environment_ci:process.env.CI,environment:process.env.REDOCLY_ENVIRONMENT,has_config:typeof e?.document?.parsed>"u"?"no":"yes",spec_version:o,spec_keyword:i,spec_full_version:s,respect_x_security_auth_types:E==="arazzo1"&&c?.length?JSON.stringify(c):void 0,respect_source_description_types:E==="arazzo1"&&f?.length?JSON.stringify(f):void 0,respect_criterion_object_types:E==="arazzo1"&&N?.length?JSON.stringify(N):void 0,lint_rules_with_errors:T?.length?JSON.stringify(T):void 0,lint_rules_with_warnings:b?.length?JSON.stringify(b):void 0,lint_rules_with_ignored_problems:O?.length?JSON.stringify(O):void 0,generate_client_builtin_generators:a?.generate_client_builtin_generators?.length?JSON.stringify(a.generate_client_builtin_generators):void 0,generate_client_custom_generators_count:a?.generate_client_custom_generators_count,generate_client_toolkit_imports:a?.generate_client_toolkit_imports?.length?JSON.stringify(a.generate_client_toolkit_imports):void 0,generate_client_error_category:a?.generate_client_error_category,generate_client_ejected_generators:a?.generate_client_ejected_generators?.length?JSON.stringify(a.generate_client_ejected_generators):void 0,generate_client_composed_apis_count:a?.generate_client_composed_apis_count,eject_generator_action:l?.eject_generator_action,eject_generator_name:l?.eject_generator_name,eject_generator_outcome:l?.eject_generator_outcome,eject_generator_conflicts:l?.eject_generator_conflicts,eject_generator_from_version:l?.eject_generator_from_version,eject_generator_to_version:l?.eject_generator_to_version,bundle_overlays_count:G?.bundle_overlays_count}],ee=R.mapToCloudEvent({type:"com.redocly.command.ran",source:"urn:redocly:cli",origin:"redocly-cli",env:"production",osPlatform:$.platform(),actor:{id:g,object:"user",uri:""},category:"product",data:X}),{otelTelemetry:te}=await import("./NNBSSORJ.js");te.send(ee)}catch{}}function De(e,t){for(let n of e.sourceDescriptions??[])n.type&&t.add(n.type)}function Ie(e,t){for(let n of e.workflows??[]){d(n.successActions,t),d(n.failureActions,t);for(let r of n.steps??[])W(r.successCriteria,t),d(r.onSuccess,t),d(r.onFailure,t)}d(Object.values(e.components?.successActions??{}),t),d(Object.values(e.components?.failureActions??{}),t)}function d(e,t){for(let n of e??[])W(n.criteria,t)}function W(e,t){for(let n of e??[]){let r=ie(n);r&&t.add(r)}}function ie(e){let t=e.type;return typeof t=="string"?t:t?.type||(e.condition?"simple":void 0)}function ke(e,t){for(let n of e.workflows??[]){for(let r of n["x-security"]??[]){let o=r.scheme;if(o?.type){let i=o.type==="http"?o.scheme:o.type;i&&t.add(i)}}for(let r of n.steps??[])for(let o of r["x-security"]??[]){let i=o.scheme;if(i?.type){let c=i.type==="http"?i.scheme:i.type;c&&t.add(c)}let s=o.schemeName;s&&t.add(s)}}}function se(e){return p.existsSync(e)&&p.statSync(e).isFile()}function ce(e){return p.existsSync(e)&&p.statSync(e).isDirectory()}function w(e){return e&&(I(e)?e.split("://")[0]+"://url":se(e)?e.replace(/.+\.([^.]+)$/,(t,n)=>"file-"+n):ce(e)?"folder":e)}function j(e,t,n){let r=Array.isArray(t)?t:[t];for(let o of r)o.length>1&&(e=e.replaceAll(o,n));return e}function Y(e,t){let n={};for(let[r,o]of Object.entries(e))t.includes(r)?n[r]=y:m(o)?n[r]=Y(o,t):n[r]=o;return n}function x(e,t,n=[]){if(Array.isArray(e))return e.forEach(r=>x(r,t,n)),n;if(m(e))for(let[r,o]of Object.entries(e))t.includes(r)&&typeof o=="string"?n.push(o):(m(o)||Array.isArray(o))&&x(o,t,n);return n}function ae(e,t){let n=["organization","o","input","i","author","a","clientCert","clientKey","caCert","server","S"],r=t.join(" "),o={};for(let[i,s]of Object.entries(e))if(n.includes(i))o[i]=y,r=j(r,s,y);else if(typeof s=="string"){let c=w(s);o[i]=c,r=j(r,s,c)}else if(Array.isArray(s)){o[i]=s.map(w);for(let c of s){let f=w(c);r.includes(c)&&(r=r.replaceAll(c,f))}}else if(m(s)){let c=x(s,n);for(let f of c)r=j(r,f,y);o[i]=Y(s,n)}else o[i]=s;return{arguments:JSON.stringify(o),raw_input:r}}var fe=process.platform==="win32"?A(J(process.execPath),"node_modules","npm","package.json"):A(J(process.execPath),"..","lib","node_modules","npm","package.json");function le(){try{return JSON.parse(M(fe,"utf8")).version}catch{}try{return ne("npm -v",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return"unknown"}}var ue=e=>{if(!(process.env.CI||!e))try{let n=A(U(),v);oe(n,e)}catch{}},de=()=>{if(!process.env.CI)try{let t=A(U(),v);return re(t)?M(t).toString().trim():void 0}catch{return}};export{_e as a,be as b,Oe as c,De as d,Ie as e,ke as f};
|
|
@@ -0,0 +1,53 @@
|
|
|
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 V}from"./XKENZH7W.js";import{c as I,d as N,e as ue,h as G,j as _,k as me,v as B,w as H}from"./5F7XFPS7.js";import{a as ce,b as W,c as pe,d as fe}from"./44US4AGQ.js";import"./IHUHQ7PO.js";import{a as ae}from"./64G5RPLP.js";import{e as ie}from"./GKPSJEG5.js";import{Q as oe,R as v,c as y,k as O,ka as S,qa as J,va as se}from"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";import{mkdir as jt,writeFile as kt}from"node:fs/promises";import Rt from"node:path";import{performance as Jt}from"node:perf_hooks";var Be=/^[a-zA-Z][a-zA-Z0-9]*(?:[_\-.][a-zA-Z0-9]+)*$/,He=/^[0-9a-f-]{8,}$/i,ze=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["date-time",/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["uri",/^https?:\/\/\S+$/],["ipv4",/^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/]],x=new WeakMap;function z(e){return{formats:ze.filter(([,t])=>t.test(e)).map(([t])=>t),values:[e],count:1,overflow:!1}}function q(e,t){if(!e)return t;if(!t)return e;let n={formats:e.formats.filter(r=>t.formats.includes(r)),values:[],count:e.count+t.count,overflow:e.overflow||t.overflow};if(!n.overflow){let r=[...e.values];for(let s of t.values)r.includes(s)||r.push(s);r.length>10?n.overflow=!0:n.values=r}return n}function D(e,t){x.set(e,t)}function U(e){return x.get(e)}function F(e,t){let n=x.get(e);n&&x.set(t,n)}function De(e){return e.length<=30&&!He.test(e)&&Be.test(e)}function X(e,t){return e.formats.length>0?{format:e.formats[0]}:t&&!e.overflow&&e.count>=4&&e.values.length>0&&e.values.length<=5&&e.values.length*2<=e.count&&e.values.every(De)?{enum:[...e.values].sort()}:{}}function T(e){let t=x.get(e);if(t){let n=typeof e.type=="string"?[e.type]:e.type??[];n.includes("string")&&Object.assign(e,X(t,n.length===1))}for(let n of Object.values(e.properties??{}))T(n);e.additionalProperties&&T(e.additionalProperties),e.items&&T(e.items);for(let n of e.oneOf??[])T(n)}function de(e){for(let t of Object.values(e.paths))for(let n of Object.values(t)){for(let r of Object.values(n.requestBody?.content??{}))T(r.schema);for(let r of Object.values(n.responses))for(let s of Object.values(r.content??{}))T(s.schema)}for(let t of Object.values(e.components?.schemas??{}))T(t);return e}var Oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Y=/^\d+$/,Ue=/^[0-9a-hjkmnp-tv-z]{26}$/i,Fe=/^[a-z][a-z0-9]*_(?=[0-9a-z]*\d)[0-9a-z]{10,}$/i,Le=/^[a-z](?=[a-z0-9]*\d)[a-z0-9]{23,24}$/,Q=new Set(ae),Ye=new Set(["get","head"]),le="application/x-www-form-urlencoded",he="multipart/form-data";function Ke(e){return e?Y.test(e)||Oe.test(e)||Ue.test(e)||Fe.test(e)||Le.test(e)?!0:/^[0-9a-f]{16,}$/i.test(e):!1}function ee(e){let t=e.split("/"),n=[],r=new Set;return{template:t.map((o,a)=>{if(!Ke(o))return o;let i=t[a-1],c=i?`${O(i,1)}Id`:"id",p=1;for(;r.has(c);)p+=1,c=i?`${O(i,1)}Id${p}`:`id${p}`;return r.add(c),n.push({name:c,value:o}),`{${c}}`}).join("/")||"/",params:n}}function $(e){if(e===null)return{type:"null"};if(Array.isArray(e)){if(e.length===0)return{type:"array"};let t=e.slice(0,20).map($);return{type:"array",items:E(t)}}switch(typeof e){case"string":{let t={type:"string"};return D(t,z(e)),t}case"boolean":return{type:"boolean"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"object":{let t=Object.entries(e);if(t.length>0&&(t.every(([a])=>Y.test(a))||t.every(([a])=>Oe.test(a))))return{type:"object",additionalProperties:E(t.map(([,a])=>$(a)))};let n={},r=[];for(let[o,a]of t)n[o]=$(a),r.push(o);let s={type:"object",properties:n};return r.length>0&&(s.required=r),s}default:return{}}}function E(e){if(e.length===0)return{};let[t,...n]=e,r=t;for(let s of n)r=L(r,s);return r}function ge(e){return Object.keys(e).length===0}function A(e){return e.additionalProperties?"map":e.type==="object"?"object":e.type==="array"?"array":"scalar"}function Z(e){return e.oneOf?e.oneOf.flatMap(Z):Array.isArray(e.type)?e.type.map(t=>{if(t==="object"){let r={type:"object"};return e.properties&&(r.properties=e.properties),e.required&&(r.required=e.required),e.additionalProperties&&(r.additionalProperties=e.additionalProperties),r}if(t==="array")return e.items?{type:"array",items:e.items}:{type:"array"};let n={type:t};return t==="string"&&F(e,n),n}):[e]}var We=.5,Xe=3;function ve(e,t){let n=Object.keys(e.properties??{}),r=Object.keys(t.properties??{});if(n.length===0||r.length===0)return 1;let s=new Set(r),o=n.filter(a=>s.has(a)).length;return o/(n.length+r.length-o)}function Ze(e,t){let n=A(e);if(n!==A(t))return!1;switch(n){case"scalar":return e.type===t.type||e.type==="integer"&&t.type==="number"||e.type==="number"&&t.type==="integer";case"object":return ve(e,t)>=We;default:return!0}}function we(e,t){switch(A(e)){case"scalar":{if(e.type!==t.type)return{type:"number"};if(e.type==="string"){let n=q(U(e),U(t));if(n){let r={type:"string"};return D(r,n),r}}return e}case"map":return{type:"object",additionalProperties:L(e.additionalProperties??{},t.additionalProperties??{})};case"object":{let n={...e.properties??{}};for(let[a,i]of Object.entries(t.properties??{}))n[a]=n[a]?L(n[a],i):i;let r=new Set(t.required??[]),s=(e.required??[]).filter(a=>r.has(a)),o={type:"object",properties:n};return s.length>0&&(o.required=s),o}case"array":{if(!e.items||!t.items){let n=e.items??t.items;return n?{type:"array",items:n}:{type:"array"}}return{type:"array",items:L(e.items,t.items)}}}}function Qe(e){let t=[...e],n=()=>t.filter(r=>A(r)==="object").length;for(;n()>Xe;){let r=-1,s=-1,o=-1;for(let a=0;a<t.length;a++)if(A(t[a])==="object")for(let i=a+1;i<t.length;i++){if(A(t[i])!=="object")continue;let c=ve(t[a],t[i]);c>o&&(o=c,r=a,s=i)}t[r]=we(t[r],t[s]),t.splice(s,1)}return t}var et=["boolean","integer","number","string","null"];function tt(e){if(e.length===1)return e[0];let t=[],n=new Set,r;for(let i of e)A(i)==="scalar"&&typeof i.type=="string"?(n.add(i.type),i.type==="string"&&(r=q(r,U(i)))):t.push(i);let s=et.filter(i=>n.has(i)),o=i=>{let c={type:i};return(typeof i=="string"?i==="string":i.includes("string"))&&r&&D(c,r),c};if(t.length===0)return s.length===1?o(s[0]):o(s);if(t.length===1&&s.length===1&&s[0]==="null"&&typeof t[0].type=="string")return{...t[0],type:[t[0].type,"null"]};let a=[...t];return s.length===1?a.push(o(s[0])):s.length>1&&a.push(o(s)),{oneOf:a}}function L(e,t){if(ge(e)||ge(t))return{};let n=Z(e);for(let r of Z(t)){let s=n.findIndex(o=>Ze(o,r));s===-1?n.push(r):n[s]=we(n[s],r)}return tt(Qe(n))}function nt(e){if(!e)return;let t=e.trim();if(!(!t.startsWith("{")&&!t.startsWith("[")))try{return JSON.parse(t)}catch{return}}function rt(e,t){let n=t?.match(/boundary="?([^";,]+)"?/i)?.[1];if(!n)return;let r={};for(let s of e.split(`--${n}`)){let o=s.match(/^\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)\r?\n$/);if(!o)continue;let[,a,i]=o,c=a.match(/\bname="([^"]*)"/i)?.[1];c!==void 0&&(r[c]=/\bfilename="/i.test(a)?{type:"string",format:"binary"}:$(i))}if(Object.keys(r).length!==0)return{type:"object",properties:r,required:Object.keys(r)}}function ye(e){let t=_(e.contentType);if(e.bodyJson!==void 0)return{mime:me(t)?t:"application/json",schema:$(e.bodyJson)};if(t===le&&e.bodyText){let r={};for(let[s,o]of new URLSearchParams(e.bodyText))r[s]=o;return Object.keys(r).length===0?void 0:{mime:le,schema:$(r)}}if(t===he&&e.bodyText){let r=rt(e.bodyText,e.contentType);return r?{mime:he,schema:r}:void 0}let n=nt(e.bodyText);if(n!==void 0)return{mime:"application/json",schema:$(n)}}function Se(e,t,n){let r=e.get(t);e.set(t,r?E([r,n]):n)}async function Pe(e){let t=await N(e.trafficPath);if(t.length===0)throw new Error("No traffic files found in the provided traffic path.");let n=B(e.server),r=new Map,s=new Set,o=0,a=0,i=p=>{let f=p.request.method.toLowerCase();if(!Q.has(f))return;let u=p.request.path||"/";if(n){let d=H(p.request,n);if(d===void 0)return;u=d}if(f==="query"&&e.openapiVersion==="3.1"){a+=1;return}!n&&p.request.host&&!ue(p.request.host)&&s.add(`${p.request.protocol}//${p.request.host}`);let{template:m,params:k}=ee(G(u)),P=`${f} ${m}`,l=r.get(P);l||(l={method:f,template:m,pathParams:new Map,queryParams:new Map,requestBodies:new Map,responses:new Map},r.set(P,l));for(let{name:d,value:g}of k){let h=l.pathParams.get(d);l.pathParams.set(d,{numeric:(h?.numeric??!0)&&Y.test(g),observations:q(h?.observations,z(g))})}for(let d of new Set(p.request.query.keys())){let g=p.request.query.getAll(d),h=l.queryParams.get(d),C=g.length>0&&g.every(R=>Y.test(R)),b=h?.observations;for(let R of g)b=q(b,z(R));l.queryParams.set(d,{numeric:(h?.numeric??!0)&&C,observations:b})}if(!Ye.has(f)){let d=ye(p.request);d&&Se(l.requestBodies,d.mime,d.schema)}if(p.response&&p.response.status>=100){let d=String(p.response.status),g=l.responses.get(d);g||(g={bodies:new Map},l.responses.set(d,g)),g.statusText??=p.response.statusText||void 0;let h=ye(p.response);h&&Se(g.bodies,h.mime,h.schema)}};for(let p of t){let f=await V(p,e.format);if(!f){S.warn(`Skipping traffic file with unrecognized format: ${p}
|
|
8
|
+
`);continue}o+=1;for await(let u of f.parse(p))i(u)}if(o===0)throw new J("No supported traffic files found to generate an OpenAPI description from.");if(r.size===0&&a>0)throw new J("All observed HTTP exchanges use the QUERY method, which OpenAPI 3.1 does not support. Use --openapi-version 3.2 to include them.");if(r.size===0)throw new J(n?`No HTTP exchanges in the traffic matched the server "${n}".`:"No HTTP exchanges were observed in the traffic. Cannot generate an OpenAPI description.");let c=n?[n]:Array.from(s).sort();return ot(r,e.openapiVersion,e.title??"Generated API",c)}function Te(e){return Object.values(e.paths).reduce((t,n)=>t+Object.keys(n).length,0)}function be(e,t){if(e.numeric)return{type:"integer"};let n={type:"string"};return e.observations&&Object.assign(n,X(e.observations,t)),n}function ot(e,t,n,r){let s={};for(let o of e.values()){let a=s[o.template]??={},i=[...Array.from(o.pathParams).map(([p,f])=>({name:p,in:"path",required:!0,schema:be(f,!1)})),...Array.from(o.queryParams).map(([p,f])=>({name:p,in:"query",required:!1,schema:be(f,!0)}))],c={operationId:st(o.method,o.template),responses:{}};if(i.length>0&&(c.parameters=i),o.requestBodies.size>0){let p={};for(let[f,u]of o.requestBodies)p[f]={schema:u};c.requestBody={content:p}}if(o.responses.size===0)c.responses.default={description:"Observed response"};else for(let[p,f]of o.responses){let u={description:f.statusText||"Observed response"};if(f.bodies.size>0){let m={};for(let[k,P]of f.bodies)m[k]={schema:P};u.content=m}c.responses[p]=u}a[o.method]=c}return{openapi:`${t}.0`,info:{title:n,version:"1.0.0"},...r.length>0?{servers:r.map(o=>({url:o}))}:{},paths:s}}function st(e,t){let n=t.split("/").filter(Boolean).map(r=>r.replace(/[{}]/g,"")).join("-");return`${e}-${n||"root"}`}function K(e,t){return`${e.toUpperCase()} ${t}`}function $e(e,t){let n;if(e.bodyJson!==void 0)try{n=JSON.stringify(e.bodyJson)}catch{n=void 0}if(n??=e.bodyText,!n)return;let r=n.trim();if(r)return r.length>t?`${r.slice(0,t)}\u2026[truncated]`:r}function Ae(e){if(!e)return"";let t=e.bodyJson;return t===void 0?e.bodyText?_(e.contentType)||"text":"":t===null?"null":Array.isArray(t)?`array<${t.length>0?je(t[0]):""}>`:je(t)}function je(e){return y(e)?Object.keys(e).sort().join(","):e===null?"null":typeof e}async function ke(e){let t=e.perGroup??2,n=e.perOperation??4,r=e.maxBodyChars??2e3,s=B(e.server),o=await N(e.trafficPath),a=new Map;for(let c of o){let p=await V(c,e.format);if(p)for await(let f of p.parse(c)){let u=f.request.method.toUpperCase();if(!Q.has(u.toLowerCase()))continue;let m=f.request.path||"/";if(s){let R=H(f.request,s);if(R===void 0)continue;m=R}let k=G(m),{template:P}=ee(k),l=f.response&&f.response.status>=100?f.response:void 0,d=l?.status,g=`${Ae(f.request)}\u2192${Ae(l)}`,h=a.get(K(u,P));h||(h=new Map,a.set(K(u,P),h));let C=`${d??""} ${g}`,b=h.get(C);b||(b=[],h.set(C,b)),!(b.length>=t)&&b.push({method:u,path:k,query:f.request.query.toString(),status:d,requestContentType:f.request.contentType,requestBody:$e(f.request,r),responseContentType:l?.contentType,responseBody:l?$e(l,r):void 0})}}let i=new Map;for(let[c,p]of a){let f=[];for(let u=0;u<t&&f.length<n;u++)for(let m of p.values()){if(f.length>=n)break;m[u]&&f.push(m[u])}i.set(c,f)}return i}var it=e=>`You are an expert API designer. You are given one operation from an OpenAPI ${e} description that was inferred mechanically from recorded HTTP traffic, the component schemas it references, and a sample of the real recorded HTTP exchanges for that operation. The inferred description is only a hypothesis: types are coarse, every observed property is marked required, and descriptions are missing. Alternative body shapes observed in the traffic appear as "oneOf" variants or type unions. Common string formats (uuid, date-time, date, email, uri, ipv4) and small closed enums are detected conservatively from the observed values.
|
|
9
|
+
|
|
10
|
+
Refine the operation into the most accurate OpenAPI ${e} definition you can justify from the evidence, while staying conservative:
|
|
11
|
+
- Keep the path template and the HTTP method exactly as given. Do not rename path parameters, do not move parameters to the path item level, and keep every response status code. The result is programmatically checked and rejected otherwise.
|
|
12
|
+
- Keep the operationId unless it is clearly wrong.
|
|
13
|
+
- Narrow property types where the samples clearly support it (formats such as date-time, uuid, email, uri; integer vs number; enums when a field only ever takes a small fixed set of values). Verify the formats and enums already detected against the samples; correct or extend them where justified. The detected formats and enums were derived from the full recorded traffic while you see only a subset of it, so never remove a detected format or enum value merely because the samples do not show it \u2014 correct one only when a sample contradicts it.
|
|
14
|
+
- Relax "required" for properties that are plausibly optional (e.g. absent in some samples, or clearly nullable). Express nullable values as type unions such as ["string", "null"].
|
|
15
|
+
- When a request or response body has alternative shapes \u2014 the baseline shows "oneOf" variants, or the samples show clearly different payloads \u2014 model them explicitly with "oneOf". Name each variant in components/schemas, and add a "discriminator" when a property (such as "type" or "kind") selects the variant.
|
|
16
|
+
- Factor structure shared between variants or schemas with "allOf": extract the common base into components/schemas and compose each variant as "allOf" of the base plus its specific properties.
|
|
17
|
+
- Keep the $ref references to the component schemas you were given. You may refine the definition of a referenced component when the samples justify it, and you may add new components, but never rename an existing component and never reuse a reserved component name listed in the input.
|
|
18
|
+
- Add concise, useful "summary" and "description" fields to the operation, its parameters and important schema properties.
|
|
19
|
+
- Add example values drawn from the real samples where helpful, but never copy values that look like secrets or personal data (tokens, API keys, passwords, session identifiers, email addresses, personal names); use clearly fictional placeholder values instead.
|
|
20
|
+
|
|
21
|
+
Output ONLY a YAML document with this exact top-level structure:
|
|
22
|
+
|
|
23
|
+
paths:
|
|
24
|
+
<the path template exactly as given>:
|
|
25
|
+
<the method>:
|
|
26
|
+
...the refined operation...
|
|
27
|
+
components:
|
|
28
|
+
schemas:
|
|
29
|
+
...only the component schemas you changed or added; omit "components" entirely when there are none...
|
|
30
|
+
|
|
31
|
+
Do not wrap the output in Markdown code fences. Do not add any commentary before or after the document.`;function at(e){return e.length===0?"(no sample exchanges were captured)":e.map((t,n)=>{let r=[],s=t.query?`?${t.query}`:"";return r.push(`### Exchange ${n+1}`),r.push(`${t.method} ${t.path}${s}`),t.requestContentType&&r.push(`Request Content-Type: ${t.requestContentType}`),t.requestBody&&r.push(`Request body: ${t.requestBody}`),t.status!==void 0&&r.push(`Response status: ${t.status}`),t.responseContentType&&r.push(`Response Content-Type: ${t.responseContentType}`),t.responseBody&&r.push(`Response body: ${t.responseBody}`),r.join(`
|
|
32
|
+
`)}).join(`
|
|
33
|
+
|
|
34
|
+
`)}function Re(e){let t=[];return t.push(`# Operation to refine (inferred from traffic)
|
|
35
|
+
|
|
36
|
+
\`\`\`yaml
|
|
37
|
+
${v({paths:{[e.path]:{[e.method]:e.operation}}})}\`\`\``),Object.keys(e.components).length>0&&t.push(`# Component schemas referenced by this operation (current definitions)
|
|
38
|
+
|
|
39
|
+
\`\`\`yaml
|
|
40
|
+
${v({components:{schemas:e.components}})}\`\`\``),e.reservedComponentNames.length>0&&t.push(`# Reserved component names (used elsewhere in the description; do not redefine or reuse them)
|
|
41
|
+
|
|
42
|
+
${e.reservedComponentNames.join(", ")}`),t.push(`# Recorded HTTP exchanges for this operation
|
|
43
|
+
|
|
44
|
+
${at(e.samples)}`),t.push(`Refine ${e.method.toUpperCase()} ${e.path} as instructed and output only the YAML document.`),{system:it(e.openapiVersion),user:t.join(`
|
|
45
|
+
|
|
46
|
+
`)}}var Je=/^#\/components\/schemas\/(.+)$/;function te(e,t){if(Array.isArray(e)){for(let n of e)te(n,t);return}if(y(e)){if(typeof e.$ref=="string"){let n=e.$ref.match(Je);n&&t.add(n[1])}if(y(e.discriminator)&&y(e.discriminator.mapping)){for(let n of Object.values(e.discriminator.mapping))if(typeof n=="string"){let r=n.match(Je);t.add(r?r[1]:n)}}for(let n of Object.values(e))te(n,t)}}function Ee(e,t){let n=new Set,r=[e];for(;r.length>0;){let s=new Set;te(r.pop(),s);for(let o of s)!n.has(o)&&o in t&&(n.add(o),r.push(t[o]))}return n}function ct(e){let t=e.components?.schemas;if(!t)return;let n=Ee(e.paths,t);for(let r of Object.keys(t))n.has(r)||delete t[r];Object.keys(t).length===0&&delete e.components}function pt(e,t,n){let r=ce(e),s;try{s=oe(r)}catch(f){throw new Error(`the provider did not return valid YAML: ${f instanceof Error?f.message:String(f)}`)}if(!y(s))throw new Error('the response is not a YAML document with a "paths" object');let o=s.paths;if(!y(o))throw new Error('the response is not a YAML document with a "paths" object');let a=o[t];if(!y(a))throw new Error(`the response does not keep the path template "${t}"`);let i=a[n];if(!y(i))throw new Error(`the response does not contain the ${n.toUpperCase()} operation`);let c=s.components,p=y(c)?c.schemas:void 0;return{operation:i,components:y(p)?p:{}}}function ft(e,t){let n=y(t.responses)?t.responses:{};return Object.keys(e.responses).filter(r=>!(r in n))}async function ut(e){let t=e.document.components?.schemas??{},n=Ee(e.operation,t),r={};for(let m of n)r[m]=t[m];let s=Object.keys(t).filter(m=>!n.has(m)),{system:o,user:a}=Re({openapiVersion:e.document.openapi,path:e.path,method:e.method,operation:e.operation,components:r,reservedComponentNames:s,samples:e.samples}),{text:i}=await pe(e.provider,{system:o,user:a,model:e.model}),c=pt(i,e.path,e.method),p=ft(e.operation,c.operation);if(p.length>0)throw new Error(`the response dropped observed response status(es): ${p.join(", ")}`);if(typeof c.operation.operationId!="string")throw new Error("the response dropped the operationId");let f=Object.keys(c.components).filter(m=>s.includes(m));if(f.length>0)throw new Error(`the response redefines reserved component(s): ${f.join(", ")}`);let u={openapi:e.document.openapi,info:e.document.info,paths:{[e.path]:{[e.method]:c.operation}},components:{schemas:{...t,...c.components}}};return await W(v(u),e.config),c}function mt(e,t,n,r){e.paths[t][n]=r.operation,Object.keys(r.components).length>0&&(e.components??={schemas:{}},Object.assign(e.components.schemas,r.components))}async function Me(e){let t=structuredClone(e.baseline),n=await se({extends:["spec"]}),r=[];for(let[i,c]of Object.entries(e.baseline.paths))for(let[p,f]of Object.entries(c))r.push({path:i,method:p,operation:f});let o=(await fe({items:r,concurrency:e.concurrency??1,action:"Refining",successNote:"refined",failureNote:"kept the baseline",label:({path:i,method:c})=>`${c.toUpperCase()} ${i}`,run:async({path:i,method:c,operation:p})=>{let f=await ut({provider:e.provider,model:e.model,document:t,path:i,method:c,operation:p,samples:e.samplesByOperation.get(K(c,i))??[],config:n});return mt(t,i,c,f),f}})).filter(i=>i!==null).length;if(o===0)throw new Error(`the ${e.provider} provider did not produce a usable refinement for any operation`);ct(t);let a=v(t);return await W(a,n),{yaml:a,document:t,refined:o,total:r.length}}var dt=2,lt=2,ht=.75,gt=2,xe=new Set(["integer","number"]),qe=new WeakMap;function w(e){let t=qe.get(e);if(t!==void 0)return t;let n;if(e.$ref!==void 0)n=`ref(${e.$ref})`;else if(e.oneOf)n=`oneOf(${e.oneOf.map(w).sort().join("|")})`;else{let s=[`type=${(Array.isArray(e.type)?[...e.type].sort().join(","):e.type)??""}`];if(e.properties){let o=Object.entries(e.properties).map(([a,i])=>`${JSON.stringify(a)}:${w(i)}`).sort().join(",");s.push(`props{${o}}`)}e.additionalProperties&&s.push(`values(${w(e.additionalProperties)})`),e.items&&s.push(`items(${w(e.items)})`),n=s.join(";")}return qe.set(e,n),n}function yt(e){return e.$ref===void 0&&e.type==="object"&&e.oneOf===void 0&&e.additionalProperties===void 0&&Object.keys(e.properties??{}).length>=dt}function Ce(e,t){for(let n of t)e.set(n,(e.get(n)??0)+1)}function M(e,t,n){if(e.oneOf){e.oneOf.forEach((o,a)=>M(o,{...t,path:`${t.path}/oneOf/${a}`,fallbackHints:[]},n));return}let r=t.container,s=`${t.path}/`;if(yt(e)){let o=w(e),a=n.get(o);a||(a={keys:[o],schemas:[],merged:{},contexts:new Set,primaryVotes:new Map,fallbackVotes:new Map},n.set(o,a)),a.schemas.push(e),a.contexts.add(`${t.container}#${t.path}`),Ce(a.primaryVotes,t.primaryHints),Ce(a.fallbackVotes,t.fallbackHints),r=o,s=""}for(let[o,a]of Object.entries(e.properties??{}))M(a,{container:r,path:`${s}${o}`,primaryHints:[o],fallbackHints:[]},n);e.additionalProperties&&M(e.additionalProperties,{container:r,path:`${s}additionalProperties`,primaryHints:t.primaryHints.map(o=>O(o,1)),fallbackHints:t.fallbackHints.map(o=>O(o,1))},n),e.items&&M(e.items,{container:r,path:`${s}items`,primaryHints:t.primaryHints.map(o=>O(o,1)),fallbackHints:t.fallbackHints.map(o=>O(o,1))},n)}function St(e){return e.split("/").filter(n=>n&&!n.startsWith("{")).at(-1)}function bt(e){let t=new Map;for(let[n,r]of Object.entries(e.paths)){let s=St(n),o=s?O(s,1):void 0;for(let[a,i]of Object.entries(r)){for(let[c,p]of Object.entries(i.requestBody?.content??{}))M(p.schema,{container:`request ${a} ${n} ${c}`,path:"",primaryHints:o?[o]:[],fallbackHints:o?[`${o} request`]:[]},t);for(let[c,p]of Object.entries(i.responses)){let f=Number(c)>=400;for(let[u,m]of Object.entries(p.content??{}))M(m.schema,{container:`response ${a} ${n} ${c} ${u}`,path:"",primaryHints:f?["error"]:o?[o]:[],fallbackHints:f?o?[`${o} error`]:[]:o?[`${o} response`]:[]},t)}}}return t}function Ie(e){return Object.keys(e.properties??{})}function Ot(e,t){let n=Ie(e),r=new Set(Ie(t)),s=n.filter(a=>r.has(a)).length,o=n.length+r.size-s;return o===0?0:s/o}function Ne(e){if(e.$ref!==void 0||e.properties||e.additionalProperties||e.items||e.oneOf)return;let t=typeof e.type=="string"?[e.type]:e.type;if(!(!t||t.some(n=>n==="object"||n==="array")))return t}function ne(e){return Object.keys(e).length===0}function _e(e,t){if(w(e)===w(t)||ne(e)||ne(t))return!0;let n=Ne(e),r=Ne(t);if(n&&r){let o=new Set(n.filter(i=>i!=="null")),a=new Set(r.filter(i=>i!=="null"));return o.size===a.size&&[...o].every(i=>a.has(i))?!0:[...o].every(i=>xe.has(i))&&[...a].every(i=>xe.has(i))}let s=o=>o.type==="array"||o.items!==void 0;return s(e)&&s(t)?!e.items||!t.items||_e(e.items,t.items):!1}function vt(e,t){let n=t.merged.properties??{};return Object.entries(e.merged.properties??{}).every(([r,s])=>!(r in n)||_e(s,n[r]))}function wt(e){let t=[...e];for(;t.length>1;){let n=-1,r=-1,s=0;for(let i=0;i<t.length;i++)for(let c=i+1;c<t.length;c++){let p=Ot(t[i].merged,t[c].merged);p>=ht&&p>s&&vt(t[i],t[c])&&(s=p,n=i,r=c)}if(n===-1)break;let o=t[n],a=t[r];o.keys.push(...a.keys),o.schemas.push(...a.schemas),o.merged=E([o.merged,a.merged]);for(let i of a.contexts)o.contexts.add(i);for(let[i,c]of a.primaryVotes)o.primaryVotes.set(i,(o.primaryVotes.get(i)??0)+c);for(let[i,c]of a.fallbackVotes)o.fallbackVotes.set(i,(o.fallbackVotes.get(i)??0)+c);t.splice(r,1)}return t}function re(e,t){return e<t?-1:e>t?1:0}function Pt(e){return e.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function Ge(e){return[...e.entries()].sort(([t,n],[r,s])=>s-n||re(t,r)).map(([t])=>t)}function Tt(e){let t=[...e].sort((r,s)=>s.contexts.size-r.contexts.size||s.schemas.length-r.schemas.length||re(r.keys[0],s.keys[0])),n=new Set;return t.map(r=>{let s=[...Ge(r.primaryVotes),...Ge(r.fallbackVotes)].map(Pt).filter(a=>a.length>0);s.length===0&&s.push("Schema");let o=s.find(a=>!n.has(a));for(let a=2;o===void 0;a++){let i=`${s[0]}${a}`;n.has(i)||(o=i)}return n.add(o),{group:r,name:o}})}function j(e,t,n=!1){if(!n){let s=t.get(w(e));if(s!==void 0)return{$ref:`#/components/schemas/${s}`}}let r={...e};return F(e,r),e.properties&&(r.properties=Object.fromEntries(Object.entries(e.properties).map(([s,o])=>[s,j(o,t)]))),e.additionalProperties&&(r.additionalProperties=j(e.additionalProperties,t)),e.items&&(r.items=j(e.items,t)),e.oneOf&&(r.oneOf=e.oneOf.map(s=>j(s,t))),r}function $t(e){let t=Object.values(e.properties??{}),n=t.filter(r=>r.type==="array"&&(!r.items||ne(r.items)));return n.length>0&&t.length-n.length<=gt}function At(e){let t=0,n=0;for(let r of e.primaryVotes.values())t+=r,n=Math.max(n,r);return n*2>t}function Ve(e){let t=bt(e);for(let i of t.values())i.merged=E(i.schemas);let r=wt([...t.values()]).filter(i=>i.contexts.size>=lt&&(At(i)||!i.schemas.some($t)));if(r.length===0)return e;let s=Tt(r),o=new Map;for(let{group:i,name:c}of s)for(let p of i.keys)o.set(p,c);let a={};for(let{group:i,name:c}of[...s].sort((p,f)=>re(p.name,f.name)))a[c]=j(i.merged,o,!0);for(let i of Object.values(e.paths))for(let c of Object.values(i)){for(let p of Object.values(c.requestBody?.content??{}))p.schema=j(p.schema,o);for(let p of Object.values(c.responses))for(let f of Object.values(p.content??{}))f.schema=j(f.schema,o)}return e.components={schemas:a},e}async function Et(e,t){let n=I(e);await jt(Rt.dirname(n),{recursive:!0}),await kt(n,t,"utf8")}async function bn({argv:e}){if(e.type!=="openapi")throw new J(`Unsupported spec type "${e.type}". Only "openapi" is supported.`);let t=Jt.now(),n=I(e.traffic),r=e["traffic-format"],s=de(Ve(await Pe({trafficPath:n,format:r,openapiVersion:e["openapi-version"],title:e.title,server:e.server})));S.info(`Inferred a baseline OpenAPI description from traffic: ${Te(s)} operation(s).
|
|
47
|
+
`);let o=v(s);if(e["with-ai"]){let a=e["ai-provider"];S.info(`Refining the description with AI provider "${a}"...
|
|
48
|
+
`),S.warn(`Note: --with-ai sends samples of the recorded traffic (URLs, query strings, request and response bodies) to the selected AI provider. Make sure the traffic contains no secrets or personal data you are not allowed to share.
|
|
49
|
+
`);let i=await ke({trafficPath:n,format:r,server:e.server});try{let c=await Me({provider:a,model:e["ai-model"],baseline:s,samplesByOperation:i,concurrency:e["ai-concurrency"]});o=c.yaml,S.info(`AI refinement complete: ${c.refined} of ${c.total} operation(s) refined (${a}).
|
|
50
|
+
`)}catch(c){S.warn(`AI refinement failed, falling back to the baseline description: ${c instanceof Error?c.message:String(c)}
|
|
51
|
+
`)}}e.output?(await Et(e.output,o),S.info(`Written to: ${I(e.output)}
|
|
52
|
+
`)):S.output(o),S.info(`Done in ${ie(t)}.
|
|
53
|
+
`)}export{bn as handleGenerateSpec};
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{c as r}from"./
|
|
7
|
+
import{c as r}from"./4ZCKAKVF.js";var s="components",p="paths",i="webhooks",O="x-webhooks",c="channels",f="operations";function e(o,n){if(r(o)){n(o);for(let t of Object.keys(o))e(o[t],n)}else if(Array.isArray(o))for(let t of o)e(t,n)}function S(o){return o.startsWith(`#/${s}/`)}export{s as a,p as b,i as c,O as d,c as e,f,e as g,S as h};
|
|
@@ -4,6 +4,6 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as m,j as C,o as a,p,q as T,r as l,s as h,t as f,u as d}from"./
|
|
7
|
+
import{b as m,j as C,o as a,p,q as T,r as l,s as h,t as f,u as d}from"./5F7XFPS7.js";import{c as g}from"./4ZCKAKVF.js";import A from"node:path";function L(e,n){if(C(e)!=="application/x-www-form-urlencoded"||!Array.isArray(n))return;let o=new URLSearchParams;for(let s of n){if(!g(s))continue;let t=a(s.name);t!==void 0&&o.append(t,a(s.value)??"")}return o.size>0?o.toString():void 0}function K(e,n,o){let s=e?.request,t=e?.response;if(!s)return null;let r=s?.postData,i=a(r?.mimeType),u=r?.text??L(i,r?.params),c=a(r?.encoding),y=t?.content?.text,S=a(t?.content?.encoding),q=p(t?.status);return l({method:a(s?.method),url:a(s?.url),requestHeaders:s?.headers,requestBody:T(u,c),requestContentType:i,responseStatus:q===0?void 0:q,responseStatusText:a(t?.statusText),responseHeaders:t?.headers,responseBody:T(y,S),responseContentType:a(t?.content?.mimeType),startedAt:a(e?.startedDateTime),raw:e},n,o)}var b=class{id="har";canParse(n,o){if(A.extname(n).toLowerCase()===".har")return!0;let t=o.toLowerCase();return t.includes('"log"')&&t.includes('"entries"')}async*parse(n){let o=0;for await(let s of f(n,"log.entries")){let t=K(s,o,n);t&&(yield t),o+=1}}};import $ from"node:path";function H(e){let n=a(e.url??e.uri);if(n)return{url:n};let o=a(e.host??e.headers?.host),s=a(e.path??e.request_uri),t=a(e.scheme??e.forwarded_proto);return o&&s?{url:`${t??"http"}://${o}${s}`,schemeKnown:!!t}:{url:s,schemeKnown:!!t}}function z(e,n,o){let s=e?.request??e?.req??e?.http?.request;if(!s)return null;let t=e?.response??e?.res??e?.http?.response,r=t?.body??t?.raw_body??t?.payload??t?.data,i=s?.body??s?.raw_body??s?.payload??s?.data,{url:u,schemeKnown:c}=H(s);return l({method:a(s?.method??s?.http_method),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:i,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode),responseHeaders:t?.headers,responseBody:r,responseContentType:d(t?.headers),startedAt:a(e?.started_at??e?.startedAt??e?.timestamp),raw:e},n,o)}var x=class{id="kong";canParse(n,o){if($.extname(n).toLowerCase()===".kong")return!0;let t=o.toLowerCase();return t.includes('"latencies"')||t.includes('"request"')&&t.includes('"response"')&&t.includes('"route"')}async*parse(n){let o=(await m(n,16)).trim().slice(0,1),s=0;if(o==="["){for await(let t of f(n)){let r=z(t,s,n);r&&(yield r),s+=1}return}for await(let t of h(n)){let r=z(t,s,n);r&&(yield r),s+=1}}};import R from"node:path";function U(e){return e?.request??e?.req??e?.httpRequest??e?.http?.request??e}function I(e){return e?.response??e?.res??e?.httpResponse??e?.http?.response}function O(e,n){let o=a(n?.url??n?.uri??n?.requestUrl??e?.url);if(o)return{url:o};let s=a(n?.host??n?.headers?.host??e?.host),t=a(n?.path??e?.path??n?.pathname),r=a(n?.scheme??e?.scheme);return s&&t?{url:`${r??"http"}://${s}${t}`,schemeKnown:!!r}:{url:t,schemeKnown:!!r}}function k(e,n,o){let s=U(e),t=I(e),r=s?.body??s?.bodyText??s?.payload??s?.data??s?.rawBody,i=t?.body??t?.bodyText??t?.payload??t?.data??t?.rawBody,{url:u,schemeKnown:c}=O(e,s);return l({method:a(s?.method??s?.httpMethod??e?.method??e?.httpMethod),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:r,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode??e?.status??e?.statusCode),responseHeaders:t?.headers,responseBody:i,responseContentType:d(t?.headers),startedAt:a(e?.startedAt??e?.timestamp??e?.time),raw:e},n,o)}var w=class{id="ndjson";canParse(n,o){let s=R.extname(n).toLowerCase();if(s===".ndjson"||s===".jsonl"||s===".jsonlines")return!0;let t=o.lastIndexOf(`
|
|
8
8
|
`),i=(t===-1?o:o.slice(0,t)).split(`
|
|
9
9
|
`).map(u=>u.trim()).find(Boolean);if(!i?.startsWith("{")||!i.endsWith("}"))return!1;try{return JSON.parse(i),!0}catch{return!1}}async*parse(n){let o=0;for await(let s of h(n)){let t=k(s,o,n);t&&(yield t),o+=1}}};import J from"node:path";function P(e){if(!e)return{};let n=e.trim().split(/\s+/);return n.length<2?{}:{method:n[0],path:n[1],protocol:n[2]}}function W(e,n){let o=a(n?.url??n?.request_uri??n?.uri??e?.url??e?.request_url??e?.absolute_uri),s=P(a(e?.request??n?.request_line)),t=a(n?.request_uri??n?.uri??n?.path??e?.request_uri??e?.uri)??s.path;if(o?.startsWith("http://")||o?.startsWith("https://"))return{url:o};let r=a(n?.host??n?.headers?.host??e?.host??e?.http_host??e?.server_name??e?.vhost),i=a(e?.scheme??n?.scheme??e?.request_scheme),u=!!i;if(r&&(o||t)){let c=i??"http",y=o??t;return y?.startsWith("/")?{url:`${c}://${r}${y}`,schemeKnown:u}:{url:`${c}://${r}/${y}`,schemeKnown:u}}return{url:o??t,schemeKnown:u}}function E(e,n,o){let s=g(e?.request)?e.request:e,t=g(e?.response)?e.response:void 0,r=P(a(e?.request)),i=a(s?.method??s?.request_method??e?.request_method??e?.method)??r.method,{url:u,schemeKnown:c}=W(e,s);return l({method:i,url:u,schemeKnown:c,requestHeaders:s?.headers??s?.request_headers??e?.request_headers??e?.headers,requestBody:s?.body??s?.request_body??e?.request_body??e?.body,requestContentType:d(s?.headers??s?.request_headers??e?.request_headers),responseStatus:p(t?.status??t?.status_code??e?.status??e?.status_code??e?.response_status),responseHeaders:t?.headers??t?.response_headers??e?.response_headers??e?.headers_out,responseBody:t?.body??t?.response_body??e?.response_body,responseContentType:d(t?.headers??t?.response_headers??e?.response_headers),startedAt:a(e?.time_iso8601??e?.timestamp??e?.time??e?.time_local??e?.["@timestamp"]),raw:e},n,o)}async function*j(e){if((await m(e,16)).trim().slice(0,1)==="["){yield*f(e);return}for await(let o of h(e))yield o}var N=class{id="nginx-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("nginx"))return!0;let r=o.toLowerCase();return r.includes('"request_uri"')||r.includes('"time_iso8601"')||r.includes('"upstream_response_time"')||r.includes('"remote_addr"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}},_=class{id="apache-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("apache"))return!0;let r=o.toLowerCase();return r.includes('"request_method"')||r.includes('"request_uri"')||r.includes('"vhost"')||r.includes('"response_status"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}};var B=[new b,new x,new N,new _,new w];async function le(e,n){if(n!=="auto"){let s=B.find(t=>t.id===n);if(!s)throw new Error(`Unsupported parser format: ${n}`);return s}let o=await m(e);return B.find(s=>s.canParse(e,o))}export{le as a};
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a,b,c}from"./
|
|
7
|
+
import{a,b,c}from"./NFGCHP5P.js";import"./TFPMT2XD.js";import"./76AJ5P4Y.js";import"./QQ2PGWE6.js";import"./4AXMK6B2.js";import"./D3C6XIMY.js";import"./WZXA5XPB.js";import"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";export{b as typescriptDocs,a as typescriptGenerator,c as typescriptSample};
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a}from"./
|
|
7
|
+
import{a}from"./JZV7EL4R.js";import"./HIMEF7J2.js";import"./76AJ5P4Y.js";import"./QQ2PGWE6.js";import"./4AXMK6B2.js";import"./D3C6XIMY.js";import"./WZXA5XPB.js";import"./4ZCKAKVF.js";import"./6RTITFQA.js";import"./RFWIIJFG.js";export{a as tanstackQueryGenerator};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as S,c as N,e as R,j as g,k as _,o as v,q as F,r as U,s as b,v as s}from"./
|
|
7
|
+
import{b as S,c as N,e as R,j as g,k as _,o as v,q as F,r as U,s as b,v as s}from"./GKPSJEG5.js";import{ca as y,da as $,ea as i,ia as u,ka as n,ra as k,ta as T,u as O,xa as B,ya as E}from"./4ZCKAKVF.js";import{writeFileSync as L}from"fs";import{resolve as j}from"path";import{performance as q}from"perf_hooks";var P={};async function Y({argv:e,config:l,version:W,collectSpecData:G}){let A=await S(e.apis,l),a={errors:0,warnings:0,ignored:0},I=N(l);for(let{path:o,alias:c,output:J}of A)try{let d=q.now(),p=l.forAlias(c);p.skipPreprocessors(e["skip-preprocessor"]),p.skipDecorators(e["skip-decorator"]);let m=e.overlay??p.resolvedConfig.overlays?.map(t=>O(t)?t:j(I,t));m?.length&&(P.bundle_overlays_count=(P.bundle_overlays_count??0)+m.length),c===void 0?n.info(u(`bundling ${s(o)}...
|
|
8
8
|
`)):n.info(u(`bundling ${s(o)} using configuration for api '${c}'...
|
|
9
9
|
`));let{bundle:D,problems:w,...x}=await T({ref:o,config:p,dereference:e.dereferenced,removeUnusedComponents:e["remove-unused-components"],keepUrlRefs:e["keep-url-references"],componentRenamingConflicts:e["component-renaming-conflicts-severity"],componentNamesStrategy:e["component-names-strategy"],overlays:m,collectSpecData:G}),r=B(w),{outputFile:f,ext:K}=F({entrypoint:o,output:J,argvOutput:e.output,ext:e.ext,entries:e?.apis?.length||0});if(r.errors===0||e.force)if(f){let t=g(b(D.parsed),K,e.dereferenced);_(f,t)}else{let t=g(b(D.parsed),e.ext||"yaml",e.dereferenced);n.output(t)}a.errors+=r.errors,a.warnings+=r.warnings,a.ignored+=r.ignored,E(w,{format:"codeframe",totals:r,version:W,command:"bundle"}),e.metafile&&(A.length>1&&n.warn('[WARNING] "--metafile" cannot be used with multiple apis. Skipping...'),L(e.metafile,JSON.stringify(x),"utf-8"));let h=R(d);r.errors>0?e.force?n.info(`\u2753 Created a bundle for ${i(s(o))} at ${i(f||"stdout")} with errors ${y(h)}.
|
|
10
10
|
${$("Errors ignored because of --force")}.
|
|
@@ -106,7 +106,7 @@ discriminated union on `kind`: `scalar`, `array`, `object`, `record`, `ref`,
|
|
|
106
106
|
| `isNullable(schema)` / `unwrapNullable(schema)` | Detect and strip `null` union members (`Optional[T]`, pointers, `Option<T>`). |
|
|
107
107
|
| `enumValues(schema)` | Values plus SCREAMING_SNAKE member-name suggestions. |
|
|
108
108
|
| `headerCoerceType(schema, model)` | Response-header coerce hint (`integer`/`number`/`boolean`/`string`) through refs, nullables, and allOf wrappers. |
|
|
109
|
-
| `casing` / `identifierFor(name, { style, reserved })` | camel/pascal/snake/screaming; keyword-safe identifiers (`RESERVED_WORDS.python/go/typescript` shipped).
|
|
109
|
+
| `casing` / `identifierFor(name, { style, reserved })` | camel/pascal/snake/screaming; keyword-safe identifiers (`RESERVED_WORDS.python/go/php/java/typescript` shipped). |
|
|
110
110
|
| `uniqueIdentifiers(names, { style, reserved, taken })` | The same, made unique among themselves and among names you already took — for a signature that takes one argument per parameter. |
|
|
111
111
|
| `Printer` | Indentation-aware text builder — no manual whitespace bookkeeping. |
|
|
112
112
|
| `docText(description)` | Description as trimmed lines for any comment syntax. |
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "cli" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator cli --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "cli" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator cli --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "cli" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator cli --update`.
|
|
@@ -86,5 +86,5 @@ export default {
|
|
|
86
86
|
docs: cliDocs,
|
|
87
87
|
requires: ["typescript","zod"],
|
|
88
88
|
errorModes: ["throw"],
|
|
89
|
-
requiresGenerator: '^0.
|
|
89
|
+
requiresGenerator: '^0.8.0',
|
|
90
90
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "cli" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator cli --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -332,5 +332,5 @@ export default {
|
|
|
332
332
|
"argsStyle": "inputs follow the target language's own idiom",
|
|
333
333
|
"importExt": "the generated file has no relative imports"
|
|
334
334
|
},
|
|
335
|
-
requiresGenerator: '^0.
|
|
335
|
+
requiresGenerator: '^0.8.0',
|
|
336
336
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Ejected from @redocly/client-generator@0.
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "go" generator.
|
|
2
2
|
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
3
|
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
4
|
// `redocly eject-generator go --update`.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Ejected from @redocly/client-generator@0.8.0 — the built-in "java" generator.
|
|
2
|
+
// This file is yours: edit freely; the generated client stays machine-owned and is
|
|
3
|
+
// rebuilt by `redocly generate-client`. Newer generator versions merge in with
|
|
4
|
+
// `redocly eject-generator java --update`.
|
|
5
|
+
// The `client` stage: the `Servers` helper class of one static method per
|
|
6
|
+
// declared server.
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
type ApiModel,
|
|
10
|
+
identifierFor,
|
|
11
|
+
type ServerModel,
|
|
12
|
+
serverUrlParts,
|
|
13
|
+
} from '@redocly/client-generator';
|
|
14
|
+
import type { JavaPrinter } from '@redocly/client-generator/printers/java';
|
|
15
|
+
|
|
16
|
+
import { JAVA, javaString, memberName } from './naming.ts';
|
|
17
|
+
|
|
18
|
+
/** The server URL as a Java expression: literals concatenated with declared-variable args. */
|
|
19
|
+
function serverUrlExpression(server: ServerModel): string {
|
|
20
|
+
const parts = serverUrlParts(server).map((part) =>
|
|
21
|
+
part.kind === 'literal' ? javaString(part.value) : memberName(part.name)
|
|
22
|
+
);
|
|
23
|
+
return parts.join(' + ');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** One static method per declared server; server variables become String arguments. */
|
|
27
|
+
export function writeServers(printer: JavaPrinter, model: ApiModel): void {
|
|
28
|
+
const servers = model.servers ?? [];
|
|
29
|
+
if (servers.length === 0) return;
|
|
30
|
+
const usedNames = new Set<string>();
|
|
31
|
+
printer.line("/** The declared servers; the description's defaults are in each method's doc. */");
|
|
32
|
+
printer.block(
|
|
33
|
+
'public static final class Servers {',
|
|
34
|
+
() => {
|
|
35
|
+
servers.forEach((server, index) => {
|
|
36
|
+
let name = identifierFor(server.description ?? `server${index + 1}`, {
|
|
37
|
+
style: 'camel',
|
|
38
|
+
reserved: JAVA,
|
|
39
|
+
});
|
|
40
|
+
if (usedNames.has(name)) name = `${name}${index + 1}`;
|
|
41
|
+
usedNames.add(name);
|
|
42
|
+
const params = server.variables.map((variable) => `String ${memberName(variable.name)}`);
|
|
43
|
+
// Java has no default arguments; the spec default lives in the doc comment.
|
|
44
|
+
const defaults = server.variables
|
|
45
|
+
.map(
|
|
46
|
+
(variable) => `${memberName(variable.name)} default: ${javaString(variable.default)}`
|
|
47
|
+
)
|
|
48
|
+
.join(', ');
|
|
49
|
+
if (index > 0) printer.blank();
|
|
50
|
+
printer.doc(
|
|
51
|
+
name,
|
|
52
|
+
`The ${javaString(server.description ?? server.url)} base URL${defaults === '' ? '.' : ` (${defaults}).`}`
|
|
53
|
+
);
|
|
54
|
+
printer.block(
|
|
55
|
+
`public static String ${name}(${params.join(', ')}) {`,
|
|
56
|
+
() => {
|
|
57
|
+
printer.line(`return ${serverUrlExpression(server)};`);
|
|
58
|
+
},
|
|
59
|
+
'}'
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
'}'
|
|
64
|
+
);
|
|
65
|
+
printer.blank();
|
|
66
|
+
}
|