@redocly/cli 2.63.0 → 2.64.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/THIRD_PARTY_NOTICES +1 -1
- package/lib/chunks/{PHWKGYUT.js → 2DKR4Z25.js} +1 -1
- package/lib/chunks/{JHK6XIMG.js → 2MCPXKB6.js} +1 -1
- package/lib/chunks/{3SFDVGEQ.js → 2ZIICV4T.js} +1 -1
- package/lib/chunks/{6AB3BDX4.js → 3CSDNX6S.js} +1 -1
- package/lib/chunks/{IODGA6FG.js → 4EAF6XUQ.js} +1 -1
- package/lib/chunks/{Y4UTXOI2.js → 5PR7FNUB.js} +1 -1
- package/lib/chunks/{7AWM5GPD.js → 654FMWX6.js} +1 -1
- package/lib/chunks/{4C44BO5N.js → 6FADWAOY.js} +1 -1
- package/lib/chunks/{X2V5QOZP.js → 6MP4DHWK.js} +1 -1
- package/lib/chunks/{A22GELRX.js → 7APJVQSB.js} +1 -1
- package/lib/chunks/{3LGZAJES.js → AC62H63B.js} +1 -1
- package/lib/chunks/{C2OCU4E3.js → ALBI5SPY.js} +1 -1
- package/lib/chunks/{XNNK5G6V.js → B5ZOH4BB.js} +1 -1
- package/lib/chunks/{ZP54RCIQ.js → BGGUKU7E.js} +1 -1
- package/lib/chunks/{L2EBKZQZ.js → BWXAXULF.js} +1 -1
- package/lib/chunks/{5IIJHGNO.js → CEASD5U3.js} +1 -1
- package/lib/chunks/{U52CY34I.js → CVPT656W.js} +1 -1
- package/lib/chunks/{NCBLLIQ3.js → DL4VP2Z4.js} +2 -2
- package/lib/chunks/DPNI74SB.js +69 -0
- package/lib/chunks/{RFGNVCAR.js → ENIPOAVJ.js} +2 -2
- package/lib/chunks/{ACMV5RZA.js → EQTXHL74.js} +101 -101
- package/lib/chunks/{HTG3RKCV.js → FU7GBMUU.js} +1 -1
- package/lib/chunks/{J7J4PH3V.js → FVGFKJ67.js} +1 -1
- package/lib/chunks/{NERCHMVY.js → FXKIC5R3.js} +1 -1
- package/lib/chunks/{B4ONRSDG.js → GKCVQWOQ.js} +3 -3
- package/lib/chunks/{Z52TEGV5.js → GKSUZULD.js} +1 -1
- package/lib/chunks/{AU7VOB4V.js → GOTKYHFM.js} +1 -1
- package/lib/chunks/{YXH72HCU.js → GRTUPOKN.js} +1 -1
- package/lib/chunks/{NR3R4HFM.js → HAOBCQWB.js} +313 -1
- package/lib/chunks/{JGBWIR5U.js → HIII45WJ.js} +1 -1
- package/lib/chunks/{ZK27F53P.js → HYMULX2S.js} +1 -1
- package/lib/chunks/{DEXQ6S3P.js → I6NMWBVI.js} +1 -1
- package/lib/chunks/{LLWU7A5G.js → IH3N62Q4.js} +1 -1
- package/lib/chunks/{WV2NAII3.js → J665DSDI.js} +1 -1
- package/lib/chunks/{BC3XCWQE.js → JQJ5TDVP.js} +1 -1
- package/lib/chunks/{BS3AUVYD.js → L5X7LBV6.js} +1 -1
- package/lib/chunks/{BFIZTFWS.js → LCAJ35J6.js} +1 -1
- package/lib/chunks/{CQMZF72H.js → LG3SUXEW.js} +1 -1
- package/lib/chunks/{KMP5ZE2D.js → LMO5V2XF.js} +1 -1
- package/lib/chunks/{J373CXCH.js → M4NCSK7Q.js} +1 -1
- package/lib/chunks/{DQFNUDOT.js → M74SGAZK.js} +1 -1
- package/lib/chunks/{HW7ZCN7J.js → MVCGBDOY.js} +1 -1
- package/lib/chunks/{24AVTWC7.js → N4R4236N.js} +1 -1
- package/lib/chunks/{Q4UGLPO2.js → NRWIPPEV.js} +1 -1
- package/lib/chunks/{CTPVBOG5.js → OGNRVBTI.js} +1 -1
- package/lib/chunks/{5VDBZVBF.js → ONBORCDJ.js} +1 -1
- package/lib/chunks/{OFJ2KV5N.js → OS52EARM.js} +1 -1
- package/lib/chunks/{YKST56C6.js → QCOPS234.js} +1 -1
- package/lib/chunks/{7LNKXEIU.js → QWTSCCNH.js} +1 -1
- package/lib/chunks/{FCZH3476.js → RRQJCLNO.js} +1 -1
- package/lib/chunks/{SXIFTBZB.js → RWDQI2KD.js} +1 -1
- package/lib/chunks/{I3M476SQ.js → S3W5GQGC.js} +1 -1
- package/lib/chunks/{AAPHKNGA.js → SRRHJLPL.js} +1 -1
- package/lib/chunks/{E2D25T4G.js → TTE4EAVV.js} +3 -2
- package/lib/chunks/{6LEQ46KS.js → TWFZE4OF.js} +1 -1
- package/lib/chunks/{Z7J6WWCO.js → U4RAHOFK.js} +1 -1
- package/lib/chunks/{QNCKZURN.js → UC5EDLXL.js} +1 -1
- package/lib/chunks/{2G2Q42ND.js → ULQK2S4O.js} +1 -1
- package/lib/chunks/{7RQW6KPZ.js → UNOXQ62I.js} +224 -115
- package/lib/chunks/{OYUXHAGQ.js → UQW6CW3M.js} +1 -1
- package/lib/chunks/{4JKMQCWY.js → VKTRI5YG.js} +1 -1
- package/lib/chunks/{6WESXERF.js → VMIHLA3H.js} +1 -1
- package/lib/chunks/{ITUUIAOZ.js → VWF52WKH.js} +1 -1
- package/lib/chunks/{VB4PNWOR.js → WKQJPOYW.js} +1 -1
- package/lib/chunks/{VSBSD3XZ.js → WQBSNQXL.js} +1 -1
- package/lib/chunks/{IYKYAJDC.js → X6TQQHRM.js} +1 -1
- package/lib/chunks/{TCALQAX5.js → XDBFHG7X.js} +1 -1
- package/lib/chunks/{LXSCIQFU.js → XYU2LTWU.js} +1 -1
- package/lib/chunks/{6QRNEF7K.js → Z4X6WES7.js} +1 -1
- package/lib/chunks/{CVUPOCX4.js → ZFXOCOU6.js} +1 -1
- package/lib/chunks/{Z5QYTPVY.js → ZM3M44Q3.js} +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/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 +29 -3
- 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/typescript-generator/SKILL.md +19 -0
- package/lib/index.js +5 -5
- package/package.json +1 -1
- package/lib/chunks/FRM6TZ42.js +0 -67
|
@@ -4,8 +4,8 @@ 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 x,ia as R}from"./
|
|
8
|
-
- `));return o}function b(e,n,o,r,a){let s=`Pagination for operation "${e.name}" (${r})`,c=q(o);if(c!==void 0)return{error:`${s}: ${c}`};let t=o,i=d=>a?{error:`${s}: ${d}`}:{};if(e.sse!==void 0)return i("the operation is a Server-Sent Events stream");if(t.style!=="link"&&t.style!=="body-link"){let d=t.style==="cursor"?"cursorParam":"offsetParam",l=t.style==="cursor"?t.cursorParam:t.offsetParam,k=e.queryParams.find(u=>u.name===l);if(!k){let u=e.queryParams.map(
|
|
7
|
+
import{c as x,ia as R}from"./EQTXHL74.js";import{m}from"./UW4UC7ZI.js";function C(e){return e.flatMap(n=>n.operations)}function P(e,n,o){let r=e.specName??e.name;if(o?.exclude?.includes(r))return{};let a=o?.operations?.[r];if(a!==void 0)return b(e,n,a,`pagination.operations["${r}"]`,!0);if(e.paginationExtension!==void 0)return b(e,n,e.paginationExtension,"x-redoclyPagination",!0);if(o?.style!==void 0){let{exclude:s,operations:c,...t}=o;return b(e,n,t,"pagination convention",!1)}return{}}function H(e,n){let o=new Map,r=[];for(let a of C(e.services)){let s=P(a,e,n);s.error!==void 0?r.push(s.error):s.spec!==void 0&&o.set(a.name,{spec:s.spec,itemSchema:s.itemSchema})}if(r.length>0)throw new Error(["Invalid pagination configuration:",...r].join(`
|
|
8
|
+
- `));return o}function b(e,n,o,r,a){let s=`Pagination for operation "${e.name}" (${r})`,c=q(o);if(c!==void 0)return{error:`${s}: ${c}`};let t=o,i=d=>a?{error:`${s}: ${d}`}:{};if(e.sse!==void 0)return i("the operation is a Server-Sent Events stream");if(t.style!=="link"&&t.style!=="body-link"){let d=t.style==="cursor"?"cursorParam":"offsetParam",l=t.style==="cursor"?t.cursorParam:t.offsetParam,k=e.queryParams.find(u=>u.name===l);if(!k){let u=e.queryParams.map(T=>T.name).join(", ");return i(`query parameter "${l}" is not declared on the operation`+(u===""?"":` (declared: ${u})`))}let p=O(k.schema,n);if(!(p!==void 0&&(t.style==="cursor"?y(p,n):p.kind==="scalar"&&(p.scalar==="number"||p.scalar==="integer")))){let u=t.style==="cursor"?"a string":"a number";return i(`the "${d}" query parameter "${l}" must accept ${u} (got ${I(p)})`)}}let g=e.successResponses.find(d=>d.contentType.toLowerCase().includes("json"));if(!g)return i("the operation has no JSON success response");if(t.style==="link"){let d=e.successResponseHeaders?.some(l=>l.name==="link")===!0;if(!d&&!a)return{};d||R.warn(`generate-client: ${s.toLowerCase()} follows the Link header, but the success response does not document one.
|
|
9
9
|
`)}let h=m(g.schema,t.items,n);if(h===void 0)return i(`the "items" pointer "${t.items}" does not resolve in the success response schema`);if(h.kind!=="array")return i(`the "items" pointer "${t.items}" must point at an array (got ${h.kind})`);if(t.style==="body-link"){let d=m(g.schema,t.nextLink,n);if(d===void 0)return i(`the "nextLink" pointer "${t.nextLink}" does not resolve in the success response schema`);if(!y(d,n))return i(`the "nextLink" pointer "${t.nextLink}" must point at a string (got ${d.kind})`)}if(t.style==="cursor"){let d=m(g.schema,t.nextCursor,n);if(d===void 0)return i(`the "nextCursor" pointer "${t.nextCursor}" does not resolve in the success response schema`);if(!y(d,n))return i(`the "nextCursor" pointer "${t.nextCursor}" must point at a string (got ${d.kind})`);if(t.hasMore!==void 0){let l=m(g.schema,t.hasMore,n);if(l===void 0)return i(`the "hasMore" pointer "${t.hasMore}" does not resolve in the success response schema`);if(l.kind!=="scalar"||l.scalar!=="boolean")return i(`the "hasMore" pointer "${t.hasMore}" must point at a boolean (got ${l.kind})`)}}let f=t.limitParam!==void 0?{limitParam:t.limitParam}:{};return{spec:t.style==="cursor"?{style:"cursor",param:t.cursorParam,...f,nextCursor:t.nextCursor,...t.hasMore!==void 0?{hasMore:t.hasMore}:{},items:t.items}:t.style==="link"?{style:"link",...f,items:t.items}:t.style==="body-link"?{style:"body-link",...f,nextLink:t.nextLink,items:t.items}:{style:t.style,param:t.offsetParam,...f,items:t.items},itemSchema:h.items}}function q(e){if(!x(e))return"the rule must be an object";let{style:n,cursorParam:o,nextCursor:r,hasMore:a,offsetParam:s,nextLink:c,limitParam:t,items:i}=e;if(n!=="cursor"&&n!=="offset"&&n!=="page"&&n!=="link"&&n!=="body-link")return`"style" must be one of "cursor" | "offset" | "page" | "link" | "body-link" (got ${JSON.stringify(n)})`;if(typeof i!="string"||i!==""&&!i.startsWith("/"))return'"items" must be a JSON pointer starting with "/" (or "" when the response body is the item array itself)';if(n==="cursor"){if(typeof o!="string"||o==="")return'cursor style requires a "cursorParam" query parameter name';if(typeof r!="string"||!r.startsWith("/"))return'cursor style requires a "nextCursor" JSON pointer starting with "/"';if(a!==void 0&&(typeof a!="string"||!a.startsWith("/")))return'"hasMore" must be a JSON pointer starting with "/"'}else if(n==="offset"||n==="page"){if(typeof s!="string"||s==="")return`${n} style requires an "offsetParam" query parameter name`}else if(n==="body-link"&&(typeof c!="string"||!c.startsWith("/")))return'body-link style requires a "nextLink" JSON pointer starting with "/"';if(t!==void 0&&typeof t!="string")return'"limitParam" must be a query parameter name'}function I(e){return e===void 0?"an unresolvable ref":e.kind==="scalar"||e.kind==="enum"?e.scalar:e.kind}function O(e,n){let o=new Set,r=e;for(;r.kind==="ref";){let{name:a}=r;if(o.has(a))return;o.add(a);let s=n.schemas.find(c=>c.name===a);if(s===void 0)return;r=s.schema}return r}function y(e,n){return e.kind==="scalar"||e.kind==="enum"?e.scalar==="string":e.kind==="literal"?typeof e.value=="string":e.kind==="union"?e.members.every(o=>{let r=O(o,n);return r!==void 0&&(r.kind==="null"||r.kind!=="union"&&y(r,n))}):!1}var G={"types.ts":`/**
|
|
10
10
|
* The public type surface of the client runtime \u2014 \`@redocly/client-generator\`'s
|
|
11
11
|
* app-facing runtime module. Pure types, no runtime code (excluded from coverage).
|
|
@@ -184,7 +184,14 @@ export type ApiErrorLike = globalThis.Error & {
|
|
|
184
184
|
body: unknown;
|
|
185
185
|
};
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
export type SettledCall = {
|
|
188
|
+
response?: Response;
|
|
189
|
+
error?: unknown;
|
|
190
|
+
attempts: number;
|
|
191
|
+
durationMs: number;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/** One interceptor: any subset of the four hooks. */
|
|
188
195
|
export type Middleware<Op extends OperationContext = OperationContext> = {
|
|
189
196
|
onRequest?: (ctx: RequestContext<Op>) => void | Promise<void>;
|
|
190
197
|
onResponse?: (
|
|
@@ -197,6 +204,7 @@ export type Middleware<Op extends OperationContext = OperationContext> = {
|
|
|
197
204
|
error: ApiErrorLike,
|
|
198
205
|
ctx: RequestContext<Op>
|
|
199
206
|
) => globalThis.Error | Promise<globalThis.Error>;
|
|
207
|
+
onSettled?: (ctx: RequestContext<Op>, call: SettledCall) => void | Promise<void>;
|
|
200
208
|
};
|
|
201
209
|
|
|
202
210
|
/** Client configuration: transport, defaults, retry policy, middleware, and credentials. */
|
|
@@ -783,6 +791,7 @@ import type {
|
|
|
783
791
|
RequestContext,
|
|
784
792
|
RequestOptions,
|
|
785
793
|
RetryConfig,
|
|
794
|
+
SettledCall,
|
|
786
795
|
} from './types.js';
|
|
787
796
|
|
|
788
797
|
/**
|
|
@@ -865,7 +874,8 @@ function anySignal(signals: AbortSignal[]): AbortSignal {
|
|
|
865
874
|
* serialization (JSON, or FormData via the multipart capability; a stream passes
|
|
866
875
|
* through in one attempt), the retry loop
|
|
867
876
|
* (idempotent-only defaults, \`Retry-After\`, abandoned-body drain), and the reverse
|
|
868
|
-
* \`onResponse\` onion
|
|
877
|
+
* \`onResponse\` onion, then the \`onSettled\` chain once with the final outcome. Returns the
|
|
878
|
+
* final response plus the request context.
|
|
869
879
|
*/
|
|
870
880
|
export async function send(
|
|
871
881
|
config: ClientConfig,
|
|
@@ -973,72 +983,117 @@ export async function send(
|
|
|
973
983
|
const retryOn = retry.retryOn ?? defaultRetryOn;
|
|
974
984
|
const signal = fetchInit.signal ?? undefined;
|
|
975
985
|
|
|
986
|
+
const startedAt = Date.now();
|
|
976
987
|
let attempt = 0;
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
988
|
+
let finalResponse: Response;
|
|
989
|
+
let lastResponse: Response | undefined;
|
|
990
|
+
try {
|
|
991
|
+
while (true) {
|
|
992
|
+
if (signal?.aborted) throw abortError(signal);
|
|
993
|
+
attempt++;
|
|
994
|
+
// A fresh timeout budget per attempt; the caller's signal still wins the race.
|
|
995
|
+
// The composed signal also governs reading the response body.
|
|
996
|
+
const budget = timeout ? timeoutSignal(timeout) : undefined;
|
|
997
|
+
const attemptSignal = budget && signal ? anySignal([signal, budget]) : (budget ?? signal);
|
|
998
|
+
let response: Response;
|
|
999
|
+
try {
|
|
1000
|
+
response = await doFetch(context.url, {
|
|
1001
|
+
...fetchInit,
|
|
1002
|
+
// \`fetch\` requires it for a stream body.
|
|
1003
|
+
...(isStream ? { duplex: 'half' } : {}),
|
|
1004
|
+
signal: attemptSignal,
|
|
1005
|
+
method: context.method,
|
|
1006
|
+
headers: context.headers,
|
|
1007
|
+
body: payload,
|
|
1008
|
+
});
|
|
1009
|
+
} catch (error) {
|
|
1010
|
+
// Decided before any await, when no timer can have fired since \`fetch\` rejected: an
|
|
1011
|
+
// aborted budget means this attempt timed out. The abort reason's name is no
|
|
1012
|
+
// evidence, because Chrome 103 to 123 abort a timeout with \`AbortError\`.
|
|
1013
|
+
const timedOut = timeout !== undefined && budget?.aborted && !signal?.aborted;
|
|
1014
|
+
if (
|
|
1015
|
+
attempt < maxAttempts &&
|
|
1016
|
+
!signal?.aborted &&
|
|
1017
|
+
(await retryOn({ attempt, request: context, error }))
|
|
1018
|
+
) {
|
|
1019
|
+
await sleep(retryDelay(retry, attempt, null), signal);
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
// Our timeout fired (never the caller's own abort \u2014 that rethrows untouched):
|
|
1023
|
+
// wrap the bare DOMException with the context a log line needs.
|
|
1024
|
+
if (timedOut) throw new TimeoutError(op.id, timeout, attempt);
|
|
1025
|
+
throw error;
|
|
1026
|
+
}
|
|
1027
|
+
lastResponse = response;
|
|
1028
|
+
// Reverse order: the last-registered middleware wraps closest to the network (onion).
|
|
1029
|
+
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
1030
|
+
const onResponse = middleware[i].onResponse;
|
|
1031
|
+
if (onResponse) {
|
|
1032
|
+
const replaced = await onResponse(response, context);
|
|
1033
|
+
if (replaced && replaced !== response) {
|
|
1034
|
+
// Cancel the abandoned original's body \u2014 like the retry path, an unread body
|
|
1035
|
+
// keeps its connection checked out under Node/undici.
|
|
1036
|
+
await response.body?.cancel().catch(() => undefined);
|
|
1037
|
+
response = replaced;
|
|
1038
|
+
lastResponse = replaced;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1000
1042
|
if (
|
|
1043
|
+
!response.ok &&
|
|
1001
1044
|
attempt < maxAttempts &&
|
|
1002
1045
|
!signal?.aborted &&
|
|
1003
|
-
(await retryOn({ attempt, request: context,
|
|
1046
|
+
(await retryOn({ attempt, request: context, response }))
|
|
1004
1047
|
) {
|
|
1005
|
-
|
|
1048
|
+
const retryAfter = response.headers.get('retry-after');
|
|
1049
|
+
// Drain the abandoned response body before the next attempt: an unread body
|
|
1050
|
+
// keeps the connection checked out (and can stall the pool) under Node/undici
|
|
1051
|
+
// and other strict HTTP clients. Ignore errors (e.g. a middleware already read it).
|
|
1052
|
+
await response.body?.cancel().catch(() => undefined);
|
|
1053
|
+
lastResponse = undefined;
|
|
1054
|
+
await sleep(retryDelay(retry, attempt, retryAfter), signal);
|
|
1006
1055
|
continue;
|
|
1007
1056
|
}
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
if (timedOut) throw new TimeoutError(op.id, timeout, attempt);
|
|
1011
|
-
throw error;
|
|
1057
|
+
finalResponse = response;
|
|
1058
|
+
break;
|
|
1012
1059
|
}
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
const settled: SettledCall = {
|
|
1062
|
+
response: lastResponse,
|
|
1063
|
+
error,
|
|
1064
|
+
attempts: attempt,
|
|
1065
|
+
durationMs: Date.now() - startedAt,
|
|
1066
|
+
};
|
|
1067
|
+
for (const mw of middleware) {
|
|
1068
|
+
if (!mw.onSettled) continue;
|
|
1069
|
+
try {
|
|
1070
|
+
await mw.onSettled(context, settled);
|
|
1071
|
+
} catch (hookError) {
|
|
1072
|
+
globalThis.console?.warn('onSettled hook failed', hookError);
|
|
1024
1073
|
}
|
|
1025
1074
|
}
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
)
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
await
|
|
1038
|
-
|
|
1075
|
+
throw error;
|
|
1076
|
+
}
|
|
1077
|
+
const settled: SettledCall = {
|
|
1078
|
+
response: finalResponse,
|
|
1079
|
+
attempts: attempt,
|
|
1080
|
+
durationMs: Date.now() - startedAt,
|
|
1081
|
+
};
|
|
1082
|
+
const hookErrors: unknown[] = [];
|
|
1083
|
+
for (const mw of middleware) {
|
|
1084
|
+
if (!mw.onSettled) continue;
|
|
1085
|
+
try {
|
|
1086
|
+
await mw.onSettled(context, settled);
|
|
1087
|
+
} catch (hookError) {
|
|
1088
|
+
hookErrors.push(hookError);
|
|
1039
1089
|
}
|
|
1040
|
-
return { response, context };
|
|
1041
1090
|
}
|
|
1091
|
+
if (hookErrors.length > 0) {
|
|
1092
|
+
// The caller never gets this response, so release its connection.
|
|
1093
|
+
await finalResponse.body?.cancel().catch(() => undefined);
|
|
1094
|
+
throw hookErrors[0];
|
|
1095
|
+
}
|
|
1096
|
+
return { response: finalResponse, context };
|
|
1042
1097
|
}
|
|
1043
1098
|
`,"sse.ts":`import { ApiError } from './errors.js';
|
|
1044
1099
|
import { readError } from './parse.js';
|
|
@@ -2985,7 +3040,14 @@ export type ApiErrorLike = globalThis.Error & {
|
|
|
2985
3040
|
body: unknown;
|
|
2986
3041
|
};
|
|
2987
3042
|
|
|
2988
|
-
|
|
3043
|
+
export type SettledCall = {
|
|
3044
|
+
response?: Response;
|
|
3045
|
+
error?: unknown;
|
|
3046
|
+
attempts: number;
|
|
3047
|
+
durationMs: number;
|
|
3048
|
+
};
|
|
3049
|
+
|
|
3050
|
+
/** One interceptor: any subset of the four hooks. */
|
|
2989
3051
|
export type Middleware<Op extends OperationContext = OperationContext> = {
|
|
2990
3052
|
onRequest?: (ctx: RequestContext<Op>) => void | Promise<void>;
|
|
2991
3053
|
onResponse?: (
|
|
@@ -2998,6 +3060,7 @@ export type Middleware<Op extends OperationContext = OperationContext> = {
|
|
|
2998
3060
|
error: ApiErrorLike,
|
|
2999
3061
|
ctx: RequestContext<Op>
|
|
3000
3062
|
) => globalThis.Error | Promise<globalThis.Error>;
|
|
3063
|
+
onSettled?: (ctx: RequestContext<Op>, call: SettledCall) => void | Promise<void>;
|
|
3001
3064
|
};
|
|
3002
3065
|
|
|
3003
3066
|
/** Client configuration: transport, defaults, retry policy, middleware, and credentials. */
|
|
@@ -3636,7 +3699,8 @@ function anySignal(signals: AbortSignal[]): AbortSignal {
|
|
|
3636
3699
|
* serialization (JSON, or FormData via the multipart capability; a stream passes
|
|
3637
3700
|
* through in one attempt), the retry loop
|
|
3638
3701
|
* (idempotent-only defaults, \`Retry-After\`, abandoned-body drain), and the reverse
|
|
3639
|
-
* \`onResponse\` onion
|
|
3702
|
+
* \`onResponse\` onion, then the \`onSettled\` chain once with the final outcome. Returns the
|
|
3703
|
+
* final response plus the request context.
|
|
3640
3704
|
*/
|
|
3641
3705
|
async function send(
|
|
3642
3706
|
config: ClientConfig,
|
|
@@ -3744,72 +3808,117 @@ async function send(
|
|
|
3744
3808
|
const retryOn = retry.retryOn ?? defaultRetryOn;
|
|
3745
3809
|
const signal = fetchInit.signal ?? undefined;
|
|
3746
3810
|
|
|
3811
|
+
const startedAt = Date.now();
|
|
3747
3812
|
let attempt = 0;
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3813
|
+
let finalResponse: Response;
|
|
3814
|
+
let lastResponse: Response | undefined;
|
|
3815
|
+
try {
|
|
3816
|
+
while (true) {
|
|
3817
|
+
if (signal?.aborted) throw abortError(signal);
|
|
3818
|
+
attempt++;
|
|
3819
|
+
// A fresh timeout budget per attempt; the caller's signal still wins the race.
|
|
3820
|
+
// The composed signal also governs reading the response body.
|
|
3821
|
+
const budget = timeout ? timeoutSignal(timeout) : undefined;
|
|
3822
|
+
const attemptSignal = budget && signal ? anySignal([signal, budget]) : (budget ?? signal);
|
|
3823
|
+
let response: Response;
|
|
3824
|
+
try {
|
|
3825
|
+
response = await doFetch(context.url, {
|
|
3826
|
+
...fetchInit,
|
|
3827
|
+
// \`fetch\` requires it for a stream body.
|
|
3828
|
+
...(isStream ? { duplex: 'half' } : {}),
|
|
3829
|
+
signal: attemptSignal,
|
|
3830
|
+
method: context.method,
|
|
3831
|
+
headers: context.headers,
|
|
3832
|
+
body: payload,
|
|
3833
|
+
});
|
|
3834
|
+
} catch (error) {
|
|
3835
|
+
// Decided before any await, when no timer can have fired since \`fetch\` rejected: an
|
|
3836
|
+
// aborted budget means this attempt timed out. The abort reason's name is no
|
|
3837
|
+
// evidence, because Chrome 103 to 123 abort a timeout with \`AbortError\`.
|
|
3838
|
+
const timedOut = timeout !== undefined && budget?.aborted && !signal?.aborted;
|
|
3839
|
+
if (
|
|
3840
|
+
attempt < maxAttempts &&
|
|
3841
|
+
!signal?.aborted &&
|
|
3842
|
+
(await retryOn({ attempt, request: context, error }))
|
|
3843
|
+
) {
|
|
3844
|
+
await sleep(retryDelay(retry, attempt, null), signal);
|
|
3845
|
+
continue;
|
|
3846
|
+
}
|
|
3847
|
+
// Our timeout fired (never the caller's own abort \u2014 that rethrows untouched):
|
|
3848
|
+
// wrap the bare DOMException with the context a log line needs.
|
|
3849
|
+
if (timedOut) throw new TimeoutError(op.id, timeout, attempt);
|
|
3850
|
+
throw error;
|
|
3851
|
+
}
|
|
3852
|
+
lastResponse = response;
|
|
3853
|
+
// Reverse order: the last-registered middleware wraps closest to the network (onion).
|
|
3854
|
+
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
3855
|
+
const onResponse = middleware[i].onResponse;
|
|
3856
|
+
if (onResponse) {
|
|
3857
|
+
const replaced = await onResponse(response, context);
|
|
3858
|
+
if (replaced && replaced !== response) {
|
|
3859
|
+
// Cancel the abandoned original's body \u2014 like the retry path, an unread body
|
|
3860
|
+
// keeps its connection checked out under Node/undici.
|
|
3861
|
+
await response.body?.cancel().catch(() => undefined);
|
|
3862
|
+
response = replaced;
|
|
3863
|
+
lastResponse = replaced;
|
|
3864
|
+
}
|
|
3865
|
+
}
|
|
3866
|
+
}
|
|
3771
3867
|
if (
|
|
3868
|
+
!response.ok &&
|
|
3772
3869
|
attempt < maxAttempts &&
|
|
3773
3870
|
!signal?.aborted &&
|
|
3774
|
-
(await retryOn({ attempt, request: context,
|
|
3871
|
+
(await retryOn({ attempt, request: context, response }))
|
|
3775
3872
|
) {
|
|
3776
|
-
|
|
3873
|
+
const retryAfter = response.headers.get('retry-after');
|
|
3874
|
+
// Drain the abandoned response body before the next attempt: an unread body
|
|
3875
|
+
// keeps the connection checked out (and can stall the pool) under Node/undici
|
|
3876
|
+
// and other strict HTTP clients. Ignore errors (e.g. a middleware already read it).
|
|
3877
|
+
await response.body?.cancel().catch(() => undefined);
|
|
3878
|
+
lastResponse = undefined;
|
|
3879
|
+
await sleep(retryDelay(retry, attempt, retryAfter), signal);
|
|
3777
3880
|
continue;
|
|
3778
3881
|
}
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
if (timedOut) throw new TimeoutError(op.id, timeout, attempt);
|
|
3782
|
-
throw error;
|
|
3882
|
+
finalResponse = response;
|
|
3883
|
+
break;
|
|
3783
3884
|
}
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3885
|
+
} catch (error) {
|
|
3886
|
+
const settled: SettledCall = {
|
|
3887
|
+
response: lastResponse,
|
|
3888
|
+
error,
|
|
3889
|
+
attempts: attempt,
|
|
3890
|
+
durationMs: Date.now() - startedAt,
|
|
3891
|
+
};
|
|
3892
|
+
for (const mw of middleware) {
|
|
3893
|
+
if (!mw.onSettled) continue;
|
|
3894
|
+
try {
|
|
3895
|
+
await mw.onSettled(context, settled);
|
|
3896
|
+
} catch (hookError) {
|
|
3897
|
+
globalThis.console?.warn('onSettled hook failed', hookError);
|
|
3795
3898
|
}
|
|
3796
3899
|
}
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
)
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
3808
|
-
await
|
|
3809
|
-
|
|
3900
|
+
throw error;
|
|
3901
|
+
}
|
|
3902
|
+
const settled: SettledCall = {
|
|
3903
|
+
response: finalResponse,
|
|
3904
|
+
attempts: attempt,
|
|
3905
|
+
durationMs: Date.now() - startedAt,
|
|
3906
|
+
};
|
|
3907
|
+
const hookErrors: unknown[] = [];
|
|
3908
|
+
for (const mw of middleware) {
|
|
3909
|
+
if (!mw.onSettled) continue;
|
|
3910
|
+
try {
|
|
3911
|
+
await mw.onSettled(context, settled);
|
|
3912
|
+
} catch (hookError) {
|
|
3913
|
+
hookErrors.push(hookError);
|
|
3810
3914
|
}
|
|
3811
|
-
return { response, context };
|
|
3812
3915
|
}
|
|
3916
|
+
if (hookErrors.length > 0) {
|
|
3917
|
+
// The caller never gets this response, so release its connection.
|
|
3918
|
+
await finalResponse.body?.cancel().catch(() => undefined);
|
|
3919
|
+
throw hookErrors[0];
|
|
3920
|
+
}
|
|
3921
|
+
return { response: finalResponse, context };
|
|
3813
3922
|
}`,"sse.ts":`/**
|
|
3814
3923
|
* A frame delimiter: two consecutive line terminators (each CR, LF, or CRLF, per the SSE
|
|
3815
3924
|
* spec \u2014 so mixed endings like \`\\n\\r\\n\` are valid boundaries, not just matching pairs).
|
|
@@ -5541,4 +5650,4 @@ async function runSingle(
|
|
|
5541
5650
|
}
|
|
5542
5651
|
return fail(1, detail);
|
|
5543
5652
|
}
|
|
5544
|
-
}`},S=["ApiError","ApiErrorLike","AuthCredentials","BodyMethod","Capabilities","CliAuthScheme","CliCommand","CliFlag","CliGlobals","CliInvocation","CliWiring","Client","ClientConfig","ClientCore","CommandContext","CommandSource","CustomCommand","Envelope","EnvelopeResult","EnvelopeResultForKnownInit","FRAME_DELIMITER","GLOBAL_FLAGS","HeadersOf","IDEMPOTENT_METHODS","LAYERS","LAYER_OF","LinkPageCall","Middleware","NoRequiredKeys","OperationArgs","OperationContext","OperationDescriptor","OperationMethodIdentity","OpsShape","PageOf","Paginated","PaginationSpec","ParamSpec","ParseAs","QueryStyle","QueryValue","RequestContext","RequestOptions","ResolvedCommand","ResponseHeaderSpec","Result","RetryConfig","RetryContext","RetryStrategy","SecuritySpec","SendCapabilities","ServerSentEvent","SseOptions","SseParseError","TRANSIENT_STATUS","ThrowMethod","TimeoutError","TokenProvider","abortError","acceptFor","anySignal","buildUrl","callInputs","coerceResponseHeader","commandContract","constantCase","createClientCore","defaultRetryOn","encodeBase64","encodeReserved","execute","groupSlug","inputOf","invokedName","isConfigured","items","itemsByLink","kindFor","linkNext","linkPageCall","loadBody","mergeSetup","middlewareChain","namespaceArgs","normalizeCommands","oneLine","pageCall","pages","pagesByLink","paginateCapability","parse","parseInvocation","parseSseFrame","prepareRequest","queryStyles","readEnvelopeHeaders","readError","redactHeaders","renderComposedHelp","renderHelp","resolveAuth","resolvePointer","resolveToken","retryDelay","runCli","runSingle","runSources","send","shadowedCommandName","sleep","splitArgs","sse","stringHeaders","substitutePath","timeoutSignal","toFormData","toHeaderRecord"];var j=["client","OPERATIONS","Ops","OperationId","OperationPath","OperationTag","createClient","mergeSetup","ApiError","TimeoutError","configure","use","auth","defaultRetryOn","ClientConfig","RequestOptions","SseOptions","Middleware","OperationDescriptor","ServerSentEvent","Result","Envelope","EnvelopeResult","TokenProvider","__redoclySetup"],$=["z","http","HttpResponse","handlers","faker","queryOptions","useSWR","useSWRMutation","__Writable"],L=["AbortController","AbortSignal","Array","ArrayBuffer","ArrayBufferView","AsyncGenerator","AsyncIterable","Blob","BodyInit","Boolean","DOMException","Date","Error","Extract","FormData","Headers","HeadersInit","JSON","Map","Math","NonNullable","Number","Object","Omit","Partial","Promise","ReadableStream","Record","RegExp","RegExpExecArray","Request","RequestInit","Response","Set","String","Symbol","TextDecoder","TextEncoder","TypeError","Uint8Array","URL","URLSearchParams","btoa","clearTimeout","crypto","decodeURIComponent","document","encodeURIComponent","fetch","globalThis","setTimeout","undefined"],w;function Q(){return w===void 0&&(w=new Set([...j,...$,...L,...S])),w}var A={name:"@redocly/client-generator",version:"0.
|
|
5653
|
+
}`},S=["ApiError","ApiErrorLike","AuthCredentials","BodyMethod","Capabilities","CliAuthScheme","CliCommand","CliFlag","CliGlobals","CliInvocation","CliWiring","Client","ClientConfig","ClientCore","CommandContext","CommandSource","CustomCommand","Envelope","EnvelopeResult","EnvelopeResultForKnownInit","FRAME_DELIMITER","GLOBAL_FLAGS","HeadersOf","IDEMPOTENT_METHODS","LAYERS","LAYER_OF","LinkPageCall","Middleware","NoRequiredKeys","OperationArgs","OperationContext","OperationDescriptor","OperationMethodIdentity","OpsShape","PageOf","Paginated","PaginationSpec","ParamSpec","ParseAs","QueryStyle","QueryValue","RequestContext","RequestOptions","ResolvedCommand","ResponseHeaderSpec","Result","RetryConfig","RetryContext","RetryStrategy","SecuritySpec","SendCapabilities","ServerSentEvent","SettledCall","SseOptions","SseParseError","TRANSIENT_STATUS","ThrowMethod","TimeoutError","TokenProvider","abortError","acceptFor","anySignal","buildUrl","callInputs","coerceResponseHeader","commandContract","constantCase","createClientCore","defaultRetryOn","encodeBase64","encodeReserved","execute","groupSlug","inputOf","invokedName","isConfigured","items","itemsByLink","kindFor","linkNext","linkPageCall","loadBody","mergeSetup","middlewareChain","namespaceArgs","normalizeCommands","oneLine","pageCall","pages","pagesByLink","paginateCapability","parse","parseInvocation","parseSseFrame","prepareRequest","queryStyles","readEnvelopeHeaders","readError","redactHeaders","renderComposedHelp","renderHelp","resolveAuth","resolvePointer","resolveToken","retryDelay","runCli","runSingle","runSources","send","shadowedCommandName","sleep","splitArgs","sse","stringHeaders","substitutePath","timeoutSignal","toFormData","toHeaderRecord"];var j=["client","OPERATIONS","Ops","OperationId","OperationPath","OperationTag","createClient","mergeSetup","ApiError","TimeoutError","configure","use","auth","defaultRetryOn","ClientConfig","RequestOptions","SseOptions","Middleware","OperationDescriptor","ServerSentEvent","Result","Envelope","EnvelopeResult","TokenProvider","__redoclySetup"],$=["z","http","HttpResponse","handlers","faker","queryOptions","useSWR","useSWRMutation","__Writable"],L=["AbortController","AbortSignal","Array","ArrayBuffer","ArrayBufferView","AsyncGenerator","AsyncIterable","Blob","BodyInit","Boolean","DOMException","Date","Error","Extract","FormData","Headers","HeadersInit","JSON","Map","Math","NonNullable","Number","Object","Omit","Partial","Promise","ReadableStream","Record","RegExp","RegExpExecArray","Request","RequestInit","Response","Set","String","Symbol","TextDecoder","TextEncoder","TypeError","Uint8Array","URL","URLSearchParams","btoa","clearTimeout","crypto","decodeURIComponent","document","encodeURIComponent","fetch","globalThis","setTimeout","undefined"],w;function Q(){return w===void 0&&(w=new Set([...j,...$,...L,...S])),w}var A={name:"@redocly/client-generator",version:"0.7.0",description:"Generate typed, zero-dependency TypeScript clients (fetch, auth, retries, middleware, SSE) from OpenAPI descriptions.",type:"module",types:"lib/index.d.ts",sideEffects:!1,exports:{".":{types:"./lib/index.d.ts",import:"./lib/index.js",default:"./lib/index.js"},"./generate":{types:"./lib/generate.d.ts",import:"./lib/generate.js",default:"./lib/generate.js"},"./printers/python":{types:"./lib/printers/python.d.ts",import:"./lib/printers/python.js",default:"./lib/printers/python.js"},"./printers/go":{types:"./lib/printers/go.d.ts",import:"./lib/printers/go.js",default:"./lib/printers/go.js"},"./printers/php":{types:"./lib/printers/php.d.ts",import:"./lib/printers/php.js",default:"./lib/printers/php.js"},"./printers/typescript":{types:"./lib/printers/typescript.d.ts",import:"./lib/printers/typescript.js",default:"./lib/printers/typescript.js"},"./printers":{types:"./lib/printers/index.d.ts",import:"./lib/printers/index.js",default:"./lib/printers/index.js"},"./contracts/typescript":{types:"./lib/contracts/typescript.d.ts",import:"./lib/contracts/typescript.js",default:"./lib/contracts/typescript.js"},"./runtime-sources":{types:"./lib/runtime-sources.d.ts",import:"./lib/runtime-sources.js",default:"./lib/runtime-sources.js"},"./package.json":"./package.json"},engines:{node:">=22.12.0 || >=20.19.0 <21.0.0",npm:">=10"},engineStrict:!0,scripts:{"examples:regen":"node scripts/regenerate-examples.mjs",prepare:"node scripts/generate-runtime-sources.mjs && node scripts/generate-eject-assets.mjs","typecheck:examples":"node scripts/typecheck-examples.mjs"},license:"MIT",repository:{type:"git",url:"git+https://github.com/Redocly/redocly-cli.git"},homepage:"https://github.com/Redocly/redocly-cli",keywords:["OpenAPI","Swagger","TypeScript","client","generator","codegen","fetch"],contributors:["Roman Marshevskyi <roman.marshevskyy@redocly.com> (https://redocly.com/)"],dependencies:{"@redocly/openapi-core":"2.64.0"},peerDependencies:{typescript:">=5.5.0"},peerDependenciesMeta:{typescript:{optional:!0}},devDependencies:{typescript:"6.0.2"},files:["lib","eject-assets"]};var ee=A.version;function E(e){let n=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());return n===null?void 0:[Number(n[1]),Number(n[2]),Number(n[3])]}function v(e,n){return e[0]-n[0]||e[1]-n[1]||e[2]-n[2]}function ne(e,n){let o=/^[\^~]|^>=/.exec(n.trim())?.[0]??"",r=E(n.trim().slice(o.length)),a=E(e);if(!(r===void 0||a===void 0))return v(a,r)<0?!1:o===">="?!0:o===""?v(a,r)===0:o==="~"?a[0]===r[0]&&a[1]===r[1]:r[0]!==0?a[0]===r[0]:r[1]!==0?a[0]===0&&a[1]===r[1]:v(a,r)===0}export{C as a,H as b,G as c,W as d,j as e,Q as f,ee as g,ne 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{a}from"./
|
|
7
|
+
import{a}from"./CEASD5U3.js";import{ia as p}from"./EQTXHL74.js";function g(t,r){let n=t.services.flatMap(e=>e.operations),s=n.filter(e=>e.sse!==void 0);s.length>0&&p.warn(`generate-client: ${r} skipped ${s.length} server-sent-events operation(s) \u2014 iterate the sdk's exported async generators directly: ${s.map(e=>e.name).join(", ")}.
|
|
8
8
|
`);let i=new Set(t.schemas.map(e=>e.name)),o=n.filter(e=>e.sse===void 0&&m(e,i));return o.length>0&&p.warn(`generate-client: ${r} skipped ${o.length} operation(s) whose variables type name collides with a schema \u2014 rename the schema or the operation: ${o.map(e=>e.name).join(", ")}.
|
|
9
9
|
`),n.filter(e=>e.sse===void 0&&!m(e,i))}function m(t,r){let n=a(t);return n.hasInputs&&r.has(n.variablesTypeName)}function x(t){return t.method==="get"||t.method==="head"}function u(t){return a(t).hasInputs}function f(t){return a(t).variablesTypeName}function $(t,r,n){let s=[];return a(t).hasInputs?s.push(r):n&&s.push("{}"),n&&s.push("{ ...init, envelope: undefined }"),`${t.name}(${s.join(", ")})`}function v(t,r,n){let s=t.map(e=>e.name).sort(),i=t.filter(u).map(f).sort();return n&&i.push("RequestOptions"),`import { ${[...s,...i.map(e=>`type ${e}`)].join(", ")} } from ${JSON.stringify(r)};`}export{g as a,x as b,u as c,f as d,$ as e,v as f};
|
|
@@ -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 K}from"./GKXY6U4S.js";import{Aa as V,j as z,l as I,o as H,oa as m,p as q,ta as Y}from"./ACMV5RZA.js";import{e as b}from"./RFWIIJFG.js";var Q=b(K(),1);var T=b(K(),1);function G(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function X(n){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(n).hostname.toLowerCase()}catch{return!1}return e.some(s=>!!(s==="*"||r===s||s.startsWith(".")&&r.endsWith(s)||!s.startsWith(".")&&r.endsWith("."+s)))}var Z=async(n,{timeout:t,...e}={})=>{let r=G(),s=r&&!X(n),o;s?o=new T.ProxyAgent({uri:r}):t&&(o=new T.Agent({connect:{timeout:t}}));try{return await(0,T.fetch)(n,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:o})}catch(i){throw await o?.destroy(),i}};var de=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function J(){let n=process.env.REDOCLY_ENVIRONMENT?.trim();return n&&de.test(n)?n:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},x=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=J(),s={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let o=await Z(t,{...e,headers:s});return this.collectSunsetWarning(o),o}catch(o){let i=o.cause??o,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)}},U=class{client;domain;apiKey;constructor(t,e,r){this.client=t,this.domain=e,this.apiKey=r}async getParsedResponse(t){let e=await t.json();if(t.ok)return e;throw new u(`${e.title||t.statusText||"Unknown error"}.`,t.status)}},N=class extends U{async find(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return r.status===404?void 0:await this.getParsedResponse(r)}catch(r){let s=`Failed to fetch project. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}},j=class extends U{async getDefaultBranch(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/source`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return(await this.getParsedResponse(r)).branchName}catch(r){let 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",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(s)}catch(s){let o=`Failed to upsert remote. ${s.message}`;throw s instanceof u?new u(o,s.status):new Error(o)}}async push(t,e,r,s){let o=new Q.FormData;o.append("remoteId",r.remoteId),o.append("commit[message]",r.commit.message),o.append("commit[author][name]",r.commit.author.name),o.append("commit[author][email]",r.commit.author.email),o.append("commit[branchName]",r.commit.branchName),r.commit.url&&o.append("commit[url]",r.commit.url),r.commit.namespace&&o.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&o.append("commit[sha]",r.commit.sha),r.commit.repository&&o.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&o.append("commit[createdAt]",r.commit.createdAt);for(let i of s){let a=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await he(i.stream)]);o.append(`files[${i.path}]`,a,i.path)}r.isMainBranch&&o.append("isMainBranch","true"),r.replace&&o.append("replace","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});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",Authorization:`Bearer ${this.apiKey}`}});return await this.getParsedResponse(s)}catch(s){let o=`Failed to get push status. ${s.message}`;throw s instanceof u?new u(o,s.status):new Error(o)}}},g=class{apiClient;projects;remotes;constructor({domain:t,apiKey:e,command:r,version:s}){this.apiClient=new x(r,s),this.projects=new N(this.apiClient,t,e),this.remotes=new j(this.apiClient,t,e)}getSunsetWarning(){return ee(this.apiClient.sunsetWarnings)}};function ee(n){let[t]=[...n].sort((e,r)=>e.isSunsetExpired!==r.isSunsetExpired?e.isSunsetExpired?-1:1:e.sunsetDate>r.sunsetDate?1:-1);return t}async function he(n){let t=[];for await(let e of n)t.push(e);return Buffer.concat(t)}function fe(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var pe=/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/,R={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function me(){return process.env.REDOCLY_DOMAIN||R.us}var te=ge((n,t)=>{try{let e=t||n?.resolvedConfig.residency;return we(e)?R[e]:e?new URL(e).origin:n?.resolvedConfig.scorecard?.fromProjectUrl?new URL(n.resolvedConfig.scorecard.fromProjectUrl).origin:R.us}catch{throw new E}});function D(n){try{te(void 0,n)}catch{return!1}return!0}function ge(n){return(...t)=>{let e=n(...t);if(!e.startsWith("https://")&&!pe.test(e))throw new E;return e}}var E=class extends Error{constructor(){super("Invalid Reunite URL")}};function we(n){return typeof n=="string"&&n in R}import{Buffer as O}from"node:buffer";import F from"node:crypto";import{mkdirSync as ye,existsSync as ne,writeFileSync as ve,readFileSync as Te,rmSync as xe}from"node:fs";import{homedir as Ce}from"node:os";import se from"node:path";import*as re from"node:child_process";var w=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new x("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]];re.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,o)=>{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),o(c.error_description))},e*1e3),a=setTimeout(async()=>{clearInterval(i),clearTimeout(a),o("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:o=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:o,expiresIn:i}}async sendRequest(t,e="GET",r=void 0,s={}){let o=`${this.baseUrl}/api${t}`,i=await this.apiClient.request(o,{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 Pe="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",oe="aes-256-cbc",k=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=Ce();this.credentialsFolderPath=se.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=se.join(this.credentialsFolderPath,this.credentialsFileName),this.key=F.createHash("sha256").update(`${this.credentialsFolderPath}${Pe}`).digest(),this.iv=F.createHash("md5").update(this.credentialsFolderPath).digest(),ye(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let s=await new w(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 w(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new w(t,this.version),r=await this.readCredentials();if(!r||!D(t)||r.residency&&r.residency!==t)return null;if(await e.verifyToken(r.access_token))return r.access_token;try{let o=await e.refreshToken(r.refresh_token);return await this.saveCredentials(o),o.access_token}catch{return null}};async saveCredentials(t){try{let e=this.encryptCredentials(t);ve(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!ne(this.credentialsFilePath))return null;try{let t=Te(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){ne(this.credentialsFilePath)&&xe(this.credentialsFilePath)}encryptCredentials(t){let e=F.createCipheriv(oe,this.key,this.iv);return O.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=F.createDecipheriv(oe,this.key,this.iv),r=O.concat([e.update(O.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};import*as y from"node:fs";import*as h from"node:path";var Re=/\/orgs\/([^/]+)\/projects\//,Ee=[401,403];async function C(n,{organization:t,project:e,onSlugDeprecated:r}){let s=await $e(n,t,e);if(!s)return{organizationId:t,projectId:e};let o={organizationId:_e(s.uri),projectId:s.id};return(o.organizationId!==t||o.projectId!==e)&&r?.(o),o}async function $e(n,t,e){try{let r=await n.projects.find(t,e);if(!r)throw new u(`Project "${e}" was not found in organization "${t}". Use the IDs from the organization and project settings in Reunite.`,404);return r}catch(r){if(r instanceof u&&Ee.includes(r.status))return;throw r}}function _e(n){let t=n.match(Re)?.[1];if(!t)throw new Error(`Could not read the organization ID from the project URI "${n}".`);return t}async function Se({domain:n,apiKey:t,organization:e,project:r,mountPath:s,files:o,defaultBranch:i,commit:a,version:c,replace:$,onUploadStart:_,onSunsetWarning:v,onSlugDeprecated:A}){let f=new g({domain:n,apiKey:t,command:"push",version:c});try{let{organizationId:d,projectId:l}=await C(f,{organization:e,project:r,onSlugDeprecated:A}),M=await f.remotes.getDefaultBranch(d,l),p=await f.remotes.upsert(d,l,{mountBranchName:M,mountPath:s});_?.(p);let{id:P}=await f.remotes.push(d,l,{remoteId:p.id,commit:a,isMainBranch:i===a.branchName,replace:$},o.map(W=>({path:H(W.name),stream:y.createReadStream(W.path)})));return{pushId:P,organizationId:d,projectId:l}}finally{let d=f.getSunsetWarning();d&&v?.(d)}}function Ue(n,t){let e={};for(let s of n)if(y.statSync(s).isDirectory()){let o=s;ie(o,[]).forEach(a=>r(a,o))}else r(s,h.dirname(s));function r(s,o){let i=h.relative(o,s);e[i]&&t?.(e[i],s),e[i]=s}return Object.entries(e).map(([s,o])=>({name:s,path:h.resolve(o)}))}function ie(n,t){let e=y.readdirSync(n);for(let r of e){let s=h.join(n,r);y.statSync(s).isDirectory()?t=ie(s,t):t.push(s)}return t}async function ae({operation:n,condition:t,onConditionNotMet:e,startTime:r=Date.now(),retryTimeoutMs:s=6e5,retryIntervalMs:o=5e3}){async function i(){let a=await n();if(t(a))return a;if(Date.now()-r>s)throw new Error("Timeout exceeded.");return await e?.(a),await z(o),i()}return i()}var Fe=1200,Ae=5e3,Ie=["pending","running"];async function Ne(n){let t=ce(n);try{let e=await C(t,n);return await le(t,e,n.pushId)}finally{ue(t,n)}}async function je({buildType:n,maxExecutionTime:t=Fe,retryIntervalMs:e=Ae,startTime:r=Date.now(),onRetry:s,...o}){let i=ce(o);try{let a=await C(i,o);return await ae({operation:()=>le(i,a,o.pushId),condition:c=>!Ie.includes(c.status[n].deploy.status),onConditionNotMet:s,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{ue(i,o)}}function ce({domain:n,apiKey:t,version:e}){return new g({domain:n,apiKey:t,command:"push-status",version:e})}function ue(n,{onSunsetWarning:t}){let e=n.getSunsetWarning();e&&t?.(e)}function le(n,{organizationId:t,projectId:e},r){return n.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function De({projectUrl:n,auth:t,isApiKey:e=!1,onDebug:r}){let s=Oe(n);if(!s)throw new m(`Invalid project URL format: ${n}`);try{let o=await ke({...s,auth:t,isApiKey:e,onDebug:r}),i=o.config.scorecardClassic||o.config.scorecard;if(!i)throw new Error("No scorecard configuration found.");let a=o.config.pluginsUrl,c=a?await Le(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(o){throw new m(o instanceof Error?o.message:String(o))}}function Oe(n){let t=new URL(n),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 ke({residency:n,orgSlug:t,projectSlug:e,auth:r,isApiKey:s,onDebug:o}){let i=new URL(`${n}/api/orgs/${t}/projects/${e}`),a=await fetch(i,{headers:Be(r,s)});if(o?.(`Project fetch response status: ${a.status}`),a.status===401||a.status===403)throw o?.(`Authentication failed with status ${a.status}.`),o?.("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 o?.("Successfully received project configuration."),a.json()}async function Le(n,t){t?.(`Fetching plugins from: ${n}`);try{let e=await fetch(n);if(t?.(`Plugins fetch response status: ${e.status}`),e.status!==200){t?.("Failed to fetch plugins");return}return e.text()}catch(e){t?.(`Error fetching plugins: ${e instanceof Error?e.message:String(e)}`);return}}function Be(n,t){return t?{Authorization:`Bearer ${n}`}:{Cookie:`accessToken=${n}`}}async function L(n,t,e=[],r=[],s){let o={};for(let i of e){let a={[i.name]:{root:n,rules:t}},c=await Y({apis:a,...i,plugins:r},{configPath:s});o[i.name]=c.forAlias(i.name)}return o}function B(n,t){if(n){for(let e of n)if(Object.entries(e.where?.metadata||{}).every(([s,o])=>Me(s,o,t)))return e}}function Me(n,t,e){if(t.match(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?\/(\d{4}-\d{2}-\d{2})?$/)){if(!e[n])return!1;let[r,s]=t.split("/"),o=new Date(e[n]);return!(o<new Date(r)||s&&o>new Date(s))}else if(t.match(/^\/.*\//)){if(!e[n])return!1;try{return q(t).test(e[n])}catch{throw new m(`Invalid regex in scorecard target "${n}": ${t}`)}}return e[n]===t}import{pathToFileURL as We}from"node:url";async function be(n,t){if(!n)return[];let e=We(t??process.cwd()).href+"/",r=n.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var ze=".redocly.com";function He(n){try{return new URL(n).hostname.toLowerCase().endsWith(ze)}catch{return!1}}async function qe({apiPath:n,document:t,externalRefResolver:e,scorecardConfig:r,configPath:s,plugins:o=[],targetLevel:i,metadata:a={},onDebug:c}){let $=[],_=new Map,v=r.levels||[];if(i&&!v.some(l=>l.name===i))throw new m(`Target level "${i}" not found in the scorecard configuration levels.
|
|
7
|
+
import{a as K}from"./GKXY6U4S.js";import{Aa as V,j as z,l as I,o as H,oa as m,p as q,ta as Y}from"./EQTXHL74.js";import{e as b}from"./RFWIIJFG.js";var Q=b(K(),1);var T=b(K(),1);function G(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function X(n){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(n).hostname.toLowerCase()}catch{return!1}return e.some(s=>!!(s==="*"||r===s||s.startsWith(".")&&r.endsWith(s)||!s.startsWith(".")&&r.endsWith("."+s)))}var Z=async(n,{timeout:t,...e}={})=>{let r=G(),s=r&&!X(n),o;s?o=new T.ProxyAgent({uri:r}):t&&(o=new T.Agent({connect:{timeout:t}}));try{return await(0,T.fetch)(n,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:o})}catch(i){throw await o?.destroy(),i}};var de=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function J(){let n=process.env.REDOCLY_ENVIRONMENT?.trim();return n&&de.test(n)?n:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},x=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=J(),s={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let o=await Z(t,{...e,headers:s});return this.collectSunsetWarning(o),o}catch(o){let i=o.cause??o,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)}},U=class{client;domain;apiKey;constructor(t,e,r){this.client=t,this.domain=e,this.apiKey=r}async getParsedResponse(t){let e=await t.json();if(t.ok)return e;throw new u(`${e.title||t.statusText||"Unknown error"}.`,t.status)}},N=class extends U{async find(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${encodeURIComponent(t)}/projects/${encodeURIComponent(e)}`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return r.status===404?void 0:await this.getParsedResponse(r)}catch(r){let s=`Failed to fetch project. ${r.message}`;throw r instanceof u?new u(s,r.status):new Error(s)}}},j=class extends U{async getDefaultBranch(t,e){try{let r=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/source`,{timeout:6e3,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return(await this.getParsedResponse(r)).branchName}catch(r){let 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",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(s)}catch(s){let o=`Failed to upsert remote. ${s.message}`;throw s instanceof u?new u(o,s.status):new Error(o)}}async push(t,e,r,s){let o=new Q.FormData;o.append("remoteId",r.remoteId),o.append("commit[message]",r.commit.message),o.append("commit[author][name]",r.commit.author.name),o.append("commit[author][email]",r.commit.author.email),o.append("commit[branchName]",r.commit.branchName),r.commit.url&&o.append("commit[url]",r.commit.url),r.commit.namespace&&o.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&o.append("commit[sha]",r.commit.sha),r.commit.repository&&o.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&o.append("commit[createdAt]",r.commit.createdAt);for(let i of s){let a=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await he(i.stream)]);o.append(`files[${i.path}]`,a,i.path)}r.isMainBranch&&o.append("isMainBranch","true"),r.replace&&o.append("replace","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${t}/projects/${e}/pushes`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:o});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",Authorization:`Bearer ${this.apiKey}`}});return await this.getParsedResponse(s)}catch(s){let o=`Failed to get push status. ${s.message}`;throw s instanceof u?new u(o,s.status):new Error(o)}}},g=class{apiClient;projects;remotes;constructor({domain:t,apiKey:e,command:r,version:s}){this.apiClient=new x(r,s),this.projects=new N(this.apiClient,t,e),this.remotes=new j(this.apiClient,t,e)}getSunsetWarning(){return ee(this.apiClient.sunsetWarnings)}};function ee(n){let[t]=[...n].sort((e,r)=>e.isSunsetExpired!==r.isSunsetExpired?e.isSunsetExpired?-1:1:e.sunsetDate>r.sunsetDate?1:-1);return t}async function he(n){let t=[];for await(let e of n)t.push(e);return Buffer.concat(t)}function fe(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var pe=/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/,R={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function me(){return process.env.REDOCLY_DOMAIN||R.us}var te=ge((n,t)=>{try{let e=t||n?.resolvedConfig.residency;return we(e)?R[e]:e?new URL(e).origin:n?.resolvedConfig.scorecard?.fromProjectUrl?new URL(n.resolvedConfig.scorecard.fromProjectUrl).origin:R.us}catch{throw new E}});function D(n){try{te(void 0,n)}catch{return!1}return!0}function ge(n){return(...t)=>{let e=n(...t);if(!e.startsWith("https://")&&!pe.test(e))throw new E;return e}}var E=class extends Error{constructor(){super("Invalid Reunite URL")}};function we(n){return typeof n=="string"&&n in R}import{Buffer as O}from"node:buffer";import F from"node:crypto";import{mkdirSync as ye,existsSync as ne,writeFileSync as ve,readFileSync as Te,rmSync as xe}from"node:fs";import{homedir as Ce}from"node:os";import se from"node:path";import*as re from"node:child_process";var w=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new x("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]];re.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,o)=>{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),o(c.error_description))},e*1e3),a=setTimeout(async()=>{clearInterval(i),clearTimeout(a),o("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:o=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:o,expiresIn:i}}async sendRequest(t,e="GET",r=void 0,s={}){let o=`${this.baseUrl}/api${t}`,i=await this.apiClient.request(o,{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 Pe="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",oe="aes-256-cbc",k=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=Ce();this.credentialsFolderPath=se.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=se.join(this.credentialsFolderPath,this.credentialsFileName),this.key=F.createHash("sha256").update(`${this.credentialsFolderPath}${Pe}`).digest(),this.iv=F.createHash("md5").update(this.credentialsFolderPath).digest(),ye(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let s=await new w(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 w(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new w(t,this.version),r=await this.readCredentials();if(!r||!D(t)||r.residency&&r.residency!==t)return null;if(await e.verifyToken(r.access_token))return r.access_token;try{let o=await e.refreshToken(r.refresh_token);return await this.saveCredentials(o),o.access_token}catch{return null}};async saveCredentials(t){try{let e=this.encryptCredentials(t);ve(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!ne(this.credentialsFilePath))return null;try{let t=Te(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){ne(this.credentialsFilePath)&&xe(this.credentialsFilePath)}encryptCredentials(t){let e=F.createCipheriv(oe,this.key,this.iv);return O.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=F.createDecipheriv(oe,this.key,this.iv),r=O.concat([e.update(O.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};import*as y from"node:fs";import*as h from"node:path";var Re=/\/orgs\/([^/]+)\/projects\//,Ee=[401,403];async function C(n,{organization:t,project:e,onSlugDeprecated:r}){let s=await $e(n,t,e);if(!s)return{organizationId:t,projectId:e};let o={organizationId:_e(s.uri),projectId:s.id};return(o.organizationId!==t||o.projectId!==e)&&r?.(o),o}async function $e(n,t,e){try{let r=await n.projects.find(t,e);if(!r)throw new u(`Project "${e}" was not found in organization "${t}". Use the IDs from the organization and project settings in Reunite.`,404);return r}catch(r){if(r instanceof u&&Ee.includes(r.status))return;throw r}}function _e(n){let t=n.match(Re)?.[1];if(!t)throw new Error(`Could not read the organization ID from the project URI "${n}".`);return t}async function Se({domain:n,apiKey:t,organization:e,project:r,mountPath:s,files:o,defaultBranch:i,commit:a,version:c,replace:$,onUploadStart:_,onSunsetWarning:v,onSlugDeprecated:A}){let f=new g({domain:n,apiKey:t,command:"push",version:c});try{let{organizationId:d,projectId:l}=await C(f,{organization:e,project:r,onSlugDeprecated:A}),M=await f.remotes.getDefaultBranch(d,l),p=await f.remotes.upsert(d,l,{mountBranchName:M,mountPath:s});_?.(p);let{id:P}=await f.remotes.push(d,l,{remoteId:p.id,commit:a,isMainBranch:i===a.branchName,replace:$},o.map(W=>({path:H(W.name),stream:y.createReadStream(W.path)})));return{pushId:P,organizationId:d,projectId:l}}finally{let d=f.getSunsetWarning();d&&v?.(d)}}function Ue(n,t){let e={};for(let s of n)if(y.statSync(s).isDirectory()){let o=s;ie(o,[]).forEach(a=>r(a,o))}else r(s,h.dirname(s));function r(s,o){let i=h.relative(o,s);e[i]&&t?.(e[i],s),e[i]=s}return Object.entries(e).map(([s,o])=>({name:s,path:h.resolve(o)}))}function ie(n,t){let e=y.readdirSync(n);for(let r of e){let s=h.join(n,r);y.statSync(s).isDirectory()?t=ie(s,t):t.push(s)}return t}async function ae({operation:n,condition:t,onConditionNotMet:e,startTime:r=Date.now(),retryTimeoutMs:s=6e5,retryIntervalMs:o=5e3}){async function i(){let a=await n();if(t(a))return a;if(Date.now()-r>s)throw new Error("Timeout exceeded.");return await e?.(a),await z(o),i()}return i()}var Fe=1200,Ae=5e3,Ie=["pending","running"];async function Ne(n){let t=ce(n);try{let e=await C(t,n);return await le(t,e,n.pushId)}finally{ue(t,n)}}async function je({buildType:n,maxExecutionTime:t=Fe,retryIntervalMs:e=Ae,startTime:r=Date.now(),onRetry:s,...o}){let i=ce(o);try{let a=await C(i,o);return await ae({operation:()=>le(i,a,o.pushId),condition:c=>!Ie.includes(c.status[n].deploy.status),onConditionNotMet:s,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{ue(i,o)}}function ce({domain:n,apiKey:t,version:e}){return new g({domain:n,apiKey:t,command:"push-status",version:e})}function ue(n,{onSunsetWarning:t}){let e=n.getSunsetWarning();e&&t?.(e)}function le(n,{organizationId:t,projectId:e},r){return n.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function De({projectUrl:n,auth:t,isApiKey:e=!1,onDebug:r}){let s=Oe(n);if(!s)throw new m(`Invalid project URL format: ${n}`);try{let o=await ke({...s,auth:t,isApiKey:e,onDebug:r}),i=o.config.scorecardClassic||o.config.scorecard;if(!i)throw new Error("No scorecard configuration found.");let a=o.config.pluginsUrl,c=a?await Le(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(o){throw new m(o instanceof Error?o.message:String(o))}}function Oe(n){let t=new URL(n),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 ke({residency:n,orgSlug:t,projectSlug:e,auth:r,isApiKey:s,onDebug:o}){let i=new URL(`${n}/api/orgs/${t}/projects/${e}`),a=await fetch(i,{headers:Be(r,s)});if(o?.(`Project fetch response status: ${a.status}`),a.status===401||a.status===403)throw o?.(`Authentication failed with status ${a.status}.`),o?.("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 o?.("Successfully received project configuration."),a.json()}async function Le(n,t){t?.(`Fetching plugins from: ${n}`);try{let e=await fetch(n);if(t?.(`Plugins fetch response status: ${e.status}`),e.status!==200){t?.("Failed to fetch plugins");return}return e.text()}catch(e){t?.(`Error fetching plugins: ${e instanceof Error?e.message:String(e)}`);return}}function Be(n,t){return t?{Authorization:`Bearer ${n}`}:{Cookie:`accessToken=${n}`}}async function L(n,t,e=[],r=[],s){let o={};for(let i of e){let a={[i.name]:{root:n,rules:t}},c=await Y({apis:a,...i,plugins:r},{configPath:s});o[i.name]=c.forAlias(i.name)}return o}function B(n,t){if(n){for(let e of n)if(Object.entries(e.where?.metadata||{}).every(([s,o])=>Me(s,o,t)))return e}}function Me(n,t,e){if(t.match(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?\/(\d{4}-\d{2}-\d{2})?$/)){if(!e[n])return!1;let[r,s]=t.split("/"),o=new Date(e[n]);return!(o<new Date(r)||s&&o>new Date(s))}else if(t.match(/^\/.*\//)){if(!e[n])return!1;try{return q(t).test(e[n])}catch{throw new m(`Invalid regex in scorecard target "${n}": ${t}`)}}return e[n]===t}import{pathToFileURL as We}from"node:url";async function be(n,t){if(!n)return[];let e=We(t??process.cwd()).href+"/",r=n.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var ze=".redocly.com";function He(n){try{return new URL(n).hostname.toLowerCase().endsWith(ze)}catch{return!1}}async function qe({apiPath:n,document:t,externalRefResolver:e,scorecardConfig:r,configPath:s,plugins:o=[],targetLevel:i,metadata:a={},onDebug:c}){let $=[],_=new Map,v=r.levels||[];if(i&&!v.some(l=>l.name===i))throw new m(`Target level "${i}" not found in the scorecard configuration levels.
|
|
8
8
|
`);let A=B(r.targets,a)?.rules,f=await L(n,A,v,o,s||"");for(let l of v){c?.(`
|
|
9
9
|
Validating level: "${l.name}"`),o.length>0&&c?.(`Using ${o.length} ${I("plugin",o.length)} for this level.`),c?.("Linting document against level rules...");let p=(await V({document:t,externalRefResolver:e,config:f[l.name]})).filter(({ignored:P})=>!P).map(P=>({...P,scorecardLevel:l.name}));c?.(`Found ${p.length} ${I("problem",p.length)} for level "${l.name}".`),_.set(l.name,p),$.push(...p)}let d=Ye(_,v,i);return{problems:$,achievedLevel:d,targetLevelAchieved:i?d===i:!0}}function Ye(n,t,e){let r=null;for(let s of t){if((n.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,x as b,g as c,ee as d,fe as e,R as f,me as g,te as h,D as i,E as j,w as k,k as l,C as m,Se as n,Ue as o,Ne as p,je as q,De as r,L as s,B as t,be as u,He as v,qe as w};
|