@redocly/cli 2.57.0 → 2.58.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 +2 -0
- package/THIRD_PARTY_NOTICES +44 -22
- package/lib/chunks/2523PDUF.js +160 -0
- package/lib/chunks/{VBHLPG5Q.js → 252ZXXJ7.js} +1 -1
- package/lib/chunks/{XYKNLM5G.js → 2ERUBDSZ.js} +1 -1
- package/lib/chunks/{DMW5VJBT.js → 2LDRZLQD.js} +1 -1
- package/lib/chunks/{S5PUZGYS.js → 3QTDDZ3U.js} +1 -1
- package/lib/chunks/{ZVXAH4QD.js → 3RJ5Q24M.js} +1 -1
- package/lib/chunks/{J3DL5HGI.js → 3TNSVCBC.js} +1 -1
- package/lib/chunks/3TRGOJ74.js +9 -0
- package/lib/chunks/{X5NXRMUW.js → 46SNGFKM.js} +1 -1
- package/lib/chunks/4BCJL2BX.js +13 -0
- package/lib/chunks/5WKNTF7W.js +22 -0
- package/lib/chunks/{MZWBJKK2.js → 65C4QORD.js} +1 -1
- package/lib/chunks/{D7WNH6Z5.js → 6ESHHDEM.js} +1 -1
- package/lib/chunks/{YOBULQYM.js → 6G6YWZOW.js} +1 -1
- package/lib/chunks/{UXFJO2OQ.js → 6HHP5O4K.js} +1 -1
- package/lib/chunks/{JMFIKCPX.js → 6XXDGMQI.js} +1 -1
- package/lib/chunks/{YDVOCOBI.js → 7BM3QKWP.js} +1 -1
- package/lib/chunks/{GEWI247R.js → 7HX6H6PZ.js} +1 -1
- package/lib/chunks/{H5OX3UOD.js → 7KZRKMQI.js} +1 -1
- package/lib/chunks/{3QGJWJKQ.js → ABUS6H76.js} +1 -1
- package/lib/chunks/{EDU3YBRA.js → BNAH4YGC.js} +1 -1
- package/lib/chunks/{7EB22KXX.js → BZNIB4HL.js} +1 -1
- package/lib/chunks/{AOCVSFC3.js → C6B5SYPM.js} +1 -1
- package/lib/chunks/{7XKYPQPI.js → D2IJWX6B.js} +1 -1
- package/lib/chunks/{LI6IH6DJ.js → DVJIGHFR.js} +1 -1
- package/lib/chunks/{CWEET26O.js → EPFKYDYC.js} +1 -1
- package/lib/chunks/ERFOEXTV.js +9 -0
- package/lib/chunks/{R2FG6TUX.js → FBHTM4LH.js} +1 -1
- package/lib/chunks/{5FVKAWNE.js → FIMSBOF2.js} +1 -1
- package/lib/chunks/{ZFJHZEI3.js → GDFQSHUE.js} +1 -1
- package/lib/chunks/H4VN2RX3.js +7 -0
- package/lib/chunks/{ZBOUASE7.js → H7Z35EAH.js} +1 -1
- package/lib/chunks/JF6HX6A6.js +7 -0
- package/lib/chunks/{FDOONAMV.js → JPHYX7OV.js} +1 -1
- package/lib/chunks/{SRCGYHDN.js → JXAUEF5V.js} +1 -1
- package/lib/chunks/{4HG5PCQA.js → LIAO3NFX.js} +1 -1
- package/lib/chunks/{LUW2ZJJO.js → LWTH3K75.js} +1 -1
- package/lib/chunks/{VIPV4IEH.js → M4JX2FBY.js} +1 -1
- package/lib/chunks/ML6MFXCA.js +7 -0
- package/lib/chunks/{M4YE5ALG.js → MT5H2R3P.js} +81 -81
- package/lib/chunks/{GHOLYNZA.js → MWJGFN4Y.js} +1 -1
- package/lib/chunks/N6VRECSO.js +34 -0
- package/lib/chunks/{65AQJO4M.js → NRU2WFMW.js} +2 -2
- package/lib/chunks/NSNQAVBA.js +17 -0
- package/lib/chunks/{N2GTHB37.js → NYQDTPTE.js} +1 -1
- package/lib/chunks/OJE7THLM.js +31 -0
- package/lib/chunks/{F5V42ZYY.js → OQ2G774U.js} +1 -1
- package/lib/chunks/{F57WBWGV.js → PB256IKB.js} +2 -2
- package/lib/chunks/{OR3KBRCI.js → PWVCTNVT.js} +1 -1
- package/lib/chunks/{4SXCDBB7.js → PZEYEOIF.js} +1 -1
- package/lib/chunks/{4JBK2BSL.js → QXUO5IQJ.js} +1 -1
- package/lib/chunks/{DT66L2TO.js → QZJD7SST.js} +1 -1
- package/lib/chunks/{GVJFU4AP.js → R5A3H7N2.js} +1 -1
- package/lib/chunks/{YMDFCK3F.js → ROE2PM62.js} +1 -1
- package/lib/chunks/{VE7VT5PT.js → RREAI5RF.js} +1 -1
- package/lib/chunks/{QDSAT32N.js → SXYE4UNQ.js} +1 -1
- package/lib/chunks/T2G7FRCU.js +23 -0
- package/lib/chunks/{664FDTDV.js → T6HGKHGP.js} +1 -1
- package/lib/chunks/{YEACSN2C.js → TAEOWXJJ.js} +1 -1
- package/lib/chunks/{Y2AFRRAT.js → TTWBJ74O.js} +1 -1
- package/lib/chunks/U4WMP25Y.js +7 -0
- package/lib/chunks/{5UDC2SWY.js → V34PUN4E.js} +1 -1
- package/lib/chunks/{IDI3SURO.js → VNSAGJ2H.js} +1 -1
- package/lib/chunks/{VT3BHT6S.js → WFGS4GSF.js} +3 -3
- package/lib/chunks/{NALRPITK.js → WSDNWUOV.js} +1 -1
- package/lib/chunks/{P7A7BCIN.js → X5U3XCIW.js} +1 -1
- package/lib/chunks/XARQ5LTM.js +15 -0
- package/lib/chunks/{WKCOTH3C.js → YFBPBQ7G.js} +1 -1
- package/lib/chunks/{52MXI4PU.js → YLFY2DKU.js} +1 -1
- package/lib/chunks/{VUU57INZ.js → YMMEOUYX.js} +1 -1
- package/lib/chunks/{XTTR5PBC.js → YPT2KQ2K.js} +1 -1
- package/lib/chunks/{MKS4O6F4.js → YTAL3SI4.js} +2 -2
- package/lib/chunks/index.aff +205 -0
- package/lib/chunks/index.dic +49569 -0
- 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 +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/index.js +66 -61
- package/package.json +1 -1
- package/lib/chunks/2PGNW76R.js +0 -11
- package/lib/chunks/3I7XLHPY.js +0 -45
- package/lib/chunks/ARDTVDGR.js +0 -22
- package/lib/chunks/K2ENYHHD.js +0 -7
- package/lib/chunks/LJPUHAWE.js +0 -13
- package/lib/chunks/OM4VGI2Q.js +0 -9
- package/lib/chunks/VYHYEZI5.js +0 -7
- package/lib/chunks/YFI3NLJF.js +0 -9
- package/lib/chunks/YUNIBLZR.js +0 -30
package/package.json
CHANGED
package/lib/chunks/2PGNW76R.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as v}from"./LI6IH6DJ.js";import{a as x,b as y,c as R,d as u}from"./ARDTVDGR.js";import{c as f,d as g}from"./WKCOTH3C.js";import{X as a,ca as m,da as w}from"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{mkdir as S,writeFile as O}from"node:fs/promises";import C from"node:path";async function F(e){let i=await g(e.trafficPath);if(i.length===0)throw new Error("No traffic files found in the provided traffic path.");let t=y.create({openApiIndex:e.openApiIndex,matchMode:e.matchMode,ignoreCookies:e.ignoreCookies,ignoreHeaders:e.ignoreHeaders,previewFindingsLimit:e.previewFindingsLimit,activeRules:e.activeRules,server:e.server,minSeverity:e.minSeverity}),r=0,o=0;for(let n of i){let s=await v(n,e.format);if(!s){a.warn(`Skipping traffic file with unrecognized format: ${n}
|
|
8
|
-
`);continue}r+=1;for await(let c of s.parse(n))await t.process({...c,index:o}),o+=1}if(r===0)throw new Error("No supported traffic files found. In auto mode, files must match built-in traffic parser signatures.");if(o===0)throw new Error("No HTTP exchanges were parsed from the provided traffic files.");return t.finalize()}var E=!!process.stdout.isTTY&&process.env.NO_COLOR===void 0;function T(e){let i=new Set;for(let t of e.operationsByMethod.values())for(let r of t)for(let o of r.servers)i.add(o.rawUrl);return Array.from(i).sort()}function I(e,i,t){let r=e.totalExchanges-e.skippedExchanges;if(r===0&&e.skippedExchanges>0){a.warn(`All ${e.skippedExchanges} exchange(s) were outside the --server "${t}" and were skipped. Check that the server matches the traffic URLs.
|
|
9
|
-
`);return}if(e.documentedExchanges>0||r===0)return;let o=T(i),n=t?`Check that the --server "${t}" matches the traffic URLs and that the description paths align with the remainder.`:e.hostCompatibleExchanges===r?`The traffic hosts are compatible with the description servers (${o.join(", ")}), so the endpoints are likely undocumented; if they should be documented, check that the description base paths and paths align with the traffic URLs, or use --server to declare the server the traffic was captured against.`:`Check that the traffic host and base path match the description servers (${o.join(", ")}), or use --server to declare the server the traffic was captured against.`;a.warn(`None of the ${r} validated exchange(s) matched a documented operation. ${n}
|
|
10
|
-
`)}async function $(e,i){let t=f(e);await S(C.dirname(t),{recursive:!0}),await O(t,i,"utf8")}async function q({argv:e,config:i}){let t=f(e.traffic),r=e["traffic-format"],o=e.rules?u(e.rules):void 0,n=e["ignore-headers"]?u(e["ignore-headers"]):void 0,s=e.server;if(s&&e["match-mode"])throw new m("The --server and --match-mode options are mutually exclusive: --match-mode controls how requests are located via the description servers, while --server replaces the description servers with the one the traffic was captured against.");let c=e["match-mode"]??"strict-host",d=f(e.api),p=await R(d,i);if(p.loadedOperations===0)throw new m(`No OpenAPI operations were loaded from: ${d}`);let{runId:k,summary:h,findings:A}=await F({trafficPath:t,format:r,matchMode:c,ignoreCookies:e["ignore-cookies"],ignoreHeaders:n,previewFindingsLimit:e["max-findings"],activeRules:o,openApiIndex:p,server:s,minSeverity:e["min-severity"]});I(h,p,s);let l=x({runId:k,summary:h,findings:A,meta:{specSource:d,trafficPath:t,format:r,matchMode:c,server:s}},{format:e["report-format"],color:E&&e["report-format"]==="pretty"&&!e.output,maxFindings:e["max-findings"]});if(e.output?(await $(e.output,l),a.info(`Drift report written to: ${f(e.output)}
|
|
11
|
-
`)):a.output(l),h.findingsBySeverity.error>0)throw new w("Drift detected.")}export{q as handleDrift};
|
package/lib/chunks/3I7XLHPY.js
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{$,C as V,D as F,E as _,H as U,O as B,P as j,Q as K,R as l,V as u,X as o,ca as a,d as Y,da as J,e as S,f as G,ga as M,ja as I,ka as C,l as c,ma as q,pa as H,t as d}from"./M4YE5ALG.js";import{performance as be}from"perf_hooks";function X(e){return e?._?.[0]??""}import*as p from"node:fs";import{basename as Q,dirname as A,extname as h,join as Z,resolve as y,relative as ce}from"node:path";import*as f from"node:process";import{performance as fe}from"perf_hooks";var O=["json","yaml","yml"];async function re(e,n){let t=!S(e)&&G(n.resolvedConfig.apis)?me(n):await ue(e,n),s=t.filter(({path:i})=>!le(i));if(S(s)){for(let{path:i}of s)o.warn(`
|
|
8
|
-
${v(i)} ${B(`does not exist or is invalid.
|
|
9
|
-
|
|
10
|
-
`)}`);throw new a("Please provide a valid path.")}if(t.length===0)throw new a("No APIs were provided. Specify an API via the command argument or define one in your config.");return t}function T(e){return e.configPath?A(e.configPath):f.cwd()}function le(e){if(!e.trim())throw new a("Path cannot be empty.");return p.existsSync(e)||d(e)?e:void 0}function me(e){return Object.entries(e.resolvedConfig.apis||{}).map(([n,{root:r,output:t}])=>({path:d(r)?r:y(T(e),r),alias:n,output:t&&y(T(e),t)}))}function ee(e,n){let r=T(e),t=e.resolvedConfig.apis?.[n];return t?{path:d(t.root)?t.root:y(r,t.root),alias:n,output:t.output&&y(r,t.output)}:{path:n,alias:Object.entries(e.resolvedConfig.apis||{}).find(([s,i])=>y(r,i.root)===y(n))?.[0]??void 0}}async function ue(e,n){let{hasMagic:r,glob:t}=await import("./SJHPKWSD.js");return(await Promise.all(e.map(async s=>r(s)&&!d(s)?(await t(s,{cwd:T(n)})).map(w=>ee(n,w)):ee(n,s)))).flat()}function R(e){return f.env.NODE_ENV==="test"?"<test>ms":`${Math.ceil(fe.now()-e)}ms`}function ke(e,n,r){let t=R(n);o.info(u(`
|
|
11
|
-
${r}: ${e} processed in ${t}
|
|
12
|
-
|
|
13
|
-
`))}function Ne(e,n){return e==="/"?n:e.replaceAll("~1","/").replaceAll("~0","~").replace(/^\//,"").replaceAll("/",n)}function Se(e){return e.replace(/#/g,"_sharp").replace(/\//,"_").replace(/\s/g,"")}function Fe(e){return{php:".php","c#":".cs",shell:".sh",curl:".sh",bash:".sh",javascript:".js",js:".js",python:".py",c:".c","c++":".cpp",coffeescript:".litcoffee",dart:".dart",elixir:".ex",go:".go",groovy:".groovy",java:".java",kotlin:".kt","objective-c":".m",perl:".pl",powershell:".ps1",ruby:".rb",rust:".rs",scala:".sc",swift:".swift",typescript:".ts",tsx:".tsx","visual basic":".vb","c/al":".al"}[e.toLowerCase()]??""}var P=class e extends Error{constructor(r){super(r.message);this.originalError=r;Object.setPrototypeOf(this,e.prototype)}originalError};function Ie(e,n,r){if(n==="json")try{return JSON.stringify(e,null,2)}catch(t){throw t.message.indexOf("circular")>-1?new P(t):t}else return F(e,{noRefs:!r,lineWidth:-1})}function Re(e,n){p.mkdirSync(A(e),{recursive:!0}),p.writeFileSync(e,n)}function Le(e){return V(p.readFileSync(e,"utf-8"),{filename:e})}function ze(e,n,r){if(ye(n)==="json"){de(e,n);return}ge(e,n,r)}function ge(e,n,r=!1){let t=F(e,{noRefs:r});if(f.env.NODE_ENV==="test"){o.info(t);return}p.mkdirSync(A(n),{recursive:!0}),p.writeFileSync(n,t)}function de(e,n){let r=JSON.stringify(e,null,2);if(f.env.NODE_ENV==="test"){o.info(r);return}p.mkdirSync(A(n),{recursive:!0}),p.writeFileSync(n,r)}function ye(e){let n=e.split(".").pop();return O.includes(n)?n:(o.warn(`Unsupported file extension: ${n}. Using yaml.
|
|
14
|
-
`),"yaml")}function L(e,n){switch(e.constructor){case a:throw e;case U:throw new a(`Failed to resolve API description at ${n}:
|
|
15
|
-
|
|
16
|
-
- ${e.message}`);case _:throw new a(`Failed to parse API description at ${n}:
|
|
17
|
-
|
|
18
|
-
- ${e.message}`);case P:throw new a(`Detected circular reference which can't be converted to JSON.
|
|
19
|
-
Try to use ${l("yaml")} output or remove ${l("--dereferenced")}.`);case SyntaxError:throw new a(`Syntax error: ${e.message} ${e.stack?.split(`
|
|
20
|
-
|
|
21
|
-
`)?.[0]}`);case $:throw new a(e.message);default:throw new a(`Something went wrong when processing ${n}:
|
|
22
|
-
|
|
23
|
-
- ${e.message}`)}}function te(e,n){let r=e.ignored?K(`${e.ignored} ${c("problem is",e.ignored)} explicitly ignored.
|
|
24
|
-
|
|
25
|
-
`):"";e.errors>0?o.error(`\u274C Validation failed with ${e.errors} ${c("error",e.errors)}${e.warnings>0?` and ${e.warnings} ${c("warning",e.warnings)}`:""}.
|
|
26
|
-
${r}`):e.warnings>0?(o.info(j(`Woohoo! Your API ${c("description is",n)} valid. \u{1F389}
|
|
27
|
-
`)),o.warn(`You have ${e.warnings} ${c("warning",e.warnings)}.
|
|
28
|
-
${r}`)):o.info(j(`Woohoo! Your API ${c("description is",n)} valid. \u{1F389}
|
|
29
|
-
${r}`)),e.errors>0&&o.info(u("run `redocly lint --generate-ignore-file` to add all problems to the ignore file.\n")),o.info(`
|
|
30
|
-
`)}function oe(e,n){e.errors>0?o.error(`\u274C Your config has ${e.errors} ${c("error",e.errors)}.
|
|
31
|
-
`):e.warnings>0?o.warn(`\u26A0\uFE0F Your config has ${e.warnings} ${c("warning",e.warnings)}.
|
|
32
|
-
`):n==="check-config"&&o.info(j(`\u2705 Your config is valid.
|
|
33
|
-
`))}function We({entrypoint:e,output:n,argvOutput:r,ext:t,entries:s}){let i=n||r;if(!i)return{ext:t||"yaml"};if(s>1&&r){if(t=t||h(e).substring(1),!O.includes(t))throw new Error(`Invalid file extension: ${t}.`);i=Z(r,Q(e,h(e)))+"."+t}else{if(t=t||h(i).substring(1)||h(e).substring(1),!O.includes(t))throw new Error(`Invalid file extension: ${t}.`);i=Z(A(i),Q(i,h(i)))+"."+t}return{outputFile:i,ext:t}}function ie(e){let{preprocessors:n,rules:r,decorators:t}=e.getUnusedRules();r.length&&o.warn(`[WARNING] Unused rules found in ${l(e.configPath||"")}: ${r.join(", ")}.
|
|
34
|
-
`),n.length&&o.warn(`[WARNING] Unused preprocessors found in ${l(e.configPath||"")}: ${n.join(", ")}.
|
|
35
|
-
`),t.length&&o.warn(`[WARNING] Unused decorators found in ${l(e.configPath||"")}: ${t.join(", ")}.
|
|
36
|
-
`),(r.length||n.length)&&o.warn(`Check the spelling and verify the added plugin prefix.
|
|
37
|
-
`)}async function Ye(e,n){try{let r=await M({configPath:e.config,customExtends:e.extends});return await ne(e,n,r),r}catch(r){L(r,"")}}function we(e){return e.asyncapi?.startsWith("2")}var xe=["swagger","info","host","basePath","schemes","consumes","produces","security","tags","externalDocs","paths","definitions","parameters","responses","securityDefinitions"],he=["openapi","info","jsonSchemaDialect","servers","security","tags","externalDocs","paths","webhooks","x-webhooks","components"],Ae=["asyncapi","id","info","externalDocs","tags","defaultContentType","servers","channels","components"],ve=["asyncapi","info","defaultContentType","servers","channels","operations","components"];function Ge(e){return"asyncapi"in e?we(e)?D(e,Ae):D(e,ve):"swagger"in e?D(e,xe):D(e,he)}function D(e,n){let r={};for(let t of n)e.hasOwnProperty(t)&&(r[t]=e[t]);return Object.assign(r,e)}function se(e){let n={...e.oas2,...e.oas3_0,...e.oas3_1,...e.oas3_2,...e.async2,...e.async3,...e.arazzo1,...e.overlay1,...e.openrpc1,...e.graphql};if(Y(n))throw new a("\u26A0\uFE0F No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/")}function Ve(e){return e.replace(/\x1b\[\d+m/g,"")}function v(e){return d(e)?e:ce(f.cwd(),e)}async function qe({argv:e,config:n,version:r,collectSpecData:t,collectResults:s}){let i=await re(e.apis,n),m={errors:0,warnings:0,ignored:0},w=0,z=e.format==="checkstyle"||e.format==="junit",W=[];for(let{path:g,alias:k}of i)try{let N=be.now(),b=n.forAlias(k);se(b.rules),b.skipRules(e["skip-rule"]),b.skipPreprocessors(e["skip-preprocessor"]),typeof n.document?.parsed>"u"&&!e.extends&&o.info(`No configurations were provided -- using built in ${l("recommended")} configuration by default.
|
|
38
|
-
|
|
39
|
-
`),k===void 0?o.info(u(`validating ${v(g)}...
|
|
40
|
-
`)):o.info(u(`validating ${v(g)} using lint rules for api '${k}'...
|
|
41
|
-
`));let x=await q({ref:g,config:b,collectSpecData:t});s?.(x);let E=I(x);if(m.errors+=E.errors,m.warnings+=E.warnings,m.ignored+=E.ignored,e["generate-ignore-file"]){n.clearIgnoreForRef(g);for(let pe of x)n.addIgnore(pe),w++}else z?W.push(...x):C(x,{format:e.format,maxProblems:e["max-problems"],totals:E,version:r,command:"lint"});let ae=R(N);o.info(u(`${v(g)}: validated in ${ae}
|
|
42
|
-
|
|
43
|
-
`))}catch(N){L(N,g)}if(z&&!e["generate-ignore-file"]&&C(W,{format:e.format,maxProblems:e["max-problems"],totals:m,version:r,command:"lint"}),e["generate-ignore-file"]?(n.saveIgnore(),o.info(`Explicitly ignored ${w} ${c("problem",w)}.
|
|
44
|
-
|
|
45
|
-
`)):te(m,i.length),ie(n),!(m.errors===0||e["generate-ignore-file"]))throw new J("Lint failed.")}async function ne(e,n,r){if(e["lint-config"]==="off"||r.document===void 0||e.format==="json"||e.format==="junit"||e.format==="checkstyle")return;let t=e?X(e):void 0,s=await H({config:r,severity:e["lint-config"]||"warn"}),i=I(s);if(C(s,{format:e.format,maxProblems:e["max-problems"],totals:i,version:n,command:"check-config"}),oe(i,t),i.errors>0)throw new $}export{O as a,qe as b,ne as c,re as d,T as e,ee as f,R as g,ke as h,Ne as i,Se as j,Fe as k,Ie as l,Re as m,Le as n,ze as o,ye as p,L as q,We as r,ie as s,Ye as t,Ge as u,Ve as v,v as w};
|
package/lib/chunks/ARDTVDGR.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as oe,e as ae,f as ue,g as ce,h as b,i as de,k as H,l as V,m as pe,n as le,v as he,w as me}from"./WKCOTH3C.js";import{I as X,L as Je,M as Z,N as g,O,P as ee,Q as $,R as C,T as S,V as y,X as w,Y as te,Z as ne,_ as re,aa as se,c as l,fa as ie,q as Y,v as Q,y as We}from"./M4YE5ALG.js";import{e as J}from"./RFWIIJFG.js";import fe from"node:path";function R(t){return t?t.trim():""}function T(t){let e=R(t.operationId)||R(t.path);return[R(t.ruleId),R(t.severity),R(t.message),e,R(t.target),R(t.schemaPath)].join("")}var F=t=>Z(S(t));function Ye(t){return t==="error"?"error":t==="warning"?"warning":"note"}function Qe(t){if(t==null)return"";let e=String(t);return!e.includes(",")&&!e.includes('"')&&!e.includes(`
|
|
8
|
-
`)?e:`"${e.replace(/"/g,'""')}"`}function Xe(t){return fe.isAbsolute(t)?fe.relative(process.cwd(),t)||".":t}function Ze(t){if(!t)return null;let e=t.operationPathTemplate;return typeof e=="string"&&e.length>0?e:null}function et(t){return Object.entries(t).sort((e,r)=>{let n=r[1]-e[1];return n!==0?n:e[0].localeCompare(r[0])})}function tt(t){let e=[],r=new Map;for(let n of t){let s=T({ruleId:n.ruleId,severity:n.severity,message:n.message,operationId:n.operationId,path:n.path,target:n.target,schemaPath:n.schemaPath}),i=r.get(s);if(i!==void 0){e[i].occurrences+=1;continue}r.set(s,e.length),e.push({finding:n,occurrences:1})}return e}function nt(t){let e=tt(t.findings).map(n=>({occurrences:n.occurrences,exchangeIndex:n.finding.exchangeIndex,ruleId:n.finding.ruleId,severity:n.finding.severity,category:n.finding.category,message:n.finding.message,operationId:n.finding.operationId,specSource:n.finding.specSource,target:n.finding.target,schemaPath:n.finding.schemaPath,dataPath:n.finding.dataPath,details:n.finding.details,method:n.finding.method,url:n.finding.url,path:n.finding.path,status:n.finding.status})),r={run:{id:t.runId,specSource:t.meta.specSource,trafficPath:t.meta.trafficPath,format:t.meta.format,matchMode:t.meta.matchMode,server:t.meta.server,totalExchanges:t.summary.totalExchanges,documentedExchanges:t.summary.documentedExchanges,undocumentedExchanges:t.summary.undocumentedExchanges,skippedExchanges:t.summary.skippedExchanges,findingsBySeverity:t.summary.findingsBySeverity,findingsByRule:t.summary.findingsByRule,totalProblems:t.summary.totalProblemGroups,durationMs:t.summary.durationMs},problems:e};return`${JSON.stringify(r,null,2)}
|
|
9
|
-
`}function rt(t){let e=["run_id","finding_id","exchange_index","severity","category","rule_id","message","method","path","url","status","operation_id","spec_source","target","schema_path","data_path"],r=t.findings.map(s=>[t.runId,s.id,s.exchangeIndex,s.severity,s.category,s.ruleId,s.message,s.method,s.path,s.url,s.status,s.operationId,s.specSource,s.target,s.schemaPath,s.dataPath]);return`${[e,...r].map(s=>s.map(Qe).join(",")).join(`
|
|
10
|
-
`)}
|
|
11
|
-
`}function st(t){let e=new Map;for(let s of t.findings)e.has(s.ruleId)||e.set(s.ruleId,{id:s.ruleId,name:s.ruleId,shortDescription:{text:`${s.category} detection`}});let r=t.findings.map(s=>{let i=s.specSource??s.url??void 0;return{ruleId:s.ruleId,level:Ye(s.severity),message:{text:s.message},locations:i?[{physicalLocation:{artifactLocation:{uri:i}}}]:void 0,properties:{runId:t.runId,exchangeIndex:s.exchangeIndex,method:s.method,path:s.path,status:s.status,operationId:s.operationId,target:s.target,schemaPath:s.schemaPath,dataPath:s.dataPath}}}),n={$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"drift",rules:Array.from(e.values())}},results:r}]};return`${JSON.stringify(n,null,2)}
|
|
12
|
-
`}function it(t){return t.findingsBySeverity.error+t.findingsBySeverity.warning+t.findingsBySeverity.info}function ot(t){return t>=500?O:t>=400?$:t>=300?C:t>=200?ee:y}function at(t,e,r){let n=(h,f)=>e?f(h):h,s=h=>h==="error"?n("\u2716",O):h==="warning"?n("\u25B2",$):n("\u25CF",C),i=h=>h==="error"?n("ERROR",O):h==="warning"?n("WARN",$):n("INFO",C),{summary:o,meta:a}=t,c=it(o),p=o.previewFindings.slice(0,r),u=[];if(u.push(n("\u250F\u2501 Drift Report",F)),u.push(`\u2503 Run: ${t.runId}`),u.push(`\u2503 Spec: ${a.specSource}`),u.push(`\u2503 Traffic: ${a.trafficPath}`),u.push(a.server?`\u2503 Server: ${a.server} (overrides description servers)`:`\u2503 Match mode: ${a.matchMode}`),u.push(`\u2503 Traffic format: ${a.format}${a.format==="auto"?" (auto-detect)":""}`),u.push(`\u2503 Exchanges: total=${o.totalExchanges} documented=${o.documentedExchanges} undocumented=${o.undocumentedExchanges}${o.skippedExchanges>0?` skipped=${o.skippedExchanges}`:""}`),u.push(`\u2503 Findings: total=${c} ${n(`error=${o.findingsBySeverity.error}`,O)} ${n(`warning=${o.findingsBySeverity.warning}`,$)} ${n(`info=${o.findingsBySeverity.info}`,C)}`),u.push(`\u2503 Problems: total=${o.totalProblemGroups}`),u.push(`\u2517 Duration: ${o.durationMs}ms`),c===0)return u.push(""),u.push(n("\u2714 No findings.",S)),`${u.join(`
|
|
13
|
-
`)}
|
|
14
|
-
`;u.push(""),u.push(n(`Types (${Object.keys(o.problemGroupsByRule).length})`,F));for(let[h,f]of et(o.problemGroupsByRule)){let v=o.findingsByRule[h]??f;u.push(` ${n("\u2022",y)} ${h}: ${f} problems / ${v} findings`)}let m=new Map;for(let h of p)m.has(h.ruleId)||m.set(h.ruleId,[]),m.get(h.ruleId).push(h);let x=Array.from(m.keys()).sort((h,f)=>{let v=(o.problemGroupsByRule[f]??0)-(o.problemGroupsByRule[h]??0);return v!==0?v:h.localeCompare(f)});u.push(""),u.push(n(`Problems by type (showing first ${p.length} of ${o.totalProblemGroups})`,F));let q=0;for(let h of x){let f=m.get(h);if(!f||f.length===0)continue;let v=o.problemGroupsByRule[h]??f.length,ze=o.findingsByRule[h]??v;u.push(""),u.push(`${n("\u25C9",S)} ${n(h,F)} ${n(`(${f.length} problems shown / ${v} total, ${ze} findings)`,y)}`);for(let d of f){q+=1;let U=d.occurrences,De=d.status!==void 0?n(String(d.status),ot(d.status)):n("-",y),Ke=Ze(d.details)??d.path,Ue=d.operationId?` ${n(d.operationId,g)}`:"";if(u.push(`${s(d.severity)} ${i(d.severity)} #${q}${U>1?` ${n(`\xD7${U}`,y)}`:""} ${n("\u2192",y)} ${d.message}`),u.push(` \u21B3 sample exchange=${d.exchangeIndex} ${n(d.method,S)} ${Ke} (${De})${Ue}`),u.push(""),u.push(` ${n(d.url,y)}`),(d.specSource||d.schemaPath||d.dataPath)&&(u.push(""),d.specSource&&u.push(` ${n("spec:",g)} ${n(Xe(d.specSource),S)}`),d.schemaPath&&u.push(` ${n("schemaPath=",g)} ${n(d.schemaPath,g)}`),d.dataPath&&u.push(` ${n("dataPath=",g)} ${n(d.dataPath,S)}`)),d.details)if(u.push(""),d.ruleId==="security-baseline"&&typeof d.details.summary=="string")u.push(` ${n("security:",g)} ${d.details.summary}`);else if(d.ruleId==="owasp-api-top10"&&typeof d.details.summary=="string"){let k=typeof d.details.issueId=="string"?d.details.issueId:null,A=typeof d.details.issueTitle=="string"?d.details.issueTitle:null;u.push(` ${n("owasp:",g)} ${d.details.summary}`),(k||A)&&u.push(` ${n("issue:",g)} ${[k,A].filter(Boolean).join(" - ")}`)}else if(d.ruleId==="schema-consistency"&&typeof d.details.summary=="string"){let k=typeof d.details.path=="string"?d.details.path:null,A=typeof d.details.expected=="string"?d.details.expected:null,G=typeof d.details.actual=="string"?d.details.actual:null,W=typeof d.details.suggestion=="string"?d.details.suggestion:null;if(u.push(` ${n("schema:",g)} ${d.details.summary}`),k&&u.push(` ${n("path:",g)} ${n(k,S)}`),A&&u.push(` ${n("expected:",g)} ${A}`),G&&u.push(` ${n("actual:",g)} ${G}`),W){u.push(` ${n("hint:",g)}`);for(let Ge of W.split(`
|
|
15
|
-
`))u.push(` ${Ge}`)}}else u.push(` ${n("details:",g)} ${JSON.stringify(d.details)}`);u.push("")}}let P=o.totalProblemGroups-p.length;return P>0?(u[u.length-1]!==""&&u.push(""),u.push(n(`\u2026 ${P} problems omitted from terminal output. Use --format json/csv/sarif for the complete export.`,y))):u[u.length-1]===""&&u.pop(),`${u.join(`
|
|
16
|
-
`)}
|
|
17
|
-
`}function Hn(t,e){let r=e.maxFindings??10;switch(e.format){case"json":return nt(t);case"csv":return rt(t);case"sarif":return st(t);case"pretty":return at(t,e.color??!1,r);default:throw new Error(`Unsupported report format: ${e.format}`)}}import{randomUUID as Be}from"node:crypto";function ut(t,e){let r=b(t||"/")||"/",n=b(e.basePath||"/")||"/";return n==="/"?r:r===n?"/":r.startsWith(`${n}/`)?r.slice(n.length)||"/":null}function ct(t,e){return!t.host||!e?!0:t.host===e.toLowerCase()}function dt(t){try{return decodeURIComponent(t)}catch{return t}}function pt(t,e,r){let n=r==="strict-host"?e.host?20:5:0;return t.pathScore*10+n}function ge(t,e){let r={};for(let n=0;n<t.pathParams.length;n+=1){let s=t.pathParams[n],i=e[n+1];s&&i!==void 0&&(r[s]=dt(i))}return r}function lt(t,e){let r=b(e)||"/";for(let n of t){let s=n.pathRegex.exec(r);if(s)return{operation:n,pathParams:ge(n,s)}}return null}function ye(t,e,r,n){let s=e.request.method.toLowerCase(),i=t.operationsByMethod.get(s);if(!i||i.length===0)return null;if(n!==void 0)return lt(i,n);let o=null;for(let a of i)for(let c of a.servers){if(r==="strict-host"&&!ct(c,e.request.host))continue;let p=ut(e.request.path,c);if(!p)continue;let u=a.pathRegex.exec(p);if(!u)continue;let m={score:pt(a,c,r),matched:{operation:a,pathParams:ge(a,u)}};(!o||m.score>o.score)&&(o=m)}return o?.matched??null}var Se=6,ht=2e3,mt=50,ft=5,gt=1e6,yt=/(?:token|api[_-]?key|apikey|password|passwd|secret|authorization|jwt)/i,St=/(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|ssn|credit[_-]?card|card[_-]?number|cvv)/i,vt=new Set(["page","limit","offset","cursor","per_page","perpage","size","start","after","before"]),ve=4,wt=ve*2;function Rt(t){return t.length<=wt?"***":`${t.slice(0,ve)}\u2026`}function It(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Pt(t){return typeof t=="string"||typeof t=="number"}function bt(t){let e=t.toLowerCase();return e.includes("secret")||e.includes("token")||e.includes("key")?e.startsWith("is")||e.startsWith("has")||e.startsWith("can")||e.startsWith("should")||e.startsWith("enable")||e.startsWith("allow"):!1}function xt(t){if(typeof t=="number")return t===0||t===1;let e=t.trim().toLowerCase();return e==="true"||e==="false"||e==="0"||e==="1"}function kt(t){if(!l(t)&&!Array.isArray(t))return[];let e=[],r=[{value:t,path:""}],n=0;for(;r.length>0&&n<ht&&e.length<Se;){let s=r.pop();if(!s)break;if(n+=1,Array.isArray(s.value)){let i=Math.min(s.value.length,mt);for(let o=0;o<i;o+=1){let a=s.value[o];(l(a)||Array.isArray(a))&&r.push({value:a,path:`${s.path}/${o}`})}continue}if(l(s.value))for(let[i,o]of Object.entries(s.value)){let a=`${s.path}/${It(i)}`;if(St.test(i)&&Pt(o)){let c=String(o);if(bt(i)&&xt(o))continue;if(c.length>0&&(e.push(a||"/"),e.length>=Se))break}(l(o)||Array.isArray(o))&&r.push({value:o,path:a})}}return e}function At(t){for(let e of t.keys())if(vt.has(e.toLowerCase()))return!0;return!1}function I(t,e,r,n,s){return{ruleId:"owasp-api-top10",severity:n,category:"security",message:e,exchangeIndex:t.exchange.index,operationId:t.matchedOperation?.operation.operationId,specSource:t.matchedOperation?.operation.specSource,target:r,details:s}}function Ot(t){let e=[];for(let[r,n]of t.exchange.request.query.entries())if(yt.test(r)&&(e.push({key:r,valuePreview:Rt(n)}),e.length>=ft))break;return e.length===0?[]:[I(t,"Sensitive credential-like query parameters detected","request","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:"Authentication data should not be passed via query parameters because it can leak via logs, browser history, and referrers.",sensitiveQueryParams:e})]}function $t(t){let e=t.exchange.response;if(!e)return[];let r=e.headers["access-control-allow-origin"]?.trim(),n=e.headers["access-control-allow-credentials"]?.trim().toLowerCase();return r!=="*"||n!=="true"?[]:[I(t,"Insecure CORS policy: wildcard origin with credentials enabled","response","error",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Access-Control-Allow-Origin is "*" while Access-Control-Allow-Credentials is true. Browsers may expose authenticated API responses to untrusted origins.',headers:{accessControlAllowOrigin:r,accessControlAllowCredentials:n}})]}function Ct(t){let e=t.exchange.response;if(!e)return[];let r=e.headers["set-cookie"];if(!r)return[];let n=[];for(let s of ue(r)){let i=new Set(s.split(";").slice(1).map(o=>o.split("=")[0].trim().toLowerCase()));t.exchange.request.protocol==="https:"&&!i.has("secure")&&n.push(I(t,'Set-Cookie header is missing "Secure" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies over HTTPS should include "Secure" to prevent transmission over plain HTTP.',setCookiePreview:s.slice(0,200)})),i.has("httponly")||n.push(I(t,'Set-Cookie header is missing "HttpOnly" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies should include "HttpOnly" to reduce risk of token theft via client-side script access.',setCookiePreview:s.slice(0,200)})),i.has("samesite")||n.push(I(t,'Set-Cookie header is missing "SameSite" attribute',"response","info",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Set "SameSite" on session cookies to reduce CSRF risk for state-changing requests.',setCookiePreview:s.slice(0,200)}))}return n}function Et(t){let e=t.exchange.response;if(!e||e.bodyJson===void 0)return[];let r=kt(e.bodyJson);return r.length===0?[]:[I(t,"Potential sensitive data exposure in response payload","response","warning",{issueId:"API3:2019",issueTitle:"Excessive Data Exposure",summary:`Sensitive-looking fields detected in response payload: ${r.join(", ")}`,exposedPaths:r})]}function qt(t){let e=t.exchange.response;return!e||e.status>=400||t.exchange.request.method!=="GET"?[]:!e.bodyText||e.bodyText.length<gt?[]:At(t.exchange.request.query)?[]:[I(t,"Large response without pagination parameters (possible resource-consumption risk)","response","info",{issueId:"API4:2023",issueTitle:"Unrestricted Resource Consumption",summary:"A large response was returned without common pagination query parameters. Consider explicit page/limit controls for large collections.",responseBytes:e.bodyText.length})]}var M=class{id="owasp-api-top10";analyze(e){return e.matchedOperation?[...Ot(e),...$t(e),...Ct(e),...Et(e),...qt(e)]:[]}};var we=200;function Re(t){return t!==void 0&&t!==""}function Tt(t){if(!t)return{};let e={};for(let r of t.split(";")){let[n,...s]=r.trim().split("=");if(!n)continue;let i=s.join("=").trim();e[n]=i}return e}function Ft(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Mt(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function jt(t){return!t||t==="#"?"":t.startsWith("#")?t.slice(1):t}function N(t){let e=jt(t);return!e||e==="/"?[]:e.split("/").slice(1).map(r=>Ft(r))}function Ie(t,e){return`/${[...N(t),Mt(e)].join("/")}`}function Bt(t,e){let r=N(e),n=t;for(let s of r){if(Array.isArray(n)){let i=Number.parseInt(s,10);if(!Number.isInteger(i)||i<0||i>=n.length)return;n=n[i];continue}if(!l(n))return;n=n[s]}return n}function z(t){let e=t.instancePath??"",r=t.params??{};return t.keyword==="required"&&typeof r.missingProperty=="string"?Ie(e,r.missingProperty):t.keyword==="additionalProperties"&&typeof r.additionalProperty=="string"?Ie(e,r.additionalProperty):e}function Lt(t){let e=N(t);if(e.length===0)return"root";let r=[];for(let n of e)/^\d+$/.test(n)?r.push(`[${n}]`):r.length===0?r.push(n):r.push(`.${n}`);return r.join("")}function _t(t){if(t===void 0)return"[missing]";let e=JSON.stringify(t);return e?e.length>we?`${e.slice(0,we)}\u2026`:e:String(t)}function Ht(t){let e=t.params??{};if(t.keyword==="required"&&typeof e.missingProperty=="string")return`required field "${e.missingProperty}"`;if(t.keyword==="type"&&typeof e.type=="string")return`type "${e.type}"`;if(t.keyword==="additionalProperties")return"no additional undocumented properties";if(t.keyword==="format"&&typeof e.format=="string")return`format "${e.format}"`}function Vt(t,e,r){let n=t==="request"?"Request":"Response",s=e.params??{},i=Lt(r);return e.keyword==="required"&&typeof s.missingProperty=="string"?`${n} is missing required field "${i}".`:e.keyword==="additionalProperties"&&typeof s.additionalProperty=="string"?`${n} has undocumented field "${i}".`:e.keyword==="type"&&typeof s.type=="string"?`${n} field "${i}" must be ${s.type}.`:e.keyword==="enum"?`${n} field "${i}" has a value outside allowed enum values.`:e.keyword==="format"&&typeof s.format=="string"?`${n} field "${i}" does not match format "${s.format}".`:`${n} schema mismatch at "${i}": ${e.message??"validation error"}`}function be(t,e,r){let n=z(e),s=Bt(t,n);return{summary:Vt(r,e,n),keyword:e.keyword??null,path:n||"/",expected:Ht(e)??null,actual:_t(s),suggestion:null,params:e.params??{},ajvMessage:e.message??"validation error"}}function Nt(t,e,r,n){if(e==null||!t.schema)return;let s=r.validateSchema(t.schema,e,{coerce:!0});if(!s.valid)for(let i of s.errors){let o=be(e,i,"request");n.push({ruleId:"schema-consistency",severity:"error",category:"schema",message:`Invalid ${t.in} parameter "${t.name}": ${typeof o.summary=="string"?o.summary:i.message??"schema mismatch"}`,exchangeIndex:r.exchange.index,operationId:r.matchedOperation?.operation.operationId,specSource:r.matchedOperation?.operation.specSource,target:"request",schemaPath:i.schemaPath,dataPath:z(i),details:{...o,parameter:{name:t.name,in:t.in}}})}}var zt=/^([^[\]]+)\[([^[\]]+)\]$/;function xe(t){let e=t.match(zt);return e?{parameterName:e[1],property:e[2]}:void 0}function Dt(t,e){let r;for(let[n,s]of e){let i=xe(n);i?.parameterName===t&&(r??={},r[i.property]=s)}return r}function Kt(t,e,r){switch(t.in){case"path":return e.matchedOperation?.pathParams[t.name];case"query":{if(t.style==="deepObject")return Dt(t.name,e.exchange.request.query);let n=e.exchange.request.query.getAll(t.name);return n.length===0?void 0:(l(t.schema)?t.schema.type:void 0)==="array"||n.length>1?n:n[0]}case"header":return e.exchange.request.headers[t.name.toLowerCase()];case"cookie":return r[t.name];default:return}}function Ut(t,e){let r=[],n={query:new Set,header:new Set,cookie:new Set},s=new Set;for(let i of e.operation.requestParameters)i.in==="header"?n.header.add(i.name.toLowerCase()):(i.in==="query"||i.in==="cookie")&&(n[i.in].add(i.name),i.in==="query"&&i.style==="deepObject"&&s.add(i.name));for(let i of new Set(t.exchange.request.query.keys())){if(n.query.has(i))continue;let o=xe(i);o&&s.has(o.parameterName)||r.push({ruleId:"schema-consistency",severity:"warning",category:"documentation",message:`Undocumented query parameter in traffic: "${i}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"})}for(let i of Object.keys(t.exchange.request.headers))le(i,t.ignoreHeaders)||n.header.has(i.toLowerCase())||r.push({ruleId:"schema-consistency",severity:"info",category:"documentation",message:`Undocumented header in traffic: "${i}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"});return r}function Gt(t){let e=t.exchange.response;return e!==void 0&&e.status>=400&&e.status<500}function Wt(t,e){let r=t.exchange.response;if(!r)return;let n=String(r.status),s=`${Math.floor(r.status/100)}XX`,i=e.operation.responseBodyContent[n]??e.operation.responseBodyContent[s]??e.operation.responseBodyContent[s.toLowerCase()]??e.operation.responseBodyContent.default;if(i)return V(i,r.contentType)}function Pe(t,e,r,n){let s=r.validateSchema(t,e,{target:n});return s.valid?[]:s.errors.map(i=>{let o=be(e,i,n);return{ruleId:"schema-consistency",severity:"error",category:"schema",message:typeof o.summary=="string"?o.summary:`Schema mismatch (${n}): ${i.message??"validation error"}`,exchangeIndex:r.exchange.index,operationId:r.matchedOperation?.operation.operationId,specSource:r.matchedOperation?.operation.specSource,target:n,schemaPath:i.schemaPath,dataPath:z(i),details:o}})}var j=class{id="schema-consistency";analyze(e){let r=e.matchedOperation;if(!r)return[];let n=[],s=Tt(e.exchange.request.headers.cookie);if(n.push(...Ut(e,r)),!Gt(e)){for(let p of r.operation.requestParameters){if(e.ignoreCookies&&p.in==="cookie")continue;let u=Kt(p,e,s);if(p.required&&u==null){n.push({ruleId:this.id,severity:"error",category:"documentation",message:`Missing required ${p.in} parameter: "${p.name}"`,exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"});continue}Nt(p,u,e,n)}let o=e.exchange.request.contentType,a=V(r.operation.requestBodyContent,o),c=Re(e.exchange.request.bodyText);r.operation.requestBodyRequired&&!c&&n.push({ruleId:this.id,severity:"error",category:"documentation",message:"Missing required request body",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"}),a&&c&&H(o)&&(e.exchange.request.bodyJson===void 0?n.push({ruleId:this.id,severity:"error",category:"schema",message:"Request body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"}):n.push(...Pe(a,e.exchange.request.bodyJson,e,"request")))}let i=Wt(e,r);if(i&&e.exchange.response&&Re(e.exchange.response.bodyText)){let o=e.exchange.response.contentType;H(o)&&(e.exchange.response.bodyJson===void 0?n.push({ruleId:this.id,severity:"error",category:"schema",message:"Response body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"response"}):n.push(...Pe(i,e.exchange.response.bodyJson,e,"response")))}return n}};function D(t){if(!t)return null;let[e]=t.trim().split(/\s+/,1);return e?e.toLowerCase():null}function Ae(t){return!!t.exchange.request.headers.authorization}function Jt(t,e){return t?t.split(";").map(r=>r.trim()).some(r=>r.startsWith(`${e}=`)):!1}function Yt(t,e){let r=t.matchedOperation?.operation;if(!r)return{schemeName:e,schemeType:"unknown",satisfied:!0,reason:"No matched OpenAPI operation."};let n=r.securitySchemes[e];if(!n)return{schemeName:e,schemeType:"missing",satisfied:!1,reason:"Security scheme is referenced but not defined in components.securitySchemes."};let s=String(n.type??"unknown");if(n.type==="apiKey"){let i=String(n.name??""),o=String(n.in??"header");if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:'apiKey scheme is missing the "name" field in the OpenAPI spec.'};if(o==="header"){let a=!!t.exchange.request.headers[i.toLowerCase()];return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey header "${i}".`:`Missing required apiKey header "${i}".`}}if(o==="query"){let a=t.exchange.request.query.has(i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey query parameter "${i}".`:`Missing required apiKey query parameter "${i}".`}}if(o==="cookie"){if(t.ignoreCookies)return{schemeName:e,schemeType:s,satisfied:!0,skipped:!0,reason:`Skipped apiKey cookie "${i}" validation because --ignore-cookies is enabled.`};let a=Jt(t.exchange.request.headers.cookie,i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey cookie "${i}".`:`Missing required apiKey cookie "${i}".`}}return{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported apiKey location "${o}" in OpenAPI security scheme.`}}if(n.type==="http"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header."};let o=String(n.scheme??"").toLowerCase(),a=D(i);if(!o)return{schemeName:e,schemeType:s,satisfied:!0,reason:"Authorization header is present and no specific HTTP auth scheme is documented."};if(!a)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Authorization header is malformed and does not include an auth scheme."};let c=a===o;return{schemeName:e,schemeType:s,satisfied:c,reason:c?`Authorization uses expected "${o}" scheme.`:`Authorization uses "${a}" but "${o}" is required.`}}if(n.type==="oauth2"||n.type==="openIdConnect"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header for OAuth2/OpenID Connect scheme."};let o=D(i),a=o==="bearer";return{schemeName:e,schemeType:s,satisfied:a,reason:a?"Authorization uses bearer token as expected for OAuth2/OpenID Connect.":`Authorization scheme "${o??"unknown"}" does not satisfy OAuth2/OpenID Connect (expected bearer).`}}return n.type==="mutualTLS"?{schemeName:e,schemeType:s,satisfied:!0,reason:"mutualTLS cannot be validated from HTTP traffic logs alone."}:{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported security scheme type "${s}".`}}function Qt(t){let e=t.matchedOperation?.operation.security;if(!e)return{satisfied:!0,requirements:[]};if(e.length===0)return{satisfied:!0,requirements:[]};let r=e.map((n,s)=>{let i=Object.keys(n);if(i.length===0)return{requirementIndex:s,satisfied:!0,schemeResults:[]};let o=i.map(a=>Yt(t,a));return{requirementIndex:s,satisfied:o.every(a=>a.satisfied),schemeResults:o}});return{satisfied:r.some(n=>n.satisfied),requirements:r}}function Xt(t){let e=[];for(let r of t.requirements)for(let n of r.schemeResults)n.satisfied||e.push({requirement:r.requirementIndex+1,schemeName:n.schemeName,reason:n.reason});return e}function ke(t){let e=[];for(let r of t.requirements)for(let n of r.schemeResults)n.skipped&&e.push({requirement:r.requirementIndex+1,schemeName:n.schemeName,reason:n.reason});return e}function Zt(t){if(t.length===0)return"All documented security requirements are satisfied.";let e=new Map;for(let n of t){let s=e.get(n.requirement);s?s.push(n):e.set(n.requirement,[n])}let r=Array.from(e.entries()).sort((n,s)=>n[0]-s[0]).map(([n,s])=>{let i=s.map(a=>a.schemeName).join(" + "),o=s.map(a=>a.reason).join(" ");return`Option ${n} (${i}): ${o}`});return r.length===1?`Authentication check failed. ${r[0]}`:`None of the documented authentication options matched. Any one of these options would satisfy the OpenAPI security requirements: ${r.join(" | ")}`}function en(t){return Array.from(t.exchange.request.query.keys()).filter(e=>{let r=e.toLowerCase();return r.includes("token")||r.includes("apikey")||r.includes("api_key")||r.includes("access_key")})}var tn=/^(?:(?:.+\.)?localhost|127(?:\.\d{1,3}){3}|::1)$/i;function nn(t){let e;try{e=new URL(t.url).hostname}catch{e=t.host?.replace(/:\d+$/,"")}return e?tn.test(e.replace(/^\[|\]$/g,"")):!1}function rn(t){if(t.exchange.request.protocol!=="http:"||!t.exchange.request.protocolKnown||nn(t.exchange.request))return{flag:!1,hasAuthHeader:!1,sensitiveQueryKeys:[]};let e=Ae(t),r=en(t);return{flag:e||r.length>0,hasAuthHeader:e,sensitiveQueryKeys:r}}var B=class{id="security-baseline";analyze(e){if(!e.matchedOperation)return[];let r=[],n=Qt(e);if(n.satisfied){let i=ke(n);i.length>0&&r.push({ruleId:this.id,severity:"info",category:"security",message:"Some documented cookie-based security checks were skipped",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:i.map(o=>`Skipped option ${o.requirement} (${o.schemeName}): ${o.reason}`).join(" "),skippedChecks:i}})}else{let i=Xt(n);r.push({ruleId:this.id,severity:"error",category:"security",message:"Request does not satisfy documented OpenAPI security requirements",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:Zt(i),failedChecks:i,skippedChecks:ke(n),authorizationScheme:D(e.exchange.request.headers.authorization),hasAuthorizationHeader:Ae(e)}})}let s=rn(e);return s.flag&&r.push({ruleId:this.id,severity:"warning",category:"security",message:"Potential credential exposure over insecure HTTP transport",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{protocol:e.exchange.request.protocol,hasAuthorizationHeader:s.hasAuthHeader,sensitiveQueryKeys:s.sensitiveQueryKeys}}),r}};var L=class{id="undocumented-endpoint";analyze(e){if(e.matchedOperation)return[];let{method:r,path:n,host:s}=e.exchange.request,o=e.matchMode==="strict-host"&&!e.hostCompatibleWithSpecServers?`Undocumented server: ${r} ${n} was sent to "${s}", which does not match any server in the description`:`Undocumented endpoint: ${r} ${n}`;return[{ruleId:this.id,severity:"error",category:"documentation",message:o,exchangeIndex:e.exchange.index,target:"request"}]}};var K={"undocumented-endpoint":()=>new L,"schema-consistency":()=>new j,"security-baseline":()=>new B,"owasp-api-top10":()=>new M},sn=Object.keys(K),on=["undocumented-endpoint","schema-consistency","security-baseline"];function Oe(t){return!t||t.length===0?on.map(e=>K[e]()):[...new Set(t)].map(e=>{let r=K[e];if(!r)throw new Error(`Unknown rule id: "${e}". Available rules: ${sn.join(", ")}`);return r()})}var Ee=J(We(),1);var qe=J(Je(),1),$e=Ee.default,Ce=qe.default;function an(t,e){return l(t)?e==="request"?t.readOnly===!0:t.writeOnly===!0:!1}function Te(t,e,r,n=new WeakSet){if(!l(t)||n.has(t))return!1;n.add(t);let s=t.properties;return l(s)&&an(s[e],r)?!0:[t.allOf,t.oneOf,t.anyOf].some(i=>Array.isArray(i)&&i.some(o=>Te(o,e,r,n)))}var un=new Set(["items","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else"]),cn=new Set(["allOf","anyOf","oneOf","prefixItems"]),dn=new Set(["properties","patternProperties","dependentSchemas","$defs","definitions"]);function Fe(t,e,r=new WeakSet){if(!l(t))return t;if(r.has(t))return!0;r.add(t);let n=i=>Fe(i,e,r),s={};for(let[i,o]of Object.entries(t))un.has(i)?s[i]=Array.isArray(o)?o.map(n):n(o):cn.has(i)&&Array.isArray(o)?s[i]=o.map(n):dn.has(i)&&l(o)?s[i]=Object.fromEntries(Object.entries(o).map(([a,c])=>[a,n(c)])):s[i]=o;return Array.isArray(t.required)&&(s.required=t.required.filter(i=>typeof i!="string"||!Te(t,i,e))),r.delete(t),s}var E=class{ajv;fallbackAjv;objectSchemaCaches={none:new WeakMap,request:new WeakMap,response:new WeakMap};scalarSchemaCache=new Map;constructor(e){let r={strict:!1,allErrors:!0,allowUnionTypes:!0,discriminator:!0,coerceTypes:e?.coerceTypes?"array":!1,validateFormats:!0,verbose:!0,formats:{enum:!0}};this.ajv=new $e(r),this.fallbackAjv=new $e({...r,discriminator:!1}),Ce(this.ajv),Ce(this.fallbackAjv)}validate(e,r,n){if(e===void 0)return{valid:!0,errors:[]};let s;try{s=this.getOrCompileValidator(e,n)}catch(a){return{valid:!1,errors:[{message:`Schema compilation failed: ${a.message}`}]}}let i=!!s(r),o=s.errors??[];return{valid:i,errors:o}}getOrCompileValidator(e,r){if(l(e)){let o=this.objectSchemaCaches[r??"none"],a=o.get(e);if(a)return a;let c=r?Fe(e,r):e,p=this.compileSchema(c);return o.set(e,p),p}let n=`${r??"none"}:${JSON.stringify(e)}`,s=this.scalarSchemaCache.get(n);if(s)return s;let i=this.compileSchema(e);return this.scalarSchemaCache.set(n,i),i}compileSchema(e){try{return this.ajv.compile(e)}catch{return this.fallbackAjv.compile(e)}}};var pn=10,Me={info:0,warning:1,error:2};function ln(){return{totalExchanges:0,documentedExchanges:0,undocumentedExchanges:0,skippedExchanges:0,hostCompatibleExchanges:0,findingsBySeverity:{info:0,warning:0,error:0},findingsByRule:{}}}function hn(t,e){t.findingsBySeverity[e.severity]+=1,t.findingsByRule[e.ruleId]=(t.findingsByRule[e.ruleId]??0)+1}function mn(t,e){return{...t,id:Be(),method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function fn(t,e){return{exchangeIndex:t.exchangeIndex,ruleId:t.ruleId,severity:t.severity,category:t.category,message:t.message,occurrences:1,operationId:t.operationId,specSource:t.specSource,target:t.target,schemaPath:t.schemaPath,dataPath:t.dataPath,details:t.details,method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function gn(t,e){if(!e)return;t.operationId||(t.operationId=e.operation.operationId),t.specSource||(t.specSource=e.operation.specSource);let r=t.details??{};if(!l(r)){t.details={operationPathTemplate:e.operation.pathTemplate};return}typeof r.operationPathTemplate!="string"&&(r.operationPathTemplate=e.operation.pathTemplate),t.details=r}function yn(t){let e=new Set,r=!1;for(let n of t.operationsByMethod.values())for(let s of n)for(let i of s.servers)i.host?e.add(i.host):r=!0;return{specServerHosts:e,hasHostlessSpecServer:r}}async function Sn(t,e){let r=[];for(let n of t)try{let s=await n.analyze(e);s.length>0&&r.push(...s)}catch(s){w.warn(`Rule "${n.id}" failed to execute: ${s.message}
|
|
18
|
-
`)}return r}var je=class t{startedAt=Date.now();runId=Be();previewLimit;rules;schemaValidator=new E;coercingSchemaValidator=new E({coerceTypes:!0});options;counters=ln();findings=[];previewFindings=[];problemGroupsByRule={};problemKeyStats=new Map;totalProblemGroups=0;server;ignoreHeaders;minSeverityRank;specServerHosts;hasHostlessSpecServer;constructor(e,r){this.options=e,this.rules=r,this.server=he(e.server),this.ignoreHeaders=e.ignoreHeaders?pe(e.ignoreHeaders):void 0;let{specServerHosts:n,hasHostlessSpecServer:s}=yn(e.openApiIndex);this.specServerHosts=n,this.hasHostlessSpecServer=s,this.minSeverityRank=Me[e.minSeverity??"info"],this.previewLimit=e.previewFindingsLimit&&e.previewFindingsLimit>0?e.previewFindingsLimit:pn}static create(e){if(e.openApiIndex.loadedOperations===0)throw new Error("No OpenAPI operations available to validate traffic against.");return new t(e,Oe(e.activeRules))}async process(e){this.counters.totalExchanges+=1;let r;if(this.server!==void 0&&(r=me(e.request,this.server),r===void 0))return this.counters.skippedExchanges+=1,[];let n=this.isHostCompatible(e.request.host);n&&(this.counters.hostCompatibleExchanges+=1);let s=ye(this.options.openApiIndex,e,this.options.matchMode,r);s?this.counters.documentedExchanges+=1:this.counters.undocumentedExchanges+=1;let i=await Sn(this.rules,{exchange:e,matchedOperation:s,matchMode:this.options.matchMode,hostCompatibleWithSpecServers:r!==void 0||n,ignoreCookies:this.options.ignoreCookies??!1,ignoreHeaders:this.ignoreHeaders,validateSchema:(a,c,p)=>p?.coerce?this.coercingSchemaValidator.validate(a,c,p?.target):this.schemaValidator.validate(a,c,p?.target)}),o=[];for(let a of i){if(Me[a.severity]<this.minSeverityRank)continue;gn(a,s);let c=mn(a,e);this.findings.push(c),o.push(c),hn(this.counters,a);let p=T({ruleId:a.ruleId,severity:a.severity,message:a.message,operationId:a.operationId,path:e.request.path,target:a.target,schemaPath:a.schemaPath}),u=this.problemKeyStats.get(p);if(u){u.occurrences+=1,u.previewIndex!==null&&(this.previewFindings[u.previewIndex].occurrences=u.occurrences);continue}if(this.totalProblemGroups+=1,this.problemGroupsByRule[a.ruleId]=(this.problemGroupsByRule[a.ruleId]??0)+1,this.previewFindings.length<this.previewLimit){let m=this.previewFindings.length;this.previewFindings.push(fn(a,e)),this.problemKeyStats.set(p,{occurrences:1,previewIndex:m});continue}this.problemKeyStats.set(p,{occurrences:1,previewIndex:null})}return o}isHostCompatible(e){return!e||this.hasHostlessSpecServer||this.specServerHosts.has(e.toLowerCase())}finalize(){let e={runId:this.runId,totalExchanges:this.counters.totalExchanges,documentedExchanges:this.counters.documentedExchanges,undocumentedExchanges:this.counters.undocumentedExchanges,skippedExchanges:this.counters.skippedExchanges,hostCompatibleExchanges:this.counters.hostCompatibleExchanges,findingsBySeverity:this.counters.findingsBySeverity,findingsByRule:this.counters.findingsByRule,problemGroupsByRule:this.problemGroupsByRule,totalProblemGroups:this.totalProblemGroups,durationMs:Date.now()-this.startedAt,previewFindings:this.previewFindings,previewLimit:this.previewLimit,previewTruncated:this.totalProblemGroups>this.previewFindings.length};return{runId:this.runId,summary:e,findings:this.findings}}};import{stat as vn}from"node:fs/promises";function _(t,e){let r=t.replace(/\{([^}]+)\}/g,(i,o)=>{let a=e?.[o];return a?.default!==void 0?String(a.default):Array.isArray(a?.enum)&&a.enum.length>0?String(a.enum[0]):""}),n=ce(r),s=!!(n.host&&!ae(n.host));return{rawUrl:t,protocol:s?n.protocol:void 0,host:s?n.host.toLowerCase():void 0,basePath:b(n.pathname||"/")}}function Le(t){return t?t.startsWith("/")?t:`/${t}`:"/"}var wn=["get","put","post","delete","patch","head","options","trace"],Rn=new Set(["query","header","path","cookie"]);function In(t){return wn.includes(t)}function Pn(t){return Rn.has(t)}function _e(t){if(!Array.isArray(t))return[];let e=[];for(let r of t){if(!l(r))continue;let n=r.in;typeof n!="string"||!Pn(n)||e.push({name:String(r.name??""),in:n,required:!!r.required||n==="path",style:typeof r.style=="string"?r.style:void 0,schema:r.schema})}return e}function He(t){let e=t.in==="header";return`${t.in}:${e?t.name.toLowerCase():t.name}`}function bn(t,e){let r=new Map;for(let n of t)r.set(He(n),n);for(let n of e)r.set(He(n),n);return Array.from(r.values())}function Ne(t){let e={};if(!l(t))return e;for(let[r,n]of Object.entries(t))l(n)&&"schema"in n&&(e[r.toLowerCase()]=n.schema);return e}function xn(t){return l(t)?Ne(t.content):{}}function kn(t){if(!l(t))return{};let e={};for(let[r,n]of Object.entries(t))!l(n)||!("content"in n)||(e[r]=Ne(n.content));return e}function An(t,e,r){let n=t??e??r;return!Array.isArray(n)||n.length===0?[_("/")]:n.map(s=>{if(!l(s))return _("/");let i=typeof s.url=="string"?s.url:"/",o=l(s.variables)?s.variables:void 0;return _(i,o)})}function On(t,e,r){return r||`${t.toUpperCase()} ${e}`}function $n(t){try{let e=ne(t.parsed);return te(e)==="oas3"?e:null}catch{return null}}function Ve(t){return Array.isArray(t)?t:void 0}function Cn(t,e){let r,n,s={},i="/",o=[],a;return{Root:{enter(c){r=c.servers,n=c.security;let p=l(c.components)?c.components.securitySchemes:void 0;s=l(p)?p:{}}},Paths:{PathItem:{enter(c,p){i=Le(String(p.key)),o=_e(c.parameters),a=c.servers},Operation:{enter(c,p){let u=String(p.key);if(!In(u))return;let m=bn(o,_e(c.parameters)),x=de(i),q=An(c.servers,a,r),P=c.requestBody,h={operationId:On(u,i,typeof c.operationId=="string"?c.operationId:void 0),method:u,pathTemplate:i,pathRegex:x.regex,pathParams:x.params,pathScore:x.score,servers:q,requestParameters:m,requestBodyContent:xn(P),requestBodyRequired:l(P)&&!!P.required,responseBodyContent:kn(c.responses),security:Ve(c.security)??Ve(n),securitySchemes:s,specSource:t},f=e.get(u)??[];f.push(h),e.set(u,f)}}}}}}function En(t,e,r,n,s){let i=Y(r.extendTypes(Q(e),e),r),o=new Map,a={problems:[],specVersion:e,config:r,visitorsData:{}},c=re([{severity:"warn",ruleId:"drift-index",visitor:Cn(n,s)}],i);se({document:t,rootType:i.Root,normalizedVisitors:c,resolvedRefMap:o,ctx:a})}function qn(t){return`${t.host??""}|${t.basePath}`}function Tn(t){for(let e of t.values()){let r=new Map;for(let n of e){let s=r.get(n.pathRegex.source)??[];s.push(n),r.set(n.pathRegex.source,s)}for(let n of r.values()){let s=new Map;for(let i of n)for(let o of i.servers){let a=qn(o),c=s.get(a)??new Set;c.add(i.specSource),s.set(a,c)}for(let i of s.values())if(i.size>1){let[o]=n;w.warn(`"${o.method.toUpperCase()} ${o.pathTemplate}" is documented for the same server in multiple descriptions (${Array.from(i).join(", ")}). Matching traffic is validated against only one of them.
|
|
19
|
-
`);break}}}}function Fn(t,e){for(let n of t.values())n.sort((s,i)=>i.pathScore-s.pathScore);let r=Array.from(t.values()).reduce((n,s)=>n+s.length,0);return{operationsByMethod:t,loadedSpecs:e,loadedOperations:r}}async function Mn(t){return(await vn(t)).isDirectory()?{specFiles:await oe(t),fromDirectory:!0}:{specFiles:[t],fromDirectory:!1}}async function Rr(t,e){let{specFiles:r,fromDirectory:n}=await Mn(t),s=new Map,i=new X(e.resolve),o=0;for(let a of r){let c=await i.resolveDocument(null,a,!0);if(c instanceof Error){w.warn(`Failed to load OpenAPI description ${a}: ${c.message}
|
|
20
|
-
`);continue}let p=$n(c);if(!p){n||w.warn(`Skipping ${a}: not an OpenAPI 3.x description.
|
|
21
|
-
`);continue}let u;try{let{bundle:m}=await ie({config:e,doc:c,externalRefResolver:i,dereference:!0});u=m}catch(m){w.warn(`Failed to bundle OpenAPI description ${a}: ${m.message}
|
|
22
|
-
`);continue}o+=1,En(u,p,e,a,s)}return o>1&&Tn(s),Fn(s,o)}function Pr(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}export{Hn as a,je as b,Rr as c,Pr as d};
|
package/lib/chunks/K2ENYHHD.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v}from"./OM4VGI2Q.js";import"./LRUXN6H5.js";import"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";export{j as InvalidReuniteUrlError,f as REUNITE_URLS,l as RedoclyOAuthClient,k as RedoclyOAuthDeviceFlow,c as ReuniteApi,b as ReuniteApiClient,a as ReuniteApiError,n as collectFilesToPush,t as evaluatePluginsFromCode,q as fetchRemoteScorecardAndPlugins,e as getApiKeys,g as getDomain,d as getMostUrgentSunsetWarning,o as getPushStatus,h as getReuniteUrl,s as getTarget,u as isAllowedScorecardProjectUrl,i as isValidReuniteUrl,m as pushFiles,r as resolveConfigForTarget,v as validateScorecard,p as waitForDeployment};
|
package/lib/chunks/LJPUHAWE.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as x,c as P,d as c}from"./YUNIBLZR.js";import"./YEACSN2C.js";import{e as y,g as b,m as w,n as $}from"./OM4VGI2Q.js";import"./LRUXN6H5.js";import{h as l}from"./3I7XLHPY.js";import{P as g,X as n,l as p}from"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";async function C({argv:t,config:o,version:h}){let f=performance.now(),A=Date.now(),{organization:s,project:m,"mount-path":F,verbose:I}=t,d=t.domain||b(),e,r,u=[];try{let i=y();if(e=$(t.files,(a,S)=>{n.warn(`File ${a} is overwritten by ${S}
|
|
8
|
-
`)}),!e.length)return l("push",f,"No files to upload");r=(await w({domain:d,apiKey:i,organization:s,project:m,mountPath:F,files:e,defaultBranch:t["default-branch"],commit:{message:t.message,branchName:t.branch,sha:t["commit-sha"],url:t["commit-url"],createdAt:t["created-at"],namespace:t.namespace,repository:t.repository,author:T(t.author)},version:h,replace:t.replace,onUploadStart:a=>{n.info(`Uploading to ${a.mountPath} ${e.length} ${p("file",e.length)}:
|
|
9
|
-
`)},onSunsetWarning:a=>u.push(a)})).pushId}catch(i){c("push",u),P("\u2717 File upload failed.",i)}for(let i of e)n.info(g(`\u2713 ${i.name}
|
|
10
|
-
`));return n.info(`
|
|
11
|
-
`),n.info(`Push ID: ${r}
|
|
12
|
-
`),c("push",u),t["wait-for-deployment"]&&(n.info(`
|
|
13
|
-
`),await x({argv:{organization:s,project:m,pushId:r,wait:!0,domain:d,"max-execution-time":t["max-execution-time"],"start-time":A,"continue-on-deploy-failures":t["continue-on-deploy-failures"]},config:o,version:h})),I&&l("push",f,`${p("file",e.length)} uploaded to organization ${s}, project ${m}. Push ID: ${r}.`),{pushId:r}}function T(t){let o=t.match(/^(?<name>.+)\s<(?<email>[^<>]+)>$/);if(!o?.groups)throw new Error('Invalid author format. Use "Author Name <author@email.com>"');return{name:o.groups.name.trim(),email:o.groups.email.trim()}}export{C as handlePush};
|
package/lib/chunks/OM4VGI2Q.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as oe}from"./LRUXN6H5.js";import{ca as d,ha as W,j,l as U,o as B,oa as b,p as M}from"./M4YE5ALG.js";import{e as se}from"./RFWIIJFG.js";var S=se(oe(),1);function H(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function q(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 Y=async(o,{timeout:t,...e}={})=>{let r=H(),s=r&&!q(o),n,i=t?{connect:{timeout:t}}:{};return s?n=new S.ProxyAgent({uri:r,...i}):t&&(n=new S.Agent(i)),await fetch(o,{signal:t?AbortSignal.timeout(t):void 0,...e,dispatcher:n})};var ie=/^[\x21-\x7e]+( [\x21-\x7e]+)*$/;function V(){let o=process.env.REDOCLY_ENVIRONMENT?.trim();return o&&ie.test(o)?o:void 0}var u=class extends Error{status;constructor(t,e){super(t),this.status=e}},v=class{command;version;sunsetWarnings=[];constructor(t,e="2.0"){this.command=t,this.version=e}async request(t,e){let r=V(),s={...e.headers,"user-agent":`redocly-cli/${this.version} ${this.command}${r?` ${r}`:""}`};try{let n=await Y(t,{...e,headers:s});return this.collectSunsetWarning(n),n}catch(n){let i="Failed to fetch.";throw n.cause&&(i+=` Caused by ${n.cause.message||n.cause.name}.`),(n.code||n.cause?.code)&&(i+=` Code: ${n.code||n.cause?.code}`),new Error(i)}}collectSunsetWarning(t){let e=this.getSunsetDate(t);if(!e)return;let r=new Date(e);e>Date.now()?this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!1}):this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!0})}getSunsetDate(t){let{headers:e}=t;if(!e)return;let r=e.get("sunset")||e.get("Sunset");if(r)return Date.parse(r)}},N=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)}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 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 globalThis.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 ae(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:{Authorization:`Bearer ${this.apiKey}`},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",Authorization:`Bearer ${this.apiKey}`}});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)}}},p=class{apiClient;remotes;constructor({domain:t,apiKey:e,command:r,version:s}){this.apiClient=new v(r,s),this.remotes=new N(this.apiClient,t,e)}getSunsetWarning(){return z(this.apiClient.sunsetWarnings)}};function z(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 ae(o){let t=[];for await(let e of o)t.push(e);return Buffer.concat(t)}function ce(){if(process.env.REDOCLY_AUTHORIZATION)return process.env.REDOCLY_AUTHORIZATION;throw new Error("No api key provided, please use environment variable REDOCLY_AUTHORIZATION.")}var x={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function ue(){return process.env.REDOCLY_DOMAIN||x.us}var K=le((o,t)=>{try{let e=t||o?.resolvedConfig.residency;return he(e)?x[e]:e?new URL(e).origin:o?.resolvedConfig.scorecard?.fromProjectUrl?new URL(o.resolvedConfig.scorecard.fromProjectUrl).origin:x.us}catch{throw new C}});function I(o){try{K(void 0,o)}catch{return!1}return!0}function le(o){return(...t)=>{let e=o(...t);if(!e.startsWith("https://"))throw new C;return e}}var C=class extends Error{constructor(){super("Invalid Reunite URL")}};function he(o){return typeof o=="string"&&o in x}import{Buffer as D}from"node:buffer";import _ from"node:crypto";import{mkdirSync as de,existsSync as X,writeFileSync as pe,readFileSync as me,rmSync as fe}from"node:fs";import{homedir as ge}from"node:os";import J from"node:path";import*as G from"node:child_process";var m=class{baseUrl;apiClient;clientName="redocly-cli";constructor(t,e){this.baseUrl=t,this.apiClient=new v("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]];G.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 we="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",Z="aes-256-cbc",O=class{version;credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(t){this.version=t;let e=ge();this.credentialsFolderPath=J.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=J.join(this.credentialsFolderPath,this.credentialsFileName),this.key=_.createHash("sha256").update(`${this.credentialsFolderPath}${we}`).digest(),this.iv=_.createHash("md5").update(this.credentialsFolderPath).digest(),de(this.credentialsFolderPath,{recursive:!0})}async login(t,e){let s=await new m(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 m(t,this.version).verifyApiKey(e):!!await this.getAccessToken(t)}getAccessToken=async t=>{let e=new m(t,this.version),r=await this.readCredentials();if(!r||!I(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);pe(this.credentialsFilePath,e,"utf8")}catch(e){throw new Error(`Failed to save credentials: ${e.message}`)}}async readCredentials(){if(!X(this.credentialsFilePath))return null;try{let t=me(this.credentialsFilePath,"utf8");return this.decryptCredentials(t)}catch{return null}}async removeCredentials(){X(this.credentialsFilePath)&&fe(this.credentialsFilePath)}encryptCredentials(t){let e=_.createCipheriv(Z,this.key,this.iv);return D.concat([e.update(JSON.stringify(t),"utf8"),e.final()]).toString("hex")}decryptCredentials(t){let e=_.createDecipheriv(Z,this.key,this.iv),r=D.concat([e.update(D.from(t,"hex")),e.final()]);return JSON.parse(r.toString("utf8"))}};import*as f from"node:fs";import*as h from"node:path";async function ye({domain:o,apiKey:t,organization:e,project:r,mountPath:s,files:n,defaultBranch:i,commit:a,version:c,replace:P,onUploadStart:E,onSunsetWarning:g}){let w=new p({domain:o,apiKey:t,command:"push",version:c});try{let y=await w.remotes.getDefaultBranch(e,r),T=await w.remotes.upsert(e,r,{mountBranchName:y,mountPath:s});E?.(T);let{id:l}=await w.remotes.push(e,r,{remoteId:T.id,commit:a,isMainBranch:i===a.branchName,replace:P},n.map(F=>({path:B(F.name),stream:f.createReadStream(F.path)})));return{pushId:l}}finally{let y=w.getSunsetWarning();y&&g?.(y)}}function ve(o,t){let e={};for(let s of o)if(f.statSync(s).isDirectory()){let n=s;Q(n,[]).forEach(a=>r(a,n))}else r(s,h.dirname(s));function r(s,n){let i=h.relative(n,s);e[i]&&t?.(e[i],s),e[i]=s}return Object.entries(e).map(([s,n])=>({name:s,path:h.resolve(n)}))}function Q(o,t){let e=f.readdirSync(o);for(let r of e){let s=h.join(o,r);f.statSync(s).isDirectory()?t=Q(s,t):t.push(s)}return t}async function ee({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 j(n),i()}return i()}var Te=1200,xe=5e3,Ce=["pending","running"];async function Pe(o){let t=te(o);try{return await ne(t,o)}finally{re(t,o)}}async function Ee({buildType:o,maxExecutionTime:t=Te,retryIntervalMs:e=xe,startTime:r=Date.now(),onRetry:s,...n}){let i=te(n);try{return await ee({operation:()=>ne(i,n),condition:a=>!Ce.includes(a.status[o].deploy.status),onConditionNotMet:s,startTime:r,retryTimeoutMs:t*1e3,retryIntervalMs:e})}finally{re(i,n)}}function te({domain:o,apiKey:t,version:e}){return new p({domain:o,apiKey:t,command:"push-status",version:e})}function re(o,{onSunsetWarning:t}){let e=o.getSunsetWarning();e&&t?.(e)}function ne(o,{organization:t,project:e,pushId:r}){return o.remotes.getPush({organizationId:t,projectId:e,pushId:r})}async function Re({projectUrl:o,auth:t,isApiKey:e=!1,onDebug:r}){let s=Se(o);if(!s)throw new d(`Invalid project URL format: ${o}`);try{let n=await _e({...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 Fe(a,r):void 0;return{scorecard:i,plugins:c,pluginsUrl:a}}catch(n){throw new d(n instanceof Error?n.message:String(n))}}function Se(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 _e({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:$e(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 Fe(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 $e(o,t){return t?{Authorization:`Bearer ${o}`}:{Cookie:`accessToken=${o}`}}async function k(o,t,e=[],r=[],s){let n={};for(let i of e){let a={[i.name]:{root:o,rules:t}},c=await W({apis:a,...i,plugins:r},{configPath:s});n[i.name]=c.forAlias(i.name)}return n}function L(o,t){if(o){for(let e of o)if(Object.entries(e.where?.metadata||{}).every(([s,n])=>Ue(s,n,t)))return e}}function Ue(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 M(t).test(e[o])}catch{throw new d(`Invalid regex in scorecard target "${o}": ${t}`)}}return e[o]===t}import{pathToFileURL as Ae}from"node:url";async function Ne(o,t){if(!o)return[];let e=Ae(t??process.cwd()).href+"/",r=o.replaceAll("__redocly_dirname",`"${e}"`);return(await import(`data:text/javascript;base64,${btoa(r)}`)).default.map(i=>i())}var Ie=".redocly.com";function De(o){try{return new URL(o).hostname.toLowerCase().endsWith(Ie)}catch{return!1}}async function Oe({apiPath:o,document:t,externalRefResolver:e,scorecardConfig:r,configPath:s,plugins:n=[],targetLevel:i,metadata:a={},onDebug:c}){let P=[],E=new Map,g=r.levels||[];if(i&&!g.some(l=>l.name===i))throw new d(`Target level "${i}" not found in the scorecard configuration levels.
|
|
8
|
-
`);let w=L(r.targets,a)?.rules,y=await k(o,w,g,n,s||"");for(let l of g){c?.(`
|
|
9
|
-
Validating level: "${l.name}"`),n.length>0&&c?.(`Using ${n.length} ${U("plugin",n.length)} for this level.`),c?.("Linting document against level rules...");let R=(await b({document:t,externalRefResolver:e,config:y[l.name]})).filter(({ignored:$})=>!$).map($=>({...$,scorecardLevel:l.name}));c?.(`Found ${R.length} ${U("problem",R.length)} for level "${l.name}".`),E.set(l.name,R),P.push(...R)}let T=ke(E,g,i);return{problems:P,achievedLevel:T,targetLevelAchieved:i?T===i:!0}}function ke(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,v as b,p as c,z as d,ce as e,x as f,ue as g,K as h,I as i,C as j,m as k,O as l,ye as m,ve as n,Pe as o,Ee as p,Re as q,k as r,L as s,Ne as t,De as u,Oe as v};
|
package/lib/chunks/VYHYEZI5.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a,b,c,d}from"./YUNIBLZR.js";import"./YEACSN2C.js";import"./OM4VGI2Q.js";import"./LRUXN6H5.js";import"./3I7XLHPY.js";import"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";export{a as DeploymentError,b as handlePushStatus,c as handleReuniteError,d as printSunsetWarning};
|
package/lib/chunks/YFI3NLJF.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{d as xe,h as Pe}from"./3I7XLHPY.js";import{I as le,J as he,M as b,O as fe,P as de,Q as j,S as ye,T as U,U as A,X as k,Y as Se,Z as ge,_ as Q,aa as K,c as L,ca as Ce,f as ie,fa as be,q as ae,r as pe,s as ce,u as me,v as ue}from"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{performance as mt}from"perf_hooks";var D={thresholds:{maxParamsGood:5,maxDepthGood:4,maxPolymorphismGood:2,maxDependencyDepthGood:3,maxAmbiguousGood:0,maxOperationsForDiscoverability:1e3},weights:{parameterSimplicity:.1,schemaSimplicity:.1,documentationQuality:.18,constraintClarity:.12,exampleCoverage:.18,errorClarity:.12,dependencyClarity:.1,identifierClarity:.05,polymorphismClarity:.05,anyOfPenaltyMultiplier:2,discoverabilityWeight:.1},hotspotLimit:10},Oe=new Set(["id","name","type","value","data","key","status","state","code","result","item","object","resource","entity","input","output","payload","body","content","info"]);function B(e){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),t=Math.floor(r.length/2);return r.length%2!==0?r[t]:(r[t-1]+r[t])/2}function He(e,r,t=D){let{thresholds:o,weights:n}=t,s=x(1-e.parameterCount/(o.maxParamsGood*2)),a=Math.max(e.maxRequestSchemaDepth,e.maxResponseSchemaDepth)/(o.maxDepthGood*2),c=De(e,n.anyOfPenaltyMultiplier)/(o.maxPolymorphismGood*3),h=x(1-a-c),u=(e.operationDescriptionPresent?1:0)+e.paramsWithDescription+e.schemaPropertiesWithDescription,f=1+e.parameterCount+e.totalSchemaProperties,$=f>0?x(u/f):1,O=e.totalSchemaProperties>0?x(e.constraintCount/e.totalSchemaProperties):1,y=(e.requestExamplePresent?1:0)+(e.responseExamplePresent?1:0),g=(e.requestBodyPresent?1:0)+1,M=x(y/g),T=e.totalErrorResponses>0?x(e.structuredErrorResponseCount/e.totalErrorResponses):1,I=x(1-r/(o.maxDependencyDepthGood*2)),l=x(1-e.ambiguousIdentifierCount/Math.max(o.maxAmbiguousGood+3,1)),m=De(e,n.anyOfPenaltyMultiplier),d=m===0?1:e.hasDiscriminator?x(1-m/(o.maxPolymorphismGood*4)):x(1-m/(o.maxPolymorphismGood*2));return{parameterSimplicity:s,schemaSimplicity:h,documentationQuality:$,constraintClarity:O,exampleCoverage:M,errorClarity:T,dependencyClarity:I,identifierClarity:l,polymorphismClarity:d}}function ze(e,r=D){let t=r.weights,o=e.parameterSimplicity*t.parameterSimplicity+e.schemaSimplicity*t.schemaSimplicity+e.documentationQuality*t.documentationQuality+e.constraintClarity*t.constraintClarity+e.exampleCoverage*t.exampleCoverage+e.errorClarity*t.errorClarity+e.dependencyClarity*t.dependencyClarity+e.identifierClarity*t.identifierClarity+e.polymorphismClarity*t.polymorphismClarity;return $e(x(o)*100)}function Re(e,r,t=D){let o=new Map;for(let[n,s]of e.operations){let i=r.get(n)??0,a=He(s,i,t);o.set(n,{agentReadiness:ze(a,t),subscores:a})}return o}function Me(e,r=D){return x(1-e/r.thresholds.maxOperationsForDiscoverability)}function ve(e,r,t=D){if(e.size===0)return{agentReadiness:100};let o=[];for(let i of e.values())o.push(i.agentReadiness);let n=t.weights.discoverabilityWeight,s=r*100;return{agentReadiness:$e(B(o)*(1-n)+s*n)}}function J(e,r,t){return e-r+r*t}function De(e,r){return J(e.polymorphismCount,e.anyOfCount,r)}function x(e){return Math.max(0,Math.min(1,e))}function Ee(e){let r=e.size||1,t={parameterSimplicity:0,schemaSimplicity:0,documentationQuality:0,constraintClarity:0,exampleCoverage:0,errorClarity:0,dependencyClarity:0,identifierClarity:0,polymorphismClarity:0};for(let o of e.values())t.parameterSimplicity+=o.subscores.parameterSimplicity,t.schemaSimplicity+=o.subscores.schemaSimplicity,t.documentationQuality+=o.subscores.documentationQuality,t.constraintClarity+=o.subscores.constraintClarity,t.exampleCoverage+=o.subscores.exampleCoverage,t.errorClarity+=o.subscores.errorClarity,t.dependencyClarity+=o.subscores.dependencyClarity,t.identifierClarity+=o.subscores.identifierClarity,t.polymorphismClarity+=o.subscores.polymorphismClarity;return t.parameterSimplicity/=r,t.schemaSimplicity/=r,t.documentationQuality/=r,t.constraintClarity/=r,t.exampleCoverage/=r,t.errorClarity/=r,t.dependencyClarity/=r,t.identifierClarity/=r,t.polymorphismClarity/=r,t}function $e(e){return Math.round(e*10)/10}function we(e,r,t){let o=Math.max(1,e);return r/o+t/o}function Qe(e,r){return r.totalSchemaProperties>e.totalSchemaProperties?!0:r.totalSchemaProperties<e.totalSchemaProperties?!1:we(r.totalSchemaProperties,r.schemaPropertiesWithDescription,r.constraintCount)>we(e.totalSchemaProperties,e.schemaPropertiesWithDescription,e.constraintCount)}var Ke=["enum","const","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","minProperties","maxProperties","multipleOf","exclusiveMinimum","exclusiveMaximum","uniqueItems"];function Y(){return{depth:-1,maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[],debugEntries:null,pendingRef:null}}function Ie(e){Object.assign(e,Y())}function Le(e){return{ref:{enter(r){typeof r?.$ref=="string"&&(e.refsUsed.push(r.$ref),e.pendingRef=r.$ref)}},Schema:{enter(r,t){e.depth++,e.maxDepth=Math.max(e.maxDepth,e.depth);let o=0;for(let i of Ke)r[i]!==void 0&&(e.constraintCount++,o++);r.discriminator?.propertyName&&(e.hasDiscriminator=!0);let n={};for(let i of["oneOf","anyOf","allOf"]){let a=r[i];Array.isArray(a)&&(e.polymorphismCount+=a.length,i==="anyOf"&&(e.anyOfCount+=a.length),n[i]=a.length)}let s=[];if(L(r.properties)){let i=Object.entries(r.properties);e.totalSchemaProperties+=i.length;for(let[a,c]of i){s.push(a);let h=c&&"$ref"in c&&c.$ref?t.resolve(c)?.node??c:c;h?.description&&e.schemaPropertiesWithDescription++,(h?.example!==void 0||h?.examples)&&(e.hasPropertyExamples=!0),h?.readOnly||e.writableTopLevelFields++}}e.debugEntries!==null&&e.debugEntries.push({ref:e.pendingRef,depth:e.depth,propertyNames:s,polymorphism:Object.keys(n).length>0?n:{},constraintCount:o}),e.pendingRef=null},leave(){e.depth--}}}}function qe(e,r,t){return{operations:new Map,currentPath:"",pathLevelParams:[],current:null,walkSchema:e,anyOfPenaltyMultiplier:r,debugOperationId:t,debugLogs:[]}}function Je(e,r,t){return{path:e,method:r,operationId:t.operationId,operationDescriptionPresent:!!t.description,parameterCount:0,requiredParameterCount:0,paramsWithDescription:0,ambiguousIdentifierCount:0,maxRequestSchemaDepth:0,maxResponseSchemaDepth:0,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,topLevelWritableFieldCount:0,requestBodyPresent:!1,requestExamplePresent:!1,responseExamplePresent:!1,structuredErrorResponseCount:0,totalErrorResponses:0,inRequestBody:!1,inResponse:!1,currentResponseCode:"",errorStructuredCounted:!1,maxEffectivePolymorphism:-1,refsUsed:new Set}}function Ye(e){let{inRequestBody:r,inResponse:t,currentResponseCode:o,errorStructuredCounted:n,maxEffectivePolymorphism:s,...i}=e;return i}function We(e){return{RequestBody:{enter(){e.current&&(e.current.requestBodyPresent=!0,e.current.inRequestBody=!0)},leave(){e.current&&(e.current.inRequestBody=!1)}},Response:{enter(r,t){let o=e.current;if(!o)return;let n=String(t.key);o.inResponse=!0,o.currentResponseCode=n,o.errorStructuredCounted=!1,Te(n)&&(o.totalErrorResponses++,!r.content&&r.description&&(o.structuredErrorResponseCount++,o.errorStructuredCounted=!0))},leave(){e.current&&(e.current.inResponse=!1)}},MediaType:{enter(r){let t=e.current;if(t&&(Ze(r)&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inResponse&&Te(t.currentResponseCode)&&!t.errorStructuredCounted&&(t.structuredErrorResponseCount++,t.errorStructuredCounted=!0),r.schema)){let o=!!e.debugOperationId&&(t.operationId===e.debugOperationId||`${t.method.toUpperCase()} ${t.path}`===e.debugOperationId),n=e.walkSchema(r.schema,o);Qe(t,n)&&(t.totalSchemaProperties=n.totalSchemaProperties,t.schemaPropertiesWithDescription=n.schemaPropertiesWithDescription,t.constraintCount=n.constraintCount);let s=J(n.polymorphismCount,n.anyOfCount,e.anyOfPenaltyMultiplier);s>t.maxEffectivePolymorphism&&(t.maxEffectivePolymorphism=s,t.polymorphismCount=n.polymorphismCount,t.anyOfCount=n.anyOfCount),n.hasDiscriminator&&(t.hasDiscriminator=!0);for(let i of n.refsUsed)t.refsUsed.add(i);if(n.hasPropertyExamples&&(t.inRequestBody&&(t.requestExamplePresent=!0),t.inResponse&&(t.responseExamplePresent=!0)),t.inRequestBody&&(t.maxRequestSchemaDepth=Math.max(t.maxRequestSchemaDepth,n.maxDepth),t.topLevelWritableFieldCount=Math.max(t.topLevelWritableFieldCount,n.writableTopLevelFields)),t.inResponse&&(t.maxResponseSchemaDepth=Math.max(t.maxResponseSchemaDepth,n.maxDepth)),o&&n.debugEntries){let i=t.inRequestBody?"REQUEST BODY":`RESPONSE ${t.currentResponseCode}`;e.debugLogs.push({context:i,entries:n.debugEntries,totalProperties:n.totalSchemaProperties,totalPolymorphism:n.polymorphismCount,totalConstraints:n.constraintCount,maxDepth:n.maxDepth})}}}},Paths:{PathItem:{enter(r,t){e.currentPath=String(t.key),e.pathLevelParams=r.parameters??[]},Operation:{enter(r,t){let o=String(t.key),n=Je(e.currentPath,o,r);e.current=n;let s=Xe(e.pathLevelParams,r.parameters??[],t.resolve);for(let i of s.values())n.parameterCount++,i.required&&n.requiredParameterCount++,i.description&&n.paramsWithDescription++,et(i)&&n.ambiguousIdentifierCount++},leave(r){let t=e.current;if(!t)return;let o=r.operationId??`${t.method.toUpperCase()} ${t.path}`;e.operations.set(o,Ye(t)),e.current=null}}}}}}function Ue(e){return{operationCount:e.operations.size,operations:e.operations}}function Ae(e,r){return r(e).node}function Xe(e,r,t){let o=new Map;for(let n of e){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}for(let n of r){let s=Ae(n,t);s?.name&&s.in&&o.set(`${s.in}:${s.name}`,s)}return o}function Ze(e){return e.example!==void 0||ie(e.examples)}function et(e){if(e.description)return!1;let r=(e.name??"").toLowerCase();return Oe.has(r)}function Te(e){if(e==="default"||/^4xx$/i.test(e)||/^5xx$/i.test(e))return!0;let r=parseInt(e,10);return r>=400&&r<600}function tt(e,r){if(!r.startsWith("#/"))return;let t=e;for(let o of r.slice(2).split("/"))t=t?.[ce(o)];return t}function ke({document:e,types:r,resolvedRefMap:t,ctx:o,debugOperationId:n,scoringConstants:s}){let i=s?.weights.anyOfPenaltyMultiplier??D.weights.anyOfPenaltyMultiplier,a=Y(),c=Le(a),h=Q([{severity:"warn",ruleId:"score-schema",visitor:c}],r),u=(l,m)=>{Ie(a),m&&(a.debugEntries=[]),K({document:{...e,parsed:l},rootType:r.Schema,normalizedVisitors:h,resolvedRefMap:t,ctx:o});let{depth:d,pendingRef:w,debugEntries:_,...N}=a;return{...N,refsUsed:[...a.refsUsed],debugEntries:m?a.debugEntries??void 0:void 0}},f=new Map,$=new WeakSet,O={maxDepth:0,polymorphismCount:0,anyOfCount:0,hasDiscriminator:!1,totalSchemaProperties:0,schemaPropertiesWithDescription:0,constraintCount:0,hasPropertyExamples:!1,writableTopLevelFields:0,refsUsed:[]};function y(l,m){return{maxDepth:Math.max(l.maxDepth,m.maxDepth),polymorphismCount:l.polymorphismCount+m.polymorphismCount,anyOfCount:l.anyOfCount+m.anyOfCount,hasDiscriminator:l.hasDiscriminator||m.hasDiscriminator,totalSchemaProperties:l.totalSchemaProperties+m.totalSchemaProperties,schemaPropertiesWithDescription:l.schemaPropertiesWithDescription+m.schemaPropertiesWithDescription,constraintCount:l.constraintCount+m.constraintCount,hasPropertyExamples:l.hasPropertyExamples||m.hasPropertyExamples,writableTopLevelFields:l.writableTopLevelFields+m.writableTopLevelFields,refsUsed:[...l.refsUsed,...m.refsUsed],debugEntries:l.debugEntries||m.debugEntries?[...l.debugEntries??[],...m.debugEntries??[]]:void 0}}let g=(l,m=!1)=>{let d=l,w=pe(l)?l.$ref:void 0;if(w){if(!m){let S=f.get(w);if(S)return S}d=tt(e.parsed,w)??l}if(L(d)&&$.has(d))return{...O};L(d)&&$.add(d);let _=d?.oneOf,N=d?.anyOf,Z=Array.isArray(_)&&_.length>1,ee=Array.isArray(N)&&N.length>1,G=Z||ee,te=Array.isArray(d?.allOf)&&d.allOf.length>0,V=d?.discriminator,q=!G&&L(V?.mapping)?Object.values(V.mapping).filter(S=>typeof S=="string"&&me(S)).map(S=>({$ref:S})):null,re=Array.isArray(q)&&q.length>0,C;if(G||te||re){let S={...d},F=null,oe=P=>{F=F?y(F,P):P},ne=(P,v)=>{let E=g(v[0],m);for(let z=1;z<v.length;z++){let se=g(v[z],m);se.totalSchemaProperties>E.totalSchemaProperties&&(E=se)}return{...E,polymorphismCount:E.polymorphismCount+v.length,anyOfCount:E.anyOfCount+(P==="anyOf"?v.length:0),hasDiscriminator:E.hasDiscriminator||!!V}};G&&delete S.discriminator,Z&&(delete S.oneOf,oe(ne("oneOf",_))),ee&&(delete S.anyOf,oe(ne("anyOf",N)));let H=null;if(re){delete S.discriminator;let P=g(q[0],m);for(let v=1;v<q.length;v++){let E=g(q[v],m);E.totalSchemaProperties>P.totalSchemaProperties&&(P=E)}H={...P,polymorphismCount:P.polymorphismCount+q.length,hasDiscriminator:!0}}let W=null;if(te){delete S.allOf,W={...O};for(let P of d.allOf)W=y(W,g(P,m));W.polymorphismCount+=d.allOf.length}C=u(S,m),W&&(C=y(C,W)),F&&(C=y(C,F)),H&&(C=y(C,H)),w&&(C={...C,refsUsed:[w,...C.refsUsed]})}else C=u(l,m);return L(d)&&$.delete(d),w&&!m&&f.set(w,C),C},M=qe(g,i,n),T=We(M),I=Q([{severity:"warn",ruleId:"score",visitor:T}],r);return K({document:e,rootType:r.Root,normalizedVisitors:I,resolvedRefMap:t,ctx:o}),{metrics:Ue(M),debugLogs:M.debugLogs}}function Ne(e){let r=new Map;for(let[n,s]of e)for(let i of s.refsUsed){let a=r.get(i);a||(a=new Set,r.set(i,a)),a.add(n)}let t=new Map;for(let n of e.keys())t.set(n,new Set);for(let n of r.values()){if(n.size<2)continue;let s=Array.from(n);for(let i=0;i<s.length;i++)for(let a=i+1;a<s.length;a++)t.get(s[i]).add(s[a]),t.get(s[a]).add(s[i])}let o=new Map;for(let n of e.keys()){let s=rt(n,t);o.set(n,s)}return o}function rt(e,r){let t=new Set([e]),o=[e],n=0;for(;o.length>0;){let s=[];for(let i of o)for(let a of r.get(i)??[])t.has(a)||(t.add(a),s.push(a));s.length>0&&n++,o=s}return n}function Fe(e){let r={agentReadiness:e.agentReadiness,discoverability:Math.round(e.discoverability*100),subscores:e.subscores,rawMetrics:{operationCount:e.rawMetrics.operationCount,operations:Object.fromEntries(Array.from(e.rawMetrics.operations.entries()).map(([t,o])=>{let{refsUsed:n,...s}=o;return[t,s]}))},operationScores:Object.fromEntries(e.operationScores),dependencyDepths:Object.fromEntries(e.dependencyDepths),hotspots:e.hotspots};k.output(JSON.stringify(r,null,2))}function je(e,r=!1){ot(e),nt(e),it(e),r&&at(e),pt(e)}function _e(e){return e>=80?de:e>=50?j:fe}function Be(e){return _e(e)(b(e.toFixed(1)))}function p(e){k.output(e+`
|
|
8
|
-
`)}function ot(e){p(""),p(b(A(" Scores"))),p(""),p(` Agent Readiness: ${Be(e.agentReadiness)}/100`),p("")}function nt(e){p(b(A(" Subscores"))),p("");let r=e.subscores;R("Parameter Simplicity",r.parameterSimplicity),R("Schema Simplicity",r.schemaSimplicity),R("Documentation Quality",r.documentationQuality),R("Constraint Clarity",r.constraintClarity),R("Example Coverage",r.exampleCoverage),R("Error Clarity",r.errorClarity),R("Dependency Clarity",r.dependencyClarity),R("Identifier Clarity",r.identifierClarity),R("Polymorphism Clarity",r.polymorphismClarity),R("Discoverability",e.discoverability),p("")}function R(e,r){let t=Math.round(r*100),o=st(r);p(` ${e.padEnd(24)} ${o} ${_e(t)(t+"%")}`)}function st(e){let t=Math.round(e*20);return U("["+"\u2588".repeat(t)+"\u2591".repeat(20-t)+"]")}function it(e){if(p(b(A(" Raw Metrics Summary"))),p(""),p(` Total operations: ${e.rawMetrics.operationCount}`),e.rawMetrics.operationCount===0){p("");return}let r=[],t=[],o=[],n=[],s=0,i=0,a=0;for(let u of e.rawMetrics.operations.values())r.push(u.parameterCount),t.push(Math.max(u.maxRequestSchemaDepth,u.maxResponseSchemaDepth)),o.push(u.polymorphismCount),n.push(u.totalSchemaProperties),u.requestExamplePresent&&s++,u.responseExamplePresent&&i++,u.operationDescriptionPresent&&a++;let c=e.rawMetrics.operationCount;function h(u,f){let O=(f.reduce((T,I)=>T+I,0)/c).toFixed(1),y=B(f).toFixed(1),g=Math.min(...f),M=Math.max(...f);p(` ${u.padEnd(26)} avg ${O.padStart(6)} median ${y.padStart(6)} min ${String(g).padStart(5)} max ${String(M).padStart(5)}`)}h("Parameters/operation:",r),h("Schema depth:",t),h("Polymorphism/operation:",o),h("Properties/operation:",n),p(` Operations with request examples: ${s}/${c} (${X(s,c)})`),p(` Operations with response examples: ${i}/${c} (${X(i,c)})`),p(` Operations with description: ${a}/${c} (${X(a,c)})`),p("")}function X(e,r){return r>0?`${Math.round(e/r*100)}%`:"N/A"}function at(e){p(b(A(" Per-Operation Metrics"))),p("");let r=" "+"Operation".padEnd(50)+"Props".padStart(7)+"Poly".padStart(7)+"Depth".padStart(7)+"Params".padStart(8)+"Constr".padStart(8);p(U(r)),p(U(" "+"\u2500".repeat(r.length-2)));let t=[...e.rawMetrics.operations.entries()].sort(([,o],[,n])=>n.totalSchemaProperties-o.totalSchemaProperties);for(let[,o]of t){let n=(o.operationId??`${o.method.toUpperCase()} ${o.path}`).slice(0,48),s=Math.max(o.maxRequestSchemaDepth,o.maxResponseSchemaDepth),i=" "+n.padEnd(50)+String(o.totalSchemaProperties).padStart(7)+String(o.polymorphismCount).padStart(7)+String(s).padStart(7)+String(o.parameterCount).padStart(8)+String(o.constraintCount).padStart(8);p(i)}p("")}function Ge(e,r){if(p(""),p(b(A(` Debug: ${e} schema breakdown`))),p(""),r.length===0){p(j(` No schemas found for operation "${e}".`)),p(j(' Make sure the value matches an operationId or "METHOD /path" exactly.')),p("");return}for(let t of r){p(b(U(` ${t.context}`))),p(U(" "+"\u2500".repeat(70)));let o=new Map;for(let s of t.entries){let i=s.ref??`(inline depth ${s.depth})`,a=o.get(i);if(a){a.count++,a.totalProps+=s.propertyNames.length;for(let c of s.propertyNames)a.propNames.includes(c)||a.propNames.push(c)}else o.set(i,{count:1,totalProps:s.propertyNames.length,propNames:[...s.propertyNames]})}for(let s of t.entries){let i=s.ref??"(inline)",a=" ".repeat(Math.min(s.depth,6)),c=s.propertyNames.length,h=` ${a}${i}`;c>0&&(h+=` (${c} properties)`);let u=[];if(s.polymorphism.oneOf&&u.push(`oneOf:${s.polymorphism.oneOf}`),s.polymorphism.anyOf&&u.push(`anyOf:${s.polymorphism.anyOf}`),s.polymorphism.allOf&&u.push(`allOf:${s.polymorphism.allOf}`),u.length>0&&(h+=` [${u.join(", ")}]`),s.constraintCount>0&&(h+=` {${s.constraintCount} constraints}`),p(h),c>0&&c<=20)p(` ${a} properties: ${s.propertyNames.join(", ")}`);else if(c>20){let f=s.propertyNames.slice(0,15).join(", ");p(` ${a} properties: ${f}, ... +${c-15} more`)}}p(""),p(` Totals: ${t.totalProperties} properties, ${t.totalPolymorphism} polymorphism items, ${t.totalConstraints} constraints, max depth ${t.maxDepth}`);let n=[...o.entries()].filter(([,s])=>s.totalProps>0).sort(([,s],[,i])=>i.totalProps-s.totalProps).slice(0,10);if(n.length>0){p(""),p(b(" Top schemas by property count:"));for(let[s,i]of n)p(` ${s}: ${i.totalProps} properties`)}p("")}}function pt(e){if(e.hotspots.length===0){p(b(A(" No hotspot operations found."))),p("");return}p(b(A(` Top ${e.hotspots.length} Hotspot Operations`))),p("");for(let r of e.hotspots){let t=r.operationId?`${r.method.toUpperCase()} ${r.path} (${r.operationId})`:`${r.method.toUpperCase()} ${r.path}`;p(b(` ${t}`)),p(` Agent Readiness: ${Be(r.agentReadinessScore)}`);for(let o of r.reasons)p(j(` - ${o}`));p("")}}function Ve(e,r,t,o=D){let n=[];for(let[s,i]of r){let a=e.operations.get(s);if(!a)continue;let c=ct(a,t.get(s)??0,o);c.length!==0&&n.push({path:a.path,method:a.method,operationId:a.operationId,agentReadinessScore:i.agentReadiness,reasons:c})}return n.sort((s,i)=>s.reasons.length!==i.reasons.length?i.reasons.length-s.reasons.length:s.agentReadinessScore-i.agentReadinessScore),n.slice(0,o.hotspotLimit)}function ct(e,r,t){let{thresholds:o}=t,n=[];e.parameterCount>o.maxParamsGood&&n.push(`High parameter count (${e.parameterCount})`);let s=Math.max(e.maxRequestSchemaDepth,e.maxResponseSchemaDepth);s>o.maxDepthGood&&n.push(`Deep schema nesting (depth ${s})`),e.anyOfCount>0&&!e.hasDiscriminator?n.push(`Polymorphism (anyOf) without discriminator (${e.anyOfCount} anyOf)`):e.polymorphismCount>o.maxPolymorphismGood&&n.push(`High polymorphism count (${e.polymorphismCount})`);let i=e.requestBodyPresent&&!e.requestExamplePresent,a=!e.responseExamplePresent;return i&&a?n.push("Missing request and response examples"):i?n.push("Missing request body examples"):a&&n.push("Missing response examples"),e.totalErrorResponses>0&&e.structuredErrorResponseCount===0&&n.push("No structured error responses (4xx/5xx)"),e.operationDescriptionPresent||n.push("Missing operation description"),e.parameterCount>0&&e.paramsWithDescription===0&&n.push("No parameter descriptions"),r>o.maxDependencyDepthGood&&n.push(`High dependency depth (${r})`),e.ambiguousIdentifierCount>o.maxAmbiguousGood&&n.push(`Ambiguous identifiers (${e.ambiguousIdentifierCount})`),n}async function Vt({argv:e,config:r,collectSpecData:t}){let[{path:o}]=await xe(e.api?[e.api]:[],r),n=new le(r.resolve),{bundle:s}=await be({config:r,ref:o});t?.(s);let i=ge(s.parsed);if(Se(i)!=="oas3")throw new Ce(`The score command currently supports only OpenAPI 3.x. Detected: ${i}`);let a=mt.now(),c=ae(r.extendTypes(ue(i),i),r),h=await he({rootDocument:s,rootType:c.Root,externalRefResolver:n}),u=e["debug-operation-id"],{metrics:f,debugLogs:$}=ke({document:s,types:c,resolvedRefMap:h,ctx:{problems:[],specVersion:i,config:r,visitorsData:{}},debugOperationId:u}),O=Ne(f.operations),y=Re(f,O),g=Me(f.operationCount),{agentReadiness:M}=ve(y,g),T=Ve(f,y,O),I={agentReadiness:M,discoverability:g,subscores:Ee(y),rawMetrics:f,hotspots:T,operationScores:y,dependencyDepths:O};ut(I,o,a,e.format,!!e["operation-details"],u?{operationId:u,logs:$}:void 0)}function ut(e,r,t,o,n,s){k.info(`Document: ${ye(r)} score:
|
|
9
|
-
`),o==="json"?Fe(e):je(e,n),s&&Ge(s.operationId,s.logs),Pe("score",t,r)}export{Vt as handleScore};
|
package/lib/chunks/YUNIBLZR.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
-
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
-
const require = __createRequire(import.meta.url);
|
|
5
|
-
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
-
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as O}from"./YEACSN2C.js";import{a as b,d as A,e as E,g as B,o as F,p as h}from"./OM4VGI2Q.js";import{h as I}from"./3I7XLHPY.js";import{O as P,P as v,Q as i,S as u,T as m,X as a,ca as d,m as c}from"./M4YE5ALG.js";var y=class extends Error{};async function X({argv:t,version:e}){let n=performance.now(),s=new O,{organization:o,project:p,pushId:$,wait:g}=t,T=t.domain||B(),w=t["continue-on-deploy-failures"]||!1,U=t["start-time"]||Date.now(),S=[];try{let f=E(),R={domain:T,apiKey:f,organization:o,project:p,pushId:$,version:e,onSunsetWarning:l=>S.push(l)},x={...R,maxExecutionTime:t["max-execution-time"],retryIntervalMs:t["retry-interval"]?t["retry-interval"]*1e3:void 0,startTime:U},D=l=>j=>{let{status:C,url:z}=j.status[l].deploy;s.start(M({status:C,url:z,buildType:l,wait:g}))},r=g?await h({...x,buildType:"preview",onRetry:D("preview")}):await F(R);return W({buildType:"preview",spinner:s,push:r,continueOnDeployFailures:w}),L(r.status.preview.scorecard),g&&r.isMainBranch&&r.status.preview.deploy.status==="success"&&(r=await h({...x,buildType:"production",onRetry:D("production")})),r.isMainBranch&&(W({buildType:"production",spinner:s,push:r,continueOnDeployFailures:w}),L(r.status.production.scorecard)),K({organization:o,project:p,pushId:$,startedAt:n}),{preview:r.status.preview,production:r.isMainBranch?r.status.production:null,commit:r.commit}}catch(f){s.stop(),N("\u2717 Failed to get push status.",f)}finally{s.stop(),k("push-status",S)}}function N(t,e){throw e instanceof y?new d(e.message):e instanceof b?new d(`${t} Reason: ${e.message} (status: ${e.status})
|
|
8
|
-
`):new d(`${t} Reason: ${e.message}
|
|
9
|
-
`)}function k(t,e){let n=A(e);if(!n)return;let s='Update to the latest version by running "npm install @redocly/cli@latest".';n.isSunsetExpired?a.error(`The "${t}" command is not compatible with your version of Redocly CLI. ${s}
|
|
10
|
-
|
|
11
|
-
`):a.warn(`The "${t}" command will be incompatible with your version of Redocly CLI after ${n.sunsetDate.toLocaleString()}. ${s}
|
|
12
|
-
|
|
13
|
-
`)}function K({organization:t,project:e,pushId:n,startedAt:s}){a.info(`
|
|
14
|
-
Processed push-status for ${i(t)}, ${i(e)} and pushID ${i(n)}.
|
|
15
|
-
`),I("push-status",s,"Finished")}function W({buildType:t,spinner:e,push:n,continueOnDeployFailures:s}){n.isOutdated||!n.hasChanges?a.warn(`Files not added to your project. Reason: ${n.isOutdated?"outdated":"no changes"}.
|
|
16
|
-
`):H({status:n.status[t].deploy.status,url:n.status[t].deploy.url,buildType:t,spinner:e,continueOnDeployFailures:s})}function L(t){if(!(!t||t.length===0)){a.output(`
|
|
17
|
-
${u("Scorecard")}:`);for(let e of t)a.output(`
|
|
18
|
-
${u("Name")}: ${e.name}
|
|
19
|
-
${u("Status")}: ${e.status}
|
|
20
|
-
${u("URL")}: ${m(e.url)}
|
|
21
|
-
${u("Description")}: ${e.description}
|
|
22
|
-
`);a.output(`
|
|
23
|
-
`)}}function H({status:t,url:e,spinner:n,buildType:s,continueOnDeployFailures:o}){let p=M({status:t,url:e,buildType:s});if(n.stop(),t==="failed"&&!o)throw new y(p);a.output(p)}function M({status:t,url:e,buildType:n,wait:s}){switch(t){case"skipped":return`${i(`Skipped ${n}`)}
|
|
24
|
-
`;case"pending":{let o=`${i(`Pending ${n}`)}`;return s?o:`Status: ${o}
|
|
25
|
-
`}case"running":{let o=`${i(`Running ${n}`)}`;return s?o:`Status: ${o}
|
|
26
|
-
`}case"success":return`${v(`\u{1F680} ${c(n)} deploy success.`)}
|
|
27
|
-
${u(`${c(n)} URL`)}: ${m(e||"No URL yet.")}
|
|
28
|
-
`;case"failed":return`${P(`\u274C ${c(n)} deploy fail.`)}
|
|
29
|
-
${u(`${c(n)} URL`)}: ${m(e||"No URL yet.")}`;default:{let o=`${i(`No status yet for ${n} deploy`)}`;return s?o:`Status: ${o}
|
|
30
|
-
`}}}export{y as a,X as b,N as c,k as d};
|