@redocly/cli 2.56.0 → 2.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD_PARTY_NOTICES +14 -30
- package/lib/chunks/{ICOYFJR4.js → 2PGNW76R.js} +1 -1
- package/lib/chunks/3I7XLHPY.js +45 -0
- package/lib/chunks/{JADJJP6R.js → 3QGJWJKQ.js} +1 -1
- package/lib/chunks/{BH4SKQ6M.js → 4HG5PCQA.js} +1 -1
- package/lib/chunks/{N2FNYVCN.js → 4JBK2BSL.js} +1 -1
- package/lib/chunks/4PTNG4EI.js +7 -0
- package/lib/chunks/{NPBKCM7B.js → 4SXCDBB7.js} +1 -1
- package/lib/chunks/{DOJW7C4M.js → 52MXI4PU.js} +2 -2
- package/lib/chunks/{WUXDP2A3.js → 5FVKAWNE.js} +1 -1
- package/lib/chunks/{TVL6DMBV.js → 5UDC2SWY.js} +3 -3
- package/lib/chunks/64G5RPLP.js +7 -0
- package/lib/chunks/{MGMNYFOR.js → 65AQJO4M.js} +2 -2
- package/lib/chunks/{SH75MWAC.js → 664FDTDV.js} +1 -1
- package/lib/chunks/7EB22KXX.js +14 -0
- package/lib/chunks/{3R32Y5ZJ.js → 7XKYPQPI.js} +1 -1
- package/lib/chunks/{BDCNFVGZ.js → AOCVSFC3.js} +1 -1
- package/lib/chunks/{LPB2X45H.js → ARDTVDGR.js} +1 -1
- package/lib/chunks/{DSD57XD4.js → CWEET26O.js} +1 -1
- package/lib/chunks/{YJ2CV2FV.js → D7WNH6Z5.js} +1 -1
- package/lib/chunks/{E2KKD73B.js → DMW5VJBT.js} +1 -1
- package/lib/chunks/{DXEOF3IX.js → DT66L2TO.js} +1 -1
- package/lib/chunks/EDU3YBRA.js +7 -0
- package/lib/chunks/F57WBWGV.js +29 -0
- package/lib/chunks/{JDBGRKTP.js → F5V42ZYY.js} +1 -1
- package/lib/chunks/FDOONAMV.js +20 -0
- package/lib/chunks/{EJXJAU3Z.js → GEWI247R.js} +1 -1
- package/lib/chunks/{UNHSYVDZ.js → GHOLYNZA.js} +1 -1
- package/lib/chunks/GHSNC2OX.js +9 -0
- package/lib/chunks/{7MISZQY2.js → GVJFU4AP.js} +1 -1
- package/lib/chunks/{N2D5LLBV.js → H5OX3UOD.js} +1 -1
- package/lib/chunks/HBUZKWXC.js +7 -0
- package/lib/chunks/{7BAI3GZ5.js → IDI3SURO.js} +4 -4
- package/lib/chunks/{TC3EIKUK.js → J3DL5HGI.js} +1 -1
- package/lib/chunks/{FKC3B2RN.js → JMFIKCPX.js} +1 -1
- package/lib/chunks/{O64VVDHW.js → K2ENYHHD.js} +1 -1
- package/lib/chunks/{QKT4AI5U.js → LI6IH6DJ.js} +1 -1
- package/lib/chunks/{QXIVVOOR.js → LJPUHAWE.js} +1 -1
- package/lib/chunks/LUW2ZJJO.js +13 -0
- package/lib/chunks/M4YE5ALG.js +193 -0
- package/lib/chunks/MKS4O6F4.js +119 -0
- package/lib/chunks/MZWBJKK2.js +10 -0
- package/lib/chunks/{MWNK3IKD.js → N2GTHB37.js} +1 -1
- package/lib/chunks/NALRPITK.js +7 -0
- package/lib/chunks/{FTARAJQN.js → OM4VGI2Q.js} +1 -1
- package/lib/chunks/{XKNG65W6.js → OR3KBRCI.js} +1 -1
- package/lib/chunks/P7A7BCIN.js +14 -0
- package/lib/chunks/{NHMYQF3F.js → QDSAT32N.js} +1 -1
- package/lib/chunks/{RZ6XOBIA.js → R2FG6TUX.js} +1 -1
- package/lib/chunks/{RDLDTF4L.js → S5PUZGYS.js} +1 -1
- package/lib/chunks/SJHPKWSD.js +9 -0
- package/lib/chunks/{ISBVQBNS.js → SRCGYHDN.js} +1 -1
- package/lib/chunks/U5DIFWGH.js +7 -0
- package/lib/chunks/{7IULUVWX.js → UF2ZCH7W.js} +1 -1
- package/lib/chunks/{GORWWTSA.js → UXFJO2OQ.js} +1 -1
- package/lib/chunks/{3L35HFJG.js → VBHLPG5Q.js} +1 -1
- package/lib/chunks/{ARIBTVNO.js → VE7VT5PT.js} +1 -1
- package/lib/chunks/{VM6OOWSF.js → VIPV4IEH.js} +1 -1
- package/lib/chunks/VT3BHT6S.js +34 -0
- package/lib/chunks/{ZHK7GAOT.js → VUU57INZ.js} +1 -1
- package/lib/chunks/{P43DKA2E.js → VYHYEZI5.js} +1 -1
- package/lib/chunks/{5KSMVZSO.js → WKCOTH3C.js} +1 -1
- package/lib/chunks/X5NXRMUW.js +11 -0
- package/lib/chunks/{6WNK6ZW5.js → XTTR5PBC.js} +1 -1
- package/lib/chunks/XYKNLM5G.js +10 -0
- package/lib/chunks/{UQHIGGP6.js → Y2AFRRAT.js} +1 -1
- package/lib/chunks/{LGQZK7NR.js → YDVOCOBI.js} +1 -1
- package/lib/chunks/{HOUAVEH6.js → YEACSN2C.js} +1 -1
- package/lib/chunks/YFI3NLJF.js +9 -0
- package/lib/chunks/YMDFCK3F.js +18 -0
- package/lib/chunks/YOBULQYM.js +11 -0
- package/lib/chunks/{AOFLS3JM.js → YUNIBLZR.js} +2 -2
- package/lib/chunks/ZBOUASE7.js +7 -0
- package/lib/chunks/{ZQHPJPJ2.js → ZFJHZEI3.js} +1 -1
- package/lib/chunks/{UTZVN6YA.js → ZVXAH4QD.js} +1 -1
- package/lib/eject-assets/generators/cli/docs.ts +1 -1
- package/lib/eject-assets/generators/cli/engine-source.ts +1 -1
- package/lib/eject-assets/generators/cli/index.ts +2 -2
- package/lib/eject-assets/generators/cli/render.ts +1 -1
- package/lib/eject-assets/generators/go/client.ts +1 -1
- package/lib/eject-assets/generators/go/descriptor.ts +1 -1
- package/lib/eject-assets/generators/go/index.ts +2 -2
- package/lib/eject-assets/generators/go/models.ts +1 -1
- package/lib/eject-assets/generators/go/naming.ts +1 -1
- package/lib/eject-assets/generators/go/operations.ts +1 -1
- package/lib/eject-assets/generators/go/pagination.ts +1 -1
- package/lib/eject-assets/generators/go/types.ts +1 -1
- package/lib/eject-assets/generators/mock/faker.ts +1 -1
- package/lib/eject-assets/generators/mock/index.ts +2 -2
- package/lib/eject-assets/generators/mock/render.ts +1 -1
- package/lib/eject-assets/generators/mock/sample.ts +1 -1
- package/lib/eject-assets/generators/mock/values.ts +1 -1
- package/lib/eject-assets/generators/php/client.ts +1 -1
- package/lib/eject-assets/generators/php/descriptor.ts +1 -1
- package/lib/eject-assets/generators/php/index.ts +2 -2
- package/lib/eject-assets/generators/php/models.ts +1 -1
- package/lib/eject-assets/generators/php/naming.ts +1 -1
- package/lib/eject-assets/generators/php/operations.ts +1 -1
- package/lib/eject-assets/generators/php/pagination.ts +1 -1
- package/lib/eject-assets/generators/php/types.ts +1 -1
- package/lib/eject-assets/generators/python/client.ts +1 -1
- package/lib/eject-assets/generators/python/descriptor.ts +1 -1
- package/lib/eject-assets/generators/python/index.ts +2 -2
- package/lib/eject-assets/generators/python/models.ts +1 -1
- package/lib/eject-assets/generators/python/naming.ts +1 -1
- package/lib/eject-assets/generators/python/operations.ts +1 -1
- package/lib/eject-assets/generators/python/pagination.ts +1 -1
- package/lib/eject-assets/generators/python/types.ts +1 -1
- package/lib/eject-assets/generators/swr/index.ts +2 -2
- package/lib/eject-assets/generators/swr/render.ts +1 -1
- package/lib/eject-assets/generators/tanstack-query/index.ts +2 -2
- package/lib/eject-assets/generators/tanstack-query/render.ts +1 -1
- package/lib/eject-assets/generators/transformers/index.ts +2 -2
- package/lib/eject-assets/generators/transformers/render.ts +1 -1
- package/lib/eject-assets/generators/typescript/banner.ts +1 -1
- package/lib/eject-assets/generators/typescript/client.ts +1 -1
- package/lib/eject-assets/generators/typescript/descriptor.ts +1 -1
- package/lib/eject-assets/generators/typescript/index.ts +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 +78 -293
- package/package.json +1 -1
- package/lib/chunks/EVTLV6L3.js +0 -13
- package/lib/chunks/M4FV4I2Z.js +0 -47
- package/lib/chunks/UVKEIQXW.js +0 -193
package/THIRD_PARTY_NOTICES
CHANGED
|
@@ -623,19 +623,21 @@ Packages:
|
|
|
623
623
|
zod-to-json-schema@3.25.2 — Copyright (c) 2020, Stefan Terdell
|
|
624
624
|
|
|
625
625
|
License text:
|
|
626
|
-
|
|
626
|
+
The ISC License
|
|
627
627
|
|
|
628
|
-
|
|
629
|
-
with or without fee is hereby granted, provided that the above copyright notice
|
|
630
|
-
and this permission notice appear in all copies.
|
|
628
|
+
Copyright (c) Isaac Z. Schlueter and Contributors
|
|
631
629
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
630
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
631
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
632
|
+
copyright notice and this permission notice appear in all copies.
|
|
633
|
+
|
|
634
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
635
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
636
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
637
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
638
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
639
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
|
|
640
|
+
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
639
641
|
|
|
640
642
|
============================================================
|
|
641
643
|
MIT
|
|
@@ -730,25 +732,7 @@ Packages:
|
|
|
730
732
|
zod@4.4.3 — Copyright (c) 2025 Colin McDonnell
|
|
731
733
|
|
|
732
734
|
License text:
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
736
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
737
|
-
in the Software without restriction, including without limitation the rights
|
|
738
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
739
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
740
|
-
furnished to do so, subject to the following conditions:
|
|
741
|
-
|
|
742
|
-
The above copyright notice and this permission notice shall be included in
|
|
743
|
-
all copies or substantial portions of the Software.
|
|
744
|
-
|
|
745
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
746
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
747
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
748
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
749
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
750
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
751
|
-
THE SOFTWARE.
|
|
735
|
+
(no license text found)
|
|
752
736
|
|
|
753
737
|
============================================================
|
|
754
738
|
unknown
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as x,b as y,c as R,d as u}from"./
|
|
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
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
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
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)}
|
|
@@ -0,0 +1,45 @@
|
|
|
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};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as B}from"./2U6O26CV.js";import{b as E,c as T,d as W,f as ee,g as ne,h as te,i as re}from"./VM6OOWSF.js";import{a as Y,c as C,d as p,e as w,f as x,g as D,h as O,i as X,j,k as I,l as F,n as Z}from"./UW4UC7ZI.js";var U=C.php,q=class extends Y{constructor(){super(" ")}typeName(n){return p(n,{style:"pascal",reserved:U})}memberName(n){return p(n,{style:"camel",reserved:U})}identifier(n){return p(n,{style:"camel",reserved:U})}identifiers(n,s){return w(n,{style:"camel",reserved:U,taken:s})}string(n){return`'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}literal(n){return n==null?"null":typeof n=="boolean"||typeof n=="number"?String(n):typeof n=="string"?this.string(n):Array.isArray(n)?`[${n.map(i=>this.literal(i)).join(", ")}]`:`[${Object.entries(n).map(([i,r])=>`${this.string(i)} => ${this.literal(r)}`).join(", ")}]`}comment(n){for(let s of F(n))this.line(s===""?"//":`// ${s}`);return this}doc(n,s,i=[]){let r=F(s);if(r.length===0&&i.length===0)return this;let t=r.length===0?n:`${n} \u2014 ${r.join(" ")}`;if(i.length===0)return this.line(`/** ${t} */`);this.line("/**"),this.line(` * ${t}`),this.line(" *");for(let a of i)this.line(` * ${a}`);return this.line(" */")}};var h=C.php,G=new q;function y(e){return G.typeName(e)}function b(e){return G.memberName(e)}function c(e){return G.string(e)}function ie(e){return p(e.name,{style:"camel",reserved:h})}function K(e){let n=e.services.flatMap(i=>i.operations),s=w(n.map(i=>i.name),{style:"camel",reserved:h});return new Map(n.map((i,r)=>[i.name,s[r]]))}function de(e){return ee(e).map(s=>s.kind==="literal"?c(s.value):`$${b(s.name)}`).join(" . ")}function se(e,n){let s=n.servers??[];if(s.length===0)return;let i=new Set;e.line("/** The declared servers; variables default to the values from the description. */"),e.line("final class Servers"),e.block("{",()=>{s.forEach((r,t)=>{let a=p(r.description??`server${t+1}`,{style:"camel",reserved:h});i.has(a)&&(a=`${a}${t+1}`),i.add(a);let o=r.variables.map(l=>`string $${b(l.name)} = ${c(l.default)}`);t>0&&e.blank(),e.line(`public static function ${a}(${o.join(", ")}): string`),e.block("{",()=>{e.line(`return ${de(r)};`)},"}")})},"}"),e.blank()}function ae(e,n){let s=ne(e,n).map(i=>`[${i.map(t=>t.kind==="apiKey"?`['kind' => 'apiKey', 'scheme' => ${c(t.scheme)}, 'name' => ${c(t.name)}, 'in' => ${c(t.in)}]`:`['kind' => ${c(t.kind)}, 'scheme' => ${c(t.scheme)}]`).join(", ")}]`);if(s.length!==0)return`[${s.join(", ")}]`}function oe(e){return`[${[`'style' => ${c(e.style)}`,...e.param!==void 0?[`'param' => ${c(e.param)}`]:[],...e.nextCursor!==void 0?[`'nextCursor' => ${c(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`'hasMore' => ${c(e.hasMore)}`]:[],...e.limitParam!==void 0?[`'limitParam' => ${c(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${c(e.items)}`]:[]].join(", ")}]`}function ce(e,n){let s=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let t=p(r.name,{style:"camel",reserved:h}),a=2;for(;s.has(t);)t=`${p(r.name,{style:"camel",reserved:h})}_${a++}`;s.add(t);let o=Z(r.schema,n);return`[${c(r.name)}, ${c(t)}, ${c(o)}]`}).join(", ")}]`}function _(e,n){let s=n.schemas.find(t=>t.name===e);if(s===void 0)return"other";let i=s.schema,r=I(i);return r!==void 0&&(r.scalar==="string"||r.scalar==="integer")?"enum":(i.kind==="object"||i.kind==="intersection")&&D(i,n)!==void 0?"class":"other"}function m(e,n,s="string"){if(X(e)){let i=m(j(e),n,s);return A(i)}switch(e.kind){case"scalar":return s==="Date"&&e.scalar==="string"&&L(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let i=_(e.name,n);if(i==="class"||i==="enum")return y(e.name);let r=x(e,n);return r===void 0?"mixed":m(r,n,s)}case"enum":return{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float";case"omit":return y(e.base);case"union":return me(e.members,n,s);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function L(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function A(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function me(e,n,s){let i=[];for(let r of e){if(r.kind==="null")continue;let t=m(r,n,s);if(t==="mixed")return"mixed";let a=t.startsWith("?")?t.slice(1):t;i.includes(a)||i.push(a),t.startsWith("?")&&!i.includes("null")&&i.push("null")}return i.length===0?"mixed":i.join("|")}function J(e,n,s){if(e===void 0)return;let i=j(e);if(i.kind==="ref"){let t=x(i,n);return _(i.name,n)==="other"?J(t,n,s):void 0}if(i.kind!=="array")return;let r=m(i.items,n,s);return r==="mixed"?void 0:r}function le(e,n){let s=n.schemas.find(i=>i.name===e);return s!==void 0&&O(s.schema,n)!==void 0}function v(e,n,s,i){let r=j(e);if(i==="Date"&&r.kind==="scalar"&&r.scalar==="string"&&L(r))return`new \\DateTimeImmutable(${n})`;if(r.kind==="omit")return v({kind:"ref",name:r.base},n,s,i);if(r.kind==="ref"){let t=_(r.name,s);if(t==="class")return`${y(r.name)}::fromArray(${n})`;if(t==="enum")return`${y(r.name)}::from(${n})`;if(le(r.name,s))return`unmarshal${y(r.name)}(${n})`;let a=x(r,s);return a===void 0?void 0:v(a,n,s,i)}if(r.kind==="array"){let t=v(r.items,"$item",s,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(r.kind==="record"){let t=v(r.value,"$item",s,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function N(e,n,s,i="string"){let r=j(e);if(i==="Date"&&r.kind==="scalar"&&r.scalar==="string"){if(r.metadata?.format==="date")return`${n}->format('Y-m-d')`;if(r.metadata?.format==="date-time")return`${n}->format(\\DateTimeInterface::ATOM)`}if(r.kind==="omit")return N({kind:"ref",name:r.base},n,s,i);if(r.kind==="ref"){let t=_(r.name,s);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(le(r.name,s))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let a=x(r,s);return a===void 0?void 0:N(a,n,s,i)}if(r.kind==="array"||r.kind==="record"){let t=r.kind==="array"?r.items:r.value,a=N(t,"$item",s,i);return a===void 0?void 0:`array_map(static fn ($item) => ${a}, ${n})`}}function pe(e,n,s,i,r,t){let a=[...s.filter(o=>o.required),...s.filter(o=>!o.required)];e.doc(y(n),t),e.line(`final class ${y(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let o of a){let l=m(o.schema,i,r);if(o.required)e.line(`public ${l} $${b(o.name)},`);else{let u=A(l);e.line(`public ${u} $${b(o.name)} = null,`)}}},") {"),e.line("}"),e.blank(),e.line("public static function fromArray(array $data): self"),e.block("{",()=>{e.block("return new self(",()=>{for(let o of a){let l=`$data[${c(o.name)}]`,u=v(o.schema,l,i,r),f=b(o.name);o.required?e.line(`${f}: ${u??l},`):u===void 0?e.line(`${f}: ${l} ?? null,`):e.line(`${f}: isset(${l}) ? ${u} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let o of a){let l=`$this->${b(o.name)}`,u=N(o.schema,l,i,r)??l;o.required?e.line(`$data[${c(o.name)}] = ${u};`):e.block(`if (${l} !== null) {`,()=>{e.line(`$data[${c(o.name)}] = ${u};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function V(e,n="string"){let s=new q;for(let{name:i,schema:r}of e.schemas){let t=I(r);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let o=t.scalar==="string"?"string":"int";s.doc(y(i),r.description),s.line(`enum ${y(i)}: ${o}`),s.block("{",()=>{let l=w(t.values.map(u=>String(u)),{style:"pascal",reserved:h});t.values.forEach((u,f)=>{let g=typeof u=="string"?c(u):String(u);s.line(`case ${l[f]} = ${g};`)})},"}"),s.blank();continue}if(r.kind==="object"||r.kind==="intersection"){let o=D(r,e);if(o!==void 0){pe(s,i,o.properties,e,n,o.description??r.description);continue}}let a=O(r,e);if(a!==void 0){let o=y(i),l=a.cases.map(u=>`${u.value} -> ${y(u.schemaName)}`).join(", ");s.line(`/** ${o} is a discriminated union (${c(a.property)}): ${l}. */`),s.line(`function unmarshal${o}(array $data): mixed`),s.block("{",()=>{s.block(`return match ($data[${c(a.property)}] ?? null) {`,()=>{for(let u of a.cases)s.line(`${c(u.value)} => ${y(u.schemaName)}::fromArray($data),`);s.line("default => $data,")},"};")},"}"),s.blank();continue}}return s.toString()}var ue=new Set(["post","put","patch"]),he=["body","headers","idempotencyKey"];function z(e,n,s,i){let r=w([...e.pathParams,...e.queryParams].map(l=>l.name),{style:"camel",reserved:h,taken:he}),t=e.pathParams.map((l,u)=>({php:r[u],wire:l.name,type:m(l.schema,n,i)})),a=e.queryParams.map((l,u)=>{let f=r[e.pathParams.length+u];return{php:f,wire:l.name,type:m(l.schema,n,i),value:N(l.schema,`$${f}`,n,i)??`$${f}`}}),o=[...t.map(({php:l,type:u})=>`${u} $${l}`),...s&&e.requestBody?[`${W(e)?"array":m(e.requestBody.schema,n,i)} $body`]:[],...a.map(({php:l,type:u})=>`${A(u)} $${l} = null`),"?array $headers = null",...s&&ue.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:a,signature:o}}function ye(e,n,s){e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("[$authHeaders, $query, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);");for(let{php:r,wire:t,value:a}of s.queryArgs)e.block(`if ($${r} !== null) {`,()=>{e.line(`$query[${c(t)}] = ${a};`)},"}");let i=s.pathArgs.map(({php:r,wire:t})=>`${c(t)} => $${r}`).join(", ");e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${i}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}")}function Q(e,n,s,i,r,t=!1){let a=z(n,i,!0,r),o=T(n),l=E(n),u=o===void 0&&l===void 0&&n.successResponses.some(k=>k.contentType!==""),f=t?"Envelope":o!==void 0?"\\Generator":l!==void 0?m(l,i,r):u?"string":"void",g=t?`${s}WithHeaders`:s,H=t?void 0:J(l,i,r);e.doc(g,t?`Like ${s}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,H===void 0?[]:[`@return ${H}[]`]),e.line(`public function ${g}(${a.signature.join(", ")}): ${f}`),e.block("{",()=>{if(ye(e,n,a),o!==void 0){let d=o.schema!==void 0&&o.schema.kind!=="unknown";e.line("$url = appendQuery($url, $query);"),e.block("$open = function (array $extraHeaders) use ($url, $requestHeaders): \\CurlHandle {",()=>{e.line("$handle = curl_init($url);"),e.line("$lines = [];"),e.block("foreach (array_merge($requestHeaders, $extraHeaders) as $name => $value) {",()=>{e.line("$lines[] = $name . ': ' . $value;")},"}"),e.line("curl_setopt($handle, CURLOPT_HTTPHEADER, $lines);"),e.line("return $handle;")},"};"),e.line(`yield from iterSse($open, ${d?"true":"false"});`);return}let k=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(n.requestBody&&W(n))e.line("[$contentType, $encoded] = toMultipart($body);"),k.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let d=N(n.requestBody.schema,"$body",i,r)??"$body";e.line(`$payload = json_encode(${d});`),k.push("'body' => $payload",`'contentType' => ${c(n.requestBody.contentType)}`)}ue.has(n.method.toLowerCase())&&n.requestBody&&k.push("'idempotencyKey' => $idempotencyKey"),e.line(`$response = send($this->config, [${k.join(", ")}]);`),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}");let $=u?"$response['body']":(l===void 0?void 0:v(l,"decodeJson($response)",i,r))??"decodeJson($response)";if(t){e.line(`$data = ${$};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${ce(n,i)}), status: $response['status']);`);return}if(u){e.line("return $response['body'];");return}if(f==="void"){e.line("decodeJson($response);");return}e.line(`return ${$};`)},"}"),e.blank()}function $e(e,n,s,i,r,t,a,o,l){let u=z(n,i,!1,r),f=s,g=()=>{e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:d,wire:P,value:S}of u.queryArgs)e.block(`if ($${d} !== null) {`,()=>{e.line(`$base[${c(P)}] = ${S};`)},"}");let $=u.pathArgs.map(({php:d,wire:P})=>`${c(P)} => $${d}`).join(", ");e.block("$call = function (array $params) use ($op, $headers): array {",()=>{e.line("[$authHeaders, $authQuery, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);"),e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${$}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}"),e.line("$response = send($this->config, ['operationId' => $op['id'], 'method' => $op['method'], 'url' => $url, 'headers' => $requestHeaders, 'query' => array_merge($params, $authQuery)]);"),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}"),e.line("return [decodeJson($response), $response];")},"};")},H=m(E(n)??{kind:"unknown"},i,r),k=H==="mixed"?"mixed":H;e.line("/**"),e.line(` * ${f} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${k}>`),e.line(" */"),e.line(`public function ${f}Pages(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{g(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`yield ${t??"$page"};`)},"}")},"}"),e.blank(),e.line("/**"),e.line(` * The items of every ${f} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${l}>`),e.line(" */"),e.line(`public function ${f}Items(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{g(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${c(o??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${a??"$item"};`)},"}")},"}")},"}"),e.blank()}function ge(e){let n=e.split(`
|
|
7
|
+
import{b as B}from"./2U6O26CV.js";import{b as E,c as T,d as W,f as ee,g as ne,h as te,i as re}from"./VIPV4IEH.js";import{a as Y,c as C,d as p,e as w,f as x,g as D,h as O,i as X,j,k as I,l as F,n as Z}from"./UW4UC7ZI.js";var U=C.php,q=class extends Y{constructor(){super(" ")}typeName(n){return p(n,{style:"pascal",reserved:U})}memberName(n){return p(n,{style:"camel",reserved:U})}identifier(n){return p(n,{style:"camel",reserved:U})}identifiers(n,s){return w(n,{style:"camel",reserved:U,taken:s})}string(n){return`'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}literal(n){return n==null?"null":typeof n=="boolean"||typeof n=="number"?String(n):typeof n=="string"?this.string(n):Array.isArray(n)?`[${n.map(i=>this.literal(i)).join(", ")}]`:`[${Object.entries(n).map(([i,r])=>`${this.string(i)} => ${this.literal(r)}`).join(", ")}]`}comment(n){for(let s of F(n))this.line(s===""?"//":`// ${s}`);return this}doc(n,s,i=[]){let r=F(s);if(r.length===0&&i.length===0)return this;let t=r.length===0?n:`${n} \u2014 ${r.join(" ")}`;if(i.length===0)return this.line(`/** ${t} */`);this.line("/**"),this.line(` * ${t}`),this.line(" *");for(let a of i)this.line(` * ${a}`);return this.line(" */")}};var h=C.php,G=new q;function y(e){return G.typeName(e)}function b(e){return G.memberName(e)}function c(e){return G.string(e)}function ie(e){return p(e.name,{style:"camel",reserved:h})}function K(e){let n=e.services.flatMap(i=>i.operations),s=w(n.map(i=>i.name),{style:"camel",reserved:h});return new Map(n.map((i,r)=>[i.name,s[r]]))}function de(e){return ee(e).map(s=>s.kind==="literal"?c(s.value):`$${b(s.name)}`).join(" . ")}function se(e,n){let s=n.servers??[];if(s.length===0)return;let i=new Set;e.line("/** The declared servers; variables default to the values from the description. */"),e.line("final class Servers"),e.block("{",()=>{s.forEach((r,t)=>{let a=p(r.description??`server${t+1}`,{style:"camel",reserved:h});i.has(a)&&(a=`${a}${t+1}`),i.add(a);let o=r.variables.map(l=>`string $${b(l.name)} = ${c(l.default)}`);t>0&&e.blank(),e.line(`public static function ${a}(${o.join(", ")}): string`),e.block("{",()=>{e.line(`return ${de(r)};`)},"}")})},"}"),e.blank()}function ae(e,n){let s=ne(e,n).map(i=>`[${i.map(t=>t.kind==="apiKey"?`['kind' => 'apiKey', 'scheme' => ${c(t.scheme)}, 'name' => ${c(t.name)}, 'in' => ${c(t.in)}]`:`['kind' => ${c(t.kind)}, 'scheme' => ${c(t.scheme)}]`).join(", ")}]`);if(s.length!==0)return`[${s.join(", ")}]`}function oe(e){return`[${[`'style' => ${c(e.style)}`,...e.param!==void 0?[`'param' => ${c(e.param)}`]:[],...e.nextCursor!==void 0?[`'nextCursor' => ${c(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`'hasMore' => ${c(e.hasMore)}`]:[],...e.limitParam!==void 0?[`'limitParam' => ${c(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${c(e.items)}`]:[]].join(", ")}]`}function ce(e,n){let s=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let t=p(r.name,{style:"camel",reserved:h}),a=2;for(;s.has(t);)t=`${p(r.name,{style:"camel",reserved:h})}_${a++}`;s.add(t);let o=Z(r.schema,n);return`[${c(r.name)}, ${c(t)}, ${c(o)}]`}).join(", ")}]`}function _(e,n){let s=n.schemas.find(t=>t.name===e);if(s===void 0)return"other";let i=s.schema,r=I(i);return r!==void 0&&(r.scalar==="string"||r.scalar==="integer")?"enum":(i.kind==="object"||i.kind==="intersection")&&D(i,n)!==void 0?"class":"other"}function m(e,n,s="string"){if(X(e)){let i=m(j(e),n,s);return A(i)}switch(e.kind){case"scalar":return s==="Date"&&e.scalar==="string"&&L(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let i=_(e.name,n);if(i==="class"||i==="enum")return y(e.name);let r=x(e,n);return r===void 0?"mixed":m(r,n,s)}case"enum":return{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float";case"omit":return y(e.base);case"union":return me(e.members,n,s);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function L(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function A(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function me(e,n,s){let i=[];for(let r of e){if(r.kind==="null")continue;let t=m(r,n,s);if(t==="mixed")return"mixed";let a=t.startsWith("?")?t.slice(1):t;i.includes(a)||i.push(a),t.startsWith("?")&&!i.includes("null")&&i.push("null")}return i.length===0?"mixed":i.join("|")}function J(e,n,s){if(e===void 0)return;let i=j(e);if(i.kind==="ref"){let t=x(i,n);return _(i.name,n)==="other"?J(t,n,s):void 0}if(i.kind!=="array")return;let r=m(i.items,n,s);return r==="mixed"?void 0:r}function le(e,n){let s=n.schemas.find(i=>i.name===e);return s!==void 0&&O(s.schema,n)!==void 0}function v(e,n,s,i){let r=j(e);if(i==="Date"&&r.kind==="scalar"&&r.scalar==="string"&&L(r))return`new \\DateTimeImmutable(${n})`;if(r.kind==="omit")return v({kind:"ref",name:r.base},n,s,i);if(r.kind==="ref"){let t=_(r.name,s);if(t==="class")return`${y(r.name)}::fromArray(${n})`;if(t==="enum")return`${y(r.name)}::from(${n})`;if(le(r.name,s))return`unmarshal${y(r.name)}(${n})`;let a=x(r,s);return a===void 0?void 0:v(a,n,s,i)}if(r.kind==="array"){let t=v(r.items,"$item",s,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(r.kind==="record"){let t=v(r.value,"$item",s,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function N(e,n,s,i="string"){let r=j(e);if(i==="Date"&&r.kind==="scalar"&&r.scalar==="string"){if(r.metadata?.format==="date")return`${n}->format('Y-m-d')`;if(r.metadata?.format==="date-time")return`${n}->format(\\DateTimeInterface::ATOM)`}if(r.kind==="omit")return N({kind:"ref",name:r.base},n,s,i);if(r.kind==="ref"){let t=_(r.name,s);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(le(r.name,s))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let a=x(r,s);return a===void 0?void 0:N(a,n,s,i)}if(r.kind==="array"||r.kind==="record"){let t=r.kind==="array"?r.items:r.value,a=N(t,"$item",s,i);return a===void 0?void 0:`array_map(static fn ($item) => ${a}, ${n})`}}function pe(e,n,s,i,r,t){let a=[...s.filter(o=>o.required),...s.filter(o=>!o.required)];e.doc(y(n),t),e.line(`final class ${y(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let o of a){let l=m(o.schema,i,r);if(o.required)e.line(`public ${l} $${b(o.name)},`);else{let u=A(l);e.line(`public ${u} $${b(o.name)} = null,`)}}},") {"),e.line("}"),e.blank(),e.line("public static function fromArray(array $data): self"),e.block("{",()=>{e.block("return new self(",()=>{for(let o of a){let l=`$data[${c(o.name)}]`,u=v(o.schema,l,i,r),f=b(o.name);o.required?e.line(`${f}: ${u??l},`):u===void 0?e.line(`${f}: ${l} ?? null,`):e.line(`${f}: isset(${l}) ? ${u} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let o of a){let l=`$this->${b(o.name)}`,u=N(o.schema,l,i,r)??l;o.required?e.line(`$data[${c(o.name)}] = ${u};`):e.block(`if (${l} !== null) {`,()=>{e.line(`$data[${c(o.name)}] = ${u};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function V(e,n="string"){let s=new q;for(let{name:i,schema:r}of e.schemas){let t=I(r);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let o=t.scalar==="string"?"string":"int";s.doc(y(i),r.description),s.line(`enum ${y(i)}: ${o}`),s.block("{",()=>{let l=w(t.values.map(u=>String(u)),{style:"pascal",reserved:h});t.values.forEach((u,f)=>{let g=typeof u=="string"?c(u):String(u);s.line(`case ${l[f]} = ${g};`)})},"}"),s.blank();continue}if(r.kind==="object"||r.kind==="intersection"){let o=D(r,e);if(o!==void 0){pe(s,i,o.properties,e,n,o.description??r.description);continue}}let a=O(r,e);if(a!==void 0){let o=y(i),l=a.cases.map(u=>`${u.value} -> ${y(u.schemaName)}`).join(", ");s.line(`/** ${o} is a discriminated union (${c(a.property)}): ${l}. */`),s.line(`function unmarshal${o}(array $data): mixed`),s.block("{",()=>{s.block(`return match ($data[${c(a.property)}] ?? null) {`,()=>{for(let u of a.cases)s.line(`${c(u.value)} => ${y(u.schemaName)}::fromArray($data),`);s.line("default => $data,")},"};")},"}"),s.blank();continue}}return s.toString()}var ue=new Set(["post","put","patch"]),he=["body","headers","idempotencyKey"];function z(e,n,s,i){let r=w([...e.pathParams,...e.queryParams].map(l=>l.name),{style:"camel",reserved:h,taken:he}),t=e.pathParams.map((l,u)=>({php:r[u],wire:l.name,type:m(l.schema,n,i)})),a=e.queryParams.map((l,u)=>{let f=r[e.pathParams.length+u];return{php:f,wire:l.name,type:m(l.schema,n,i),value:N(l.schema,`$${f}`,n,i)??`$${f}`}}),o=[...t.map(({php:l,type:u})=>`${u} $${l}`),...s&&e.requestBody?[`${W(e)?"array":m(e.requestBody.schema,n,i)} $body`]:[],...a.map(({php:l,type:u})=>`${A(u)} $${l} = null`),"?array $headers = null",...s&&ue.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:a,signature:o}}function ye(e,n,s){e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("[$authHeaders, $query, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);");for(let{php:r,wire:t,value:a}of s.queryArgs)e.block(`if ($${r} !== null) {`,()=>{e.line(`$query[${c(t)}] = ${a};`)},"}");let i=s.pathArgs.map(({php:r,wire:t})=>`${c(t)} => $${r}`).join(", ");e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${i}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}")}function Q(e,n,s,i,r,t=!1){let a=z(n,i,!0,r),o=T(n),l=E(n),u=o===void 0&&l===void 0&&n.successResponses.some(k=>k.contentType!==""),f=t?"Envelope":o!==void 0?"\\Generator":l!==void 0?m(l,i,r):u?"string":"void",g=t?`${s}WithHeaders`:s,H=t?void 0:J(l,i,r);e.doc(g,t?`Like ${s}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,H===void 0?[]:[`@return ${H}[]`]),e.line(`public function ${g}(${a.signature.join(", ")}): ${f}`),e.block("{",()=>{if(ye(e,n,a),o!==void 0){let d=o.schema!==void 0&&o.schema.kind!=="unknown";e.line("$url = appendQuery($url, $query);"),e.block("$open = function (array $extraHeaders) use ($url, $requestHeaders): \\CurlHandle {",()=>{e.line("$handle = curl_init($url);"),e.line("$lines = [];"),e.block("foreach (array_merge($requestHeaders, $extraHeaders) as $name => $value) {",()=>{e.line("$lines[] = $name . ': ' . $value;")},"}"),e.line("curl_setopt($handle, CURLOPT_HTTPHEADER, $lines);"),e.line("return $handle;")},"};"),e.line(`yield from iterSse($open, ${d?"true":"false"});`);return}let k=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(n.requestBody&&W(n))e.line("[$contentType, $encoded] = toMultipart($body);"),k.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let d=N(n.requestBody.schema,"$body",i,r)??"$body";e.line(`$payload = json_encode(${d});`),k.push("'body' => $payload",`'contentType' => ${c(n.requestBody.contentType)}`)}ue.has(n.method.toLowerCase())&&n.requestBody&&k.push("'idempotencyKey' => $idempotencyKey"),e.line(`$response = send($this->config, [${k.join(", ")}]);`),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}");let $=u?"$response['body']":(l===void 0?void 0:v(l,"decodeJson($response)",i,r))??"decodeJson($response)";if(t){e.line(`$data = ${$};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${ce(n,i)}), status: $response['status']);`);return}if(u){e.line("return $response['body'];");return}if(f==="void"){e.line("decodeJson($response);");return}e.line(`return ${$};`)},"}"),e.blank()}function $e(e,n,s,i,r,t,a,o,l){let u=z(n,i,!1,r),f=s,g=()=>{e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:d,wire:P,value:S}of u.queryArgs)e.block(`if ($${d} !== null) {`,()=>{e.line(`$base[${c(P)}] = ${S};`)},"}");let $=u.pathArgs.map(({php:d,wire:P})=>`${c(P)} => $${d}`).join(", ");e.block("$call = function (array $params) use ($op, $headers): array {",()=>{e.line("[$authHeaders, $authQuery, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);"),e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${$}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}"),e.line("$response = send($this->config, ['operationId' => $op['id'], 'method' => $op['method'], 'url' => $url, 'headers' => $requestHeaders, 'query' => array_merge($params, $authQuery)]);"),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}"),e.line("return [decodeJson($response), $response];")},"};")},H=m(E(n)??{kind:"unknown"},i,r),k=H==="mixed"?"mixed":H;e.line("/**"),e.line(` * ${f} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${k}>`),e.line(" */"),e.line(`public function ${f}Pages(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{g(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`yield ${t??"$page"};`)},"}")},"}"),e.blank(),e.line("/**"),e.line(` * The items of every ${f} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${l}>`),e.line(" */"),e.line(`public function ${f}Items(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{g(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${c(o??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${a??"$item"};`)},"}")},"}")},"}"),e.blank()}function ge(e){let n=e.split(`
|
|
8
8
|
`),s=0;for(let i=0;i<n.length;i++)if(n[i].trim().startsWith("namespace ")){s=i+1;break}return n.slice(s).join(`
|
|
9
9
|
`).trim()}var ln=({model:e,output:n,banner:s,emit:i,pagination:r})=>{let t=new q,a=i.dateType??"string",o=p(e.title,{style:"pascal",reserved:h});t.line("<?php"),t.blank(),t.line(`// Code generated by @redocly/client-generator (php) from ${c(e.title)} ${e.version}. DO NOT EDIT.`),t.line("// Regenerate with `redocly generate-client`. PHP >= 8.1, curl extension \u2014 zero Composer dependencies."),t.blank(),t.line("declare(strict_types=1);"),t.blank(),t.line(`namespace ${o};`),t.blank(),t.line(V(e,a)),se(t,e),i.runtime==="module"?(t.line("// \u2500\u2500\u2500 Runtime (a real file beside this one, written by the same run) \u2500\u2500\u2500"),t.line("require_once __DIR__ . '/runtime.php';"),t.blank()):(t.line("// \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator php runtime) \u2500\u2500\u2500"),t.line(ge(B)),t.blank());let l=e.services.flatMap($=>$.operations),u=K(e),f=new Map;for(let $ of l){let d=r?.get($.name)?.spec;d!==void 0&&f.set($.name,d)}t.block("const OPERATIONS = [",()=>{for(let $ of l){let d=$.specName??$.name,P=ae($,e),S=f.get($.name),M=[`'id' => ${c(d)}`,`'method' => ${c($.method.toUpperCase())}`,`'path' => ${c($.path)}`,...P!==void 0?[`'security' => ${P}`]:[],...S!==void 0?[`'pagination' => ${oe(S)}`]:[]];t.line(`${c(d)} => [${M.join(", ")}],`)}},"];"),t.blank(),t.doc("Client",`Client for ${e.title} (${e.version}).`),t.line("class Client"),t.block("{",()=>{t.line("public function __construct(private Config $config)"),t.block("{",()=>{t.block("if ($this->config->serverUrl === '') {",()=>{t.line(`$this->config->serverUrl = ${c(i.serverUrl??e.serverUrl??"")};`)},"}")},"}"),t.blank();for(let $ of l){let d=u.get($.name);Q(t,$,d,e,a),T($)===void 0&&($.successResponseHeaders?.length??0)>0&&Q(t,$,d,e,a,!0);let P=f.get($.name);if(P===void 0)continue;let S=E($),M=S===void 0?void 0:v(S,"$page",e,a),R=te(S,P.items,e),fe=R===void 0?void 0:v(R,"$item",e,a);$e(t,$,d,e,a,M,fe,P.items,R===void 0?"mixed":m(R,e,a))}},"}");let g={path:n.path.replace(/\.[^.\\/]+$/,".php"),content:t.toString()};if(i.runtime!=="module")return[g];let H=s.map($=>`// ${$}`).join(`
|
|
10
10
|
`),k=B.replace(/^namespace .*$/m,`namespace ${o};`).replace(/^<\?php\n/,`<?php
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e}from"./
|
|
7
|
+
import{a,b,c,d,e}from"./3QGJWJKQ.js";import"./2U6O26CV.js";import"./VIPV4IEH.js";import"./65AQJO4M.js";import"./WZXA5XPB.js";import"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./UW4UC7ZI.js";import"./RFWIIJFG.js";export{e as phpDocs,c as phpGenerator,d as phpSample,a as phpType,b as renderPhpModels};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as h}from"./
|
|
7
|
+
import{a as h}from"./65AQJO4M.js";import{e as g,h as p,k as $}from"./LD5MEXEL.js";import{join as R}from"node:path";var a=" ";function m(e){return`${$(e)}Schema`}var y=new Map;function u(e,r=y,t=""){return j(w(e,r,t),e)}function w(e,r,t){switch(e.kind){case"scalar":return z(e.scalar,e.metadata);case"object":return b(e.properties,r,t);case"array":return`z.array(${u(e.items,r,t)})`;case"record":return`z.record(z.string(), ${u(e.value,r,t)})`;case"ref":return`z.lazy(() => ${m(e.name)})`;case"literal":return`z.literal(${p(e.value)})`;case"enum":return q(e.values);case"union":return k(e.members,r,t);case"intersection":return e.members.map(n=>u(n,r,t)).reduce((n,o)=>`${n}.and(${o})`);case"null":return"z.null()";case"unknown":return"z.unknown()";case"omit":return E(e.base,e.keys,r,t)}}function z(e,r){switch(e){case"string":return r?.format==="binary"?"z.instanceof(Blob)":"z.string()";case"integer":return"z.number().int()";case"number":return"z.number()";case"boolean":return"z.boolean()"}}function c(e){return g(e)===e?e:JSON.stringify(e)}function b(e,r,t){if(e.length===0)return"z.object({})";let n=t+a;return`z.object({
|
|
8
8
|
${e.map((s,i)=>{let d=u(s.schema,r,n),l=s.required?d:`${d}.optional()`,x=i===e.length-1?"":",";return`${n}${c(s.name)}: ${l}${x}`}).join(`
|
|
9
9
|
`)}
|
|
10
10
|
${t}})`}function q(e){return e.every(r=>typeof r=="string")?`z.enum([${e.map(r=>JSON.stringify(r)).join(", ")}])`:`z.union([${e.map(r=>`z.literal(${p(r)})`).join(", ")}])`}function k(e,r,t){let n=e.map(o=>u(o,r,t));return n.length===1?n[0]:`z.union([${n.join(", ")}])`}function E(e,r,t,n){let o=t.get(e);if(o&&o.kind!=="object")return u(f(o,r,t,new Set([e])),t,n);let s=r.map(i=>`${c(i)}: true`).join(", ");return`${m(e)}.omit({ ${s} })`}function f(e,r,t,n){switch(e.kind){case"object":return{...e,properties:e.properties.filter(o=>!r.includes(o.name))};case"union":case"intersection":return{...e,members:e.members.map(o=>f(o,r,t,n))};case"ref":{if(n.has(e.name))return e;let o=t.get(e.name);if(!o)return e;if(o.kind==="object"){let s=r.filter(i=>o.properties.some(d=>d.name===i));return s.length>0?{kind:"omit",base:e.name,keys:s}:e}return f(o,r,t,new Set([...n,e.name]))}default:return e}}function j(e,r){let t=r.metadata;if(!t)return e;let n=e;return r.kind==="scalar"&&r.scalar==="string"&&(t.minLength!==void 0&&(n=`${n}.min(${t.minLength})`),t.maxLength!==void 0&&(n=`${n}.max(${t.maxLength})`),t.pattern!==void 0&&(n=`${n}.regex(new RegExp(${JSON.stringify(t.pattern)}))`)),r.kind==="scalar"&&(r.scalar==="number"||r.scalar==="integer")&&(t.minimum!==void 0&&(n=`${n}.min(${t.minimum})`),t.maximum!==void 0&&(n=`${n}.max(${t.maximum})`),t.exclusiveMinimum!==void 0&&(n=`${n}.gt(${t.exclusiveMinimum})`),t.exclusiveMaximum!==void 0&&(n=`${n}.lt(${t.exclusiveMaximum})`)),r.kind==="array"&&(t.minItems!==void 0&&(n=`${n}.min(${t.minItems})`),t.maxItems!==void 0&&(n=`${n}.max(${t.maxItems})`)),n}function Z(e,r){let t=[];for(let n of h(e.services)){if(n.sse!==void 0)continue;let o=n.requestBody,s=o&&o.contentType.toLowerCase().includes("json")?u(o.schema,r,a):void 0,i=n.successResponses.find(l=>l.contentType.toLowerCase().includes("json")),d=i?u(i.schema,r,a):void 0;!s&&!d||t.push({name:n.specName??n.name,request:s,response:d})}return t}function I(e){let r=e.flatMap(n=>[`${a}${c(n.name)}: {`,...n.request?[`${a}${a}request: z.ZodType;`]:[],...n.response?[`${a}${a}response: z.ZodType;`]:[],`${a}};`]),t=e.map((n,o)=>{let s=[...n.request?[`request: ${n.request}`]:[],...n.response?[`response: ${n.response}`]:[]].join(", "),i=o===e.length-1?"":",";return`${a}${c(n.name)}: { ${s} }${i}`});return["/**"," * Request/response validators by operationId \u2014 powers `zodValidation`, or import one directly."," */","export const operationSchemas: {",...r,"} = {",...t,"};"].join(`
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
var e={realm:"@redocly/realm","redoc-revel":"@redocly/redoc-revel","revel-reef":"@redocly/revel-reef","redoc-reef":"@redocly/redoc-reef",redoc:"@redocly/redoc",revel:"@redocly/revel",reef:"@redocly/reef"},r={redoc:"Redoc",revel:"Revel",reef:"Reef",realm:"Realm","redoc-revel":"Redoc + Revel","redoc-reef":"Redoc + Reef","revel-reef":"Revel + Reef"},o=["pro","enterprise"];export{e as a,r as b,o as c};
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a,b,c}from"./
|
|
7
|
+
import{a,b,c}from"./SRCGYHDN.js";import"./2U6O26CV.js";import"./JMFIKCPX.js";import"./VIPV4IEH.js";import"./65AQJO4M.js";import"./WZXA5XPB.js";import"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./LD5MEXEL.js";import"./UW4UC7ZI.js";import"./RFWIIJFG.js";export{b as typescriptDocs,a as typescriptGenerator,c as typescriptSample};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as G}from"./
|
|
7
|
+
import{a as ae,b as Y,c as ce,d as pe}from"./LUW2ZJJO.js";import{a as G}from"./LI6IH6DJ.js";import{c as x,d as C,e as fe,h as N,j as I,k as ue,v as _,w as B}from"./WKCOTH3C.js";import{a as ie}from"./64G5RPLP.js";import"./YEACSN2C.js";import{C as re,D as v,X as S,c as g,ca as oe,ha as se,l as O}from"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{mkdir as jt,writeFile as kt}from"node:fs/promises";import At from"node:path";var Be=/^[a-zA-Z][a-zA-Z0-9]*(?:[_\-.][a-zA-Z0-9]+)*$/,De=/^[0-9a-f-]{8,}$/i,ze=[["uuid",/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],["date-time",/^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/],["date",/^\d{4}-\d{2}-\d{2}$/],["email",/^[^\s@]+@[^\s@]+\.[^\s@]+$/],["uri",/^https?:\/\/\S+$/],["ipv4",/^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/]],M=new WeakMap;function D(e){return{formats:ze.filter(([,t])=>t.test(e)).map(([t])=>t),values:[e],count:1,overflow:!1}}function q(e,t){if(!e)return t;if(!t)return e;let n={formats:e.formats.filter(r=>t.formats.includes(r)),values:[],count:e.count+t.count,overflow:e.overflow||t.overflow};if(!n.overflow){let r=[...e.values];for(let o of t.values)r.includes(o)||r.push(o);r.length>10?n.overflow=!0:n.values=r}return n}function z(e,t){M.set(e,t)}function H(e){return M.get(e)}function V(e,t){let n=M.get(e);n&&M.set(t,n)}function He(e){return e.length<=30&&!De.test(e)&&Be.test(e)}function K(e,t){return e.formats.length>0?{format:e.formats[0]}:t&&!e.overflow&&e.count>=4&&e.values.length>0&&e.values.length<=5&&e.values.length*2<=e.count&&e.values.every(He)?{enum:[...e.values].sort()}:{}}function $(e){let t=M.get(e);if(t){let n=typeof e.type=="string"?[e.type]:e.type??[];n.includes("string")&&Object.assign(e,K(t,n.length===1))}for(let n of Object.values(e.properties??{}))$(n);e.additionalProperties&&$(e.additionalProperties),e.items&&$(e.items);for(let n of e.oneOf??[])$(n)}function me(e){for(let t of Object.values(e.paths))for(let n of Object.values(t)){for(let r of Object.values(n.requestBody?.content??{}))$(r.schema);for(let r of Object.values(n.responses))for(let o of Object.values(r.content??{}))$(o.schema)}for(let t of Object.values(e.components?.schemas??{}))$(t);return e}var be=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,F=/^\d+$/,Ve=/^[0-9a-hjkmnp-tv-z]{26}$/i,Ue=/^[a-z][a-z0-9]*_(?=[0-9a-z]*\d)[0-9a-z]{10,}$/i,Fe=/^[a-z](?=[a-z0-9]*\d)[a-z0-9]{23,24}$/,X=new Set(ie),Le=new Set(["get","head"]),de="application/x-www-form-urlencoded",le="multipart/form-data";function Ye(e){return e?F.test(e)||be.test(e)||Ve.test(e)||Ue.test(e)||Fe.test(e)?!0:/^[0-9a-f]{16,}$/i.test(e):!1}function Z(e){let t=e.split("/"),n=[],r=new Set;return{template:t.map((s,c)=>{if(!Ye(s))return s;let i=t[c-1],a=i?`${O(i,1)}Id`:"id",p=1;for(;r.has(a);)p+=1,a=i?`${O(i,1)}Id${p}`:`id${p}`;return r.add(a),n.push({name:a,value:s}),`{${a}}`}).join("/")||"/",params:n}}function j(e){if(e===null)return{type:"null"};if(Array.isArray(e)){if(e.length===0)return{type:"array"};let t=e.slice(0,20).map(j);return{type:"array",items:J(t)}}switch(typeof e){case"string":{let t={type:"string"};return z(t,D(e)),t}case"boolean":return{type:"boolean"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"object":{let t=Object.entries(e);if(t.length>0&&(t.every(([c])=>F.test(c))||t.every(([c])=>be.test(c))))return{type:"object",additionalProperties:J(t.map(([,c])=>j(c)))};let n={},r=[];for(let[s,c]of t)n[s]=j(c),r.push(s);let o={type:"object",properties:n};return r.length>0&&(o.required=r),o}default:return{}}}function J(e){if(e.length===0)return{};let[t,...n]=e,r=t;for(let o of n)r=U(r,o);return r}function he(e){return Object.keys(e).length===0}function k(e){return e.additionalProperties?"map":e.type==="object"?"object":e.type==="array"?"array":"scalar"}function W(e){return e.oneOf?e.oneOf.flatMap(W):Array.isArray(e.type)?e.type.map(t=>{if(t==="object"){let r={type:"object"};return e.properties&&(r.properties=e.properties),e.required&&(r.required=e.required),e.additionalProperties&&(r.additionalProperties=e.additionalProperties),r}if(t==="array")return e.items?{type:"array",items:e.items}:{type:"array"};let n={type:t};return t==="string"&&V(e,n),n}):[e]}var Ke=.5,We=3;function Oe(e,t){let n=Object.keys(e.properties??{}),r=Object.keys(t.properties??{});if(n.length===0||r.length===0)return 1;let o=new Set(r),s=n.filter(c=>o.has(c)).length;return s/(n.length+r.length-s)}function Xe(e,t){let n=k(e);if(n!==k(t))return!1;switch(n){case"scalar":return e.type===t.type||e.type==="integer"&&t.type==="number"||e.type==="number"&&t.type==="integer";case"object":return Oe(e,t)>=Ke;default:return!0}}function ve(e,t){switch(k(e)){case"scalar":{if(e.type!==t.type)return{type:"number"};if(e.type==="string"){let n=q(H(e),H(t));if(n){let r={type:"string"};return z(r,n),r}}return e}case"map":return{type:"object",additionalProperties:U(e.additionalProperties??{},t.additionalProperties??{})};case"object":{let n={...e.properties??{}};for(let[c,i]of Object.entries(t.properties??{}))n[c]=n[c]?U(n[c],i):i;let r=new Set(t.required??[]),o=(e.required??[]).filter(c=>r.has(c)),s={type:"object",properties:n};return o.length>0&&(s.required=o),s}case"array":{if(!e.items||!t.items){let n=e.items??t.items;return n?{type:"array",items:n}:{type:"array"}}return{type:"array",items:U(e.items,t.items)}}}}function Ze(e){let t=[...e],n=()=>t.filter(r=>k(r)==="object").length;for(;n()>We;){let r=-1,o=-1,s=-1;for(let c=0;c<t.length;c++)if(k(t[c])==="object")for(let i=c+1;i<t.length;i++){if(k(t[i])!=="object")continue;let a=Oe(t[c],t[i]);a>s&&(s=a,r=c,o=i)}t[r]=ve(t[r],t[o]),t.splice(o,1)}return t}var Qe=["boolean","integer","number","string","null"];function et(e){if(e.length===1)return e[0];let t=[],n=new Set,r;for(let i of e)k(i)==="scalar"&&typeof i.type=="string"?(n.add(i.type),i.type==="string"&&(r=q(r,H(i)))):t.push(i);let o=Qe.filter(i=>n.has(i)),s=i=>{let a={type:i};return(typeof i=="string"?i==="string":i.includes("string"))&&r&&z(a,r),a};if(t.length===0)return o.length===1?s(o[0]):s(o);if(t.length===1&&o.length===1&&o[0]==="null"&&typeof t[0].type=="string")return{...t[0],type:[t[0].type,"null"]};let c=[...t];return o.length===1?c.push(s(o[0])):o.length>1&&c.push(s(o)),{oneOf:c}}function U(e,t){if(he(e)||he(t))return{};let n=W(e);for(let r of W(t)){let o=n.findIndex(s=>Xe(s,r));o===-1?n.push(r):n[o]=ve(n[o],r)}return et(Ze(n))}function tt(e){if(!e)return;let t=e.trim();if(!(!t.startsWith("{")&&!t.startsWith("[")))try{return JSON.parse(t)}catch{return}}function nt(e,t){let n=t?.match(/boundary="?([^";,]+)"?/i)?.[1];if(!n)return;let r={};for(let o of e.split(`--${n}`)){let s=o.match(/^\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)\r?\n$/);if(!s)continue;let[,c,i]=s,a=c.match(/\bname="([^"]*)"/i)?.[1];a!==void 0&&(r[a]=/\bfilename="/i.test(c)?{type:"string",format:"binary"}:j(i))}if(Object.keys(r).length!==0)return{type:"object",properties:r,required:Object.keys(r)}}function ge(e){let t=I(e.contentType);if(e.bodyJson!==void 0)return{mime:ue(t)?t:"application/json",schema:j(e.bodyJson)};if(t===de&&e.bodyText){let r={};for(let[o,s]of new URLSearchParams(e.bodyText))r[o]=s;return Object.keys(r).length===0?void 0:{mime:de,schema:j(r)}}if(t===le&&e.bodyText){let r=nt(e.bodyText,e.contentType);return r?{mime:le,schema:r}:void 0}let n=tt(e.bodyText);if(n!==void 0)return{mime:"application/json",schema:j(n)}}function ye(e,t,n){let r=e.get(t);e.set(t,r?J([r,n]):n)}async function we(e){let t=await C(e.trafficPath);if(t.length===0)throw new Error("No traffic files found in the provided traffic path.");let n=_(e.server),r=new Map,o=new Set,s=0,c=a=>{let p=a.request.method.toLowerCase();if(!X.has(p))return;let f=a.request.path||"/";if(n){let u=B(a.request,n);if(u===void 0)return;f=u}else a.request.host&&!fe(a.request.host)&&o.add(`${a.request.protocol}//${a.request.host}`);let{template:m,params:d}=Z(N(f)),P=`${p} ${m}`,h=r.get(P);h||(h={method:p,template:m,pathParams:new Map,queryParams:new Map,requestBodies:new Map,responses:new Map},r.set(P,h));for(let{name:u,value:l}of d){let y=h.pathParams.get(u);h.pathParams.set(u,{numeric:(y?.numeric??!0)&&F.test(l),observations:q(y?.observations,D(l))})}for(let u of new Set(a.request.query.keys())){let l=a.request.query.getAll(u),y=h.queryParams.get(u),T=l.length>0&&l.every(b=>F.test(b)),R=y?.observations;for(let b of l)R=q(R,D(b));h.queryParams.set(u,{numeric:(y?.numeric??!0)&&T,observations:R})}if(!Le.has(p)){let u=ge(a.request);u&&ye(h.requestBodies,u.mime,u.schema)}if(a.response&&a.response.status>=100){let u=String(a.response.status),l=h.responses.get(u);l||(l={bodies:new Map},h.responses.set(u,l)),l.statusText??=a.response.statusText||void 0;let y=ge(a.response);y&&ye(l.bodies,y.mime,y.schema)}};for(let a of t){let p=await G(a,e.format);if(!p){S.warn(`Skipping traffic file with unrecognized format: ${a}
|
|
8
8
|
`);continue}s+=1;for await(let f of p.parse(a))c(f)}if(s===0)throw new Error("No supported traffic files found to generate an OpenAPI description from.");if(r.size===0)throw new Error(n?`No HTTP exchanges in the traffic matched the server "${n}".`:"No HTTP exchanges were observed in the traffic. Cannot generate an OpenAPI description.");let i=n?[n]:Array.from(o).sort();return rt(r,e.title??"Generated API",i)}function Pe(e){return Object.values(e.paths).reduce((t,n)=>t+Object.keys(n).length,0)}function Se(e,t){if(e.numeric)return{type:"integer"};let n={type:"string"};return e.observations&&Object.assign(n,K(e.observations,t)),n}function rt(e,t,n){let r={};for(let o of e.values()){let s=r[o.template]??={},c=[...Array.from(o.pathParams).map(([a,p])=>({name:a,in:"path",required:!0,schema:Se(p,!1)})),...Array.from(o.queryParams).map(([a,p])=>({name:a,in:"query",required:!1,schema:Se(p,!0)}))],i={operationId:ot(o.method,o.template),responses:{}};if(c.length>0&&(i.parameters=c),o.requestBodies.size>0){let a={};for(let[p,f]of o.requestBodies)a[p]={schema:f};i.requestBody={content:a}}if(o.responses.size===0)i.responses.default={description:"Observed response"};else for(let[a,p]of o.responses){let f={description:p.statusText||"Observed response"};if(p.bodies.size>0){let m={};for(let[d,P]of p.bodies)m[d]={schema:P};f.content=m}i.responses[a]=f}s[o.method]=i}return{openapi:"3.2.0",info:{title:t,version:"1.0.0"},...n.length>0?{servers:n.map(o=>({url:o}))}:{},paths:r}}function ot(e,t){let n=t.split("/").filter(Boolean).map(r=>r.replace(/[{}]/g,"")).join("-");return`${e}-${n||"root"}`}function L(e,t){return`${e.toUpperCase()} ${t}`}function Te(e,t){let n;if(e.bodyJson!==void 0)try{n=JSON.stringify(e.bodyJson)}catch{n=void 0}if(n??=e.bodyText,!n)return;let r=n.trim();if(r)return r.length>t?`${r.slice(0,t)}\u2026[truncated]`:r}function $e(e){if(!e)return"";let t=e.bodyJson;return t===void 0?e.bodyText?I(e.contentType)||"text":"":t===null?"null":Array.isArray(t)?`array<${t.length>0?je(t[0]):""}>`:je(t)}function je(e){return g(e)?Object.keys(e).sort().join(","):e===null?"null":typeof e}async function ke(e){let t=e.perGroup??2,n=e.perOperation??4,r=e.maxBodyChars??2e3,o=_(e.server),s=await C(e.trafficPath),c=new Map;for(let a of s){let p=await G(a,e.format);if(p)for await(let f of p.parse(a)){let m=f.request.method.toUpperCase();if(!X.has(m.toLowerCase()))continue;let d=f.request.path||"/";if(o){let ne=B(f.request,o);if(ne===void 0)continue;d=ne}let P=N(d),{template:h}=Z(P),u=f.response&&f.response.status>=100?f.response:void 0,l=u?.status,y=`${$e(f.request)}\u2192${$e(u)}`,T=c.get(L(m,h));T||(T=new Map,c.set(L(m,h),T));let R=`${l??""} ${y}`,b=T.get(R);b||(b=[],T.set(R,b)),!(b.length>=t)&&b.push({method:m,path:P,query:f.request.query.toString(),status:l,requestContentType:f.request.contentType,requestBody:Te(f.request,r),responseContentType:u?.contentType,responseBody:u?Te(u,r):void 0})}}let i=new Map;for(let[a,p]of c){let f=[];for(let m=0;m<t&&f.length<n;m++)for(let d of p.values()){if(f.length>=n)break;d[m]&&f.push(d[m])}i.set(a,f)}return i}var st=`You are an expert API designer. You are given one operation from an OpenAPI 3.2 description that was inferred mechanically from recorded HTTP traffic, the component schemas it references, and a sample of the real recorded HTTP exchanges for that operation. The inferred description is only a hypothesis: types are coarse, every observed property is marked required, and descriptions are missing. Alternative body shapes observed in the traffic appear as "oneOf" variants or type unions. Common string formats (uuid, date-time, date, email, uri, ipv4) and small closed enums are detected conservatively from the observed values.
|
|
9
9
|
|
|
10
10
|
Refine the operation into the most accurate OpenAPI 3.2 definition you can justify from the evidence, while staying conservative:
|
|
@@ -43,7 +43,7 @@ ${e.reservedComponentNames.join(", ")}`),t.push(`# Recorded HTTP exchanges for t
|
|
|
43
43
|
|
|
44
44
|
${it(e.samples)}`),t.push(`Refine ${e.method.toUpperCase()} ${e.path} as instructed and output only the YAML document.`),{system:st,user:t.join(`
|
|
45
45
|
|
|
46
|
-
`)}}var Re=/^#\/components\/schemas\/(.+)$/;function Q(e,t){if(Array.isArray(e)){for(let n of e)Q(n,t);return}if(g(e)){if(typeof e.$ref=="string"){let n=e.$ref.match(Re);n&&t.add(n[1])}if(g(e.discriminator)&&g(e.discriminator.mapping)){for(let n of Object.values(e.discriminator.mapping))if(typeof n=="string"){let r=n.match(Re);t.add(r?r[1]:n)}}for(let n of Object.values(e))Q(n,t)}}function Je(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=new Set;Q(r.pop(),o);for(let s of o)!n.has(s)&&s in t&&(n.add(s),r.push(t[s]))}return n}function at(e){let t=e.components?.schemas;if(!t)return;let n=Je(e.paths,t);for(let r of Object.keys(t))n.has(r)||delete t[r];Object.keys(t).length===0&&delete e.components}function ct(e,t,n){let r=
|
|
46
|
+
`)}}var Re=/^#\/components\/schemas\/(.+)$/;function Q(e,t){if(Array.isArray(e)){for(let n of e)Q(n,t);return}if(g(e)){if(typeof e.$ref=="string"){let n=e.$ref.match(Re);n&&t.add(n[1])}if(g(e.discriminator)&&g(e.discriminator.mapping)){for(let n of Object.values(e.discriminator.mapping))if(typeof n=="string"){let r=n.match(Re);t.add(r?r[1]:n)}}for(let n of Object.values(e))Q(n,t)}}function Je(e,t){let n=new Set,r=[e];for(;r.length>0;){let o=new Set;Q(r.pop(),o);for(let s of o)!n.has(s)&&s in t&&(n.add(s),r.push(t[s]))}return n}function at(e){let t=e.components?.schemas;if(!t)return;let n=Je(e.paths,t);for(let r of Object.keys(t))n.has(r)||delete t[r];Object.keys(t).length===0&&delete e.components}function ct(e,t,n){let r=ae(e),o;try{o=re(r)}catch(f){throw new Error(`the provider did not return valid YAML: ${f instanceof Error?f.message:String(f)}`)}if(!g(o))throw new Error('the response is not a YAML document with a "paths" object');let s=o.paths;if(!g(s))throw new Error('the response is not a YAML document with a "paths" object');let c=s[t];if(!g(c))throw new Error(`the response does not keep the path template "${t}"`);let i=c[n];if(!g(i))throw new Error(`the response does not contain the ${n.toUpperCase()} operation`);let a=o.components,p=g(a)?a.schemas:void 0;return{operation:i,components:g(p)?p:{}}}function pt(e,t){let n=g(t.responses)?t.responses:{};return Object.keys(e.responses).filter(r=>!(r in n))}async function ft(e){let t=e.document.components?.schemas??{},n=Je(e.operation,t),r={};for(let d of n)r[d]=t[d];let o=Object.keys(t).filter(d=>!n.has(d)),{system:s,user:c}=Ae({path:e.path,method:e.method,operation:e.operation,components:r,reservedComponentNames:o,samples:e.samples}),{text:i}=await ce(e.provider,{system:s,user:c,model:e.model}),a=ct(i,e.path,e.method),p=pt(e.operation,a.operation);if(p.length>0)throw new Error(`the response dropped observed response status(es): ${p.join(", ")}`);if(typeof a.operation.operationId!="string")throw new Error("the response dropped the operationId");let f=Object.keys(a.components).filter(d=>o.includes(d));if(f.length>0)throw new Error(`the response redefines reserved component(s): ${f.join(", ")}`);let m={openapi:e.document.openapi,info:e.document.info,paths:{[e.path]:{[e.method]:a.operation}},components:{schemas:{...t,...a.components}}};return await Y(v(m),e.config),a}function ut(e,t,n,r){e.paths[t][n]=r.operation,Object.keys(r.components).length>0&&(e.components??={schemas:{}},Object.assign(e.components.schemas,r.components))}async function Ee(e){let t=structuredClone(e.baseline),n=await se({extends:["spec"]}),r=[];for(let[i,a]of Object.entries(e.baseline.paths))for(let[p,f]of Object.entries(a))r.push({path:i,method:p,operation:f});let s=(await pe({items:r,concurrency:e.concurrency??1,action:"Refining",successNote:"refined",failureNote:"kept the baseline",label:({path:i,method:a})=>`${a.toUpperCase()} ${i}`,run:async({path:i,method:a,operation:p})=>{let f=await ft({provider:e.provider,model:e.model,document:t,path:i,method:a,operation:p,samples:e.samplesByOperation.get(L(a,i))??[],config:n});return ut(t,i,a,f),f}})).filter(i=>i!==null).length;if(s===0)throw new Error(`the ${e.provider} provider did not produce a usable refinement for any operation`);at(t);let c=v(t);return await Y(c,n),{yaml:c,document:t,refined:s,total:r.length}}var mt=2,dt=2,lt=.75,ht=2,Me=new Set(["integer","number"]),qe=new WeakMap;function w(e){let t=qe.get(e);if(t!==void 0)return t;let n;if(e.$ref!==void 0)n=`ref(${e.$ref})`;else if(e.oneOf)n=`oneOf(${e.oneOf.map(w).sort().join("|")})`;else{let o=[`type=${(Array.isArray(e.type)?[...e.type].sort().join(","):e.type)??""}`];if(e.properties){let s=Object.entries(e.properties).map(([c,i])=>`${JSON.stringify(c)}:${w(i)}`).sort().join(",");o.push(`props{${s}}`)}e.additionalProperties&&o.push(`values(${w(e.additionalProperties)})`),e.items&&o.push(`items(${w(e.items)})`),n=o.join(";")}return qe.set(e,n),n}function gt(e){return e.$ref===void 0&&e.type==="object"&&e.oneOf===void 0&&e.additionalProperties===void 0&&Object.keys(e.properties??{}).length>=mt}function xe(e,t){for(let n of t)e.set(n,(e.get(n)??0)+1)}function E(e,t,n){if(e.oneOf){e.oneOf.forEach((s,c)=>E(s,{...t,path:`${t.path}/oneOf/${c}`,fallbackHints:[]},n));return}let r=t.container,o=`${t.path}/`;if(gt(e)){let s=w(e),c=n.get(s);c||(c={keys:[s],schemas:[],merged:{},contexts:new Set,primaryVotes:new Map,fallbackVotes:new Map},n.set(s,c)),c.schemas.push(e),c.contexts.add(`${t.container}#${t.path}`),xe(c.primaryVotes,t.primaryHints),xe(c.fallbackVotes,t.fallbackHints),r=s,o=""}for(let[s,c]of Object.entries(e.properties??{}))E(c,{container:r,path:`${o}${s}`,primaryHints:[s],fallbackHints:[]},n);e.additionalProperties&&E(e.additionalProperties,{container:r,path:`${o}additionalProperties`,primaryHints:t.primaryHints.map(s=>O(s,1)),fallbackHints:t.fallbackHints.map(s=>O(s,1))},n),e.items&&E(e.items,{container:r,path:`${o}items`,primaryHints:t.primaryHints.map(s=>O(s,1)),fallbackHints:t.fallbackHints.map(s=>O(s,1))},n)}function yt(e){return e.split("/").filter(n=>n&&!n.startsWith("{")).at(-1)}function St(e){let t=new Map;for(let[n,r]of Object.entries(e.paths)){let o=yt(n),s=o?O(o,1):void 0;for(let[c,i]of Object.entries(r)){for(let[a,p]of Object.entries(i.requestBody?.content??{}))E(p.schema,{container:`request ${c} ${n} ${a}`,path:"",primaryHints:s?[s]:[],fallbackHints:s?[`${s} request`]:[]},t);for(let[a,p]of Object.entries(i.responses)){let f=Number(a)>=400;for(let[m,d]of Object.entries(p.content??{}))E(d.schema,{container:`response ${c} ${n} ${a} ${m}`,path:"",primaryHints:f?["error"]:s?[s]:[],fallbackHints:f?s?[`${s} error`]:[]:s?[`${s} response`]:[]},t)}}}return t}function Ce(e){return Object.keys(e.properties??{})}function bt(e,t){let n=Ce(e),r=new Set(Ce(t)),o=n.filter(c=>r.has(c)).length,s=n.length+r.size-o;return s===0?0:o/s}function Ne(e){if(e.$ref!==void 0||e.properties||e.additionalProperties||e.items||e.oneOf)return;let t=typeof e.type=="string"?[e.type]:e.type;if(!(!t||t.some(n=>n==="object"||n==="array")))return t}function ee(e){return Object.keys(e).length===0}function Ge(e,t){if(w(e)===w(t)||ee(e)||ee(t))return!0;let n=Ne(e),r=Ne(t);if(n&&r){let s=new Set(n.filter(i=>i!=="null")),c=new Set(r.filter(i=>i!=="null"));return s.size===c.size&&[...s].every(i=>c.has(i))?!0:[...s].every(i=>Me.has(i))&&[...c].every(i=>Me.has(i))}let o=s=>s.type==="array"||s.items!==void 0;return o(e)&&o(t)?!e.items||!t.items||Ge(e.items,t.items):!1}function Ot(e,t){let n=t.merged.properties??{};return Object.entries(e.merged.properties??{}).every(([r,o])=>!(r in n)||Ge(o,n[r]))}function vt(e){let t=[...e];for(;t.length>1;){let n=-1,r=-1,o=0;for(let i=0;i<t.length;i++)for(let a=i+1;a<t.length;a++){let p=bt(t[i].merged,t[a].merged);p>=lt&&p>o&&Ot(t[i],t[a])&&(o=p,n=i,r=a)}if(n===-1)break;let s=t[n],c=t[r];s.keys.push(...c.keys),s.schemas.push(...c.schemas),s.merged=J([s.merged,c.merged]);for(let i of c.contexts)s.contexts.add(i);for(let[i,a]of c.primaryVotes)s.primaryVotes.set(i,(s.primaryVotes.get(i)??0)+a);for(let[i,a]of c.fallbackVotes)s.fallbackVotes.set(i,(s.fallbackVotes.get(i)??0)+a);t.splice(r,1)}return t}function te(e,t){return e<t?-1:e>t?1:0}function wt(e){return e.split(/[^a-zA-Z0-9]+/).filter(Boolean).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function Ie(e){return[...e.entries()].sort(([t,n],[r,o])=>o-n||te(t,r)).map(([t])=>t)}function Pt(e){let t=[...e].sort((r,o)=>o.contexts.size-r.contexts.size||o.schemas.length-r.schemas.length||te(r.keys[0],o.keys[0])),n=new Set;return t.map(r=>{let o=[...Ie(r.primaryVotes),...Ie(r.fallbackVotes)].map(wt).filter(c=>c.length>0);o.length===0&&o.push("Schema");let s=o.find(c=>!n.has(c));for(let c=2;s===void 0;c++){let i=`${o[0]}${c}`;n.has(i)||(s=i)}return n.add(s),{group:r,name:s}})}function A(e,t,n=!1){if(!n){let o=t.get(w(e));if(o!==void 0)return{$ref:`#/components/schemas/${o}`}}let r={...e};return V(e,r),e.properties&&(r.properties=Object.fromEntries(Object.entries(e.properties).map(([o,s])=>[o,A(s,t)]))),e.additionalProperties&&(r.additionalProperties=A(e.additionalProperties,t)),e.items&&(r.items=A(e.items,t)),e.oneOf&&(r.oneOf=e.oneOf.map(o=>A(o,t))),r}function Tt(e){let t=Object.values(e.properties??{}),n=t.filter(r=>r.type==="array"&&(!r.items||ee(r.items)));return n.length>0&&t.length-n.length<=ht}function $t(e){let t=0,n=0;for(let r of e.primaryVotes.values())t+=r,n=Math.max(n,r);return n*2>t}function _e(e){let t=St(e);for(let i of t.values())i.merged=J(i.schemas);let r=vt([...t.values()]).filter(i=>i.contexts.size>=dt&&($t(i)||!i.schemas.some(Tt)));if(r.length===0)return e;let o=Pt(r),s=new Map;for(let{group:i,name:a}of o)for(let p of i.keys)s.set(p,a);let c={};for(let{group:i,name:a}of[...o].sort((p,f)=>te(p.name,f.name)))c[a]=A(i.merged,s,!0);for(let i of Object.values(e.paths))for(let a of Object.values(i)){for(let p of Object.values(a.requestBody?.content??{}))p.schema=A(p.schema,s);for(let p of Object.values(a.responses))for(let f of Object.values(p.content??{}))f.schema=A(f.schema,s)}return e.components={schemas:c},e}async function Rt(e,t){let n=x(e);await jt(At.dirname(n),{recursive:!0}),await kt(n,t,"utf8")}function Jt(e){let t=Math.round(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}async function gn({argv:e}){if(e.type!=="openapi")throw new oe(`Unsupported spec type "${e.type}". Only "openapi" is supported.`);let t=Date.now(),n=x(e.traffic),r=e["traffic-format"],o=me(_e(await we({trafficPath:n,format:r,title:e.title,server:e.server})));S.info(`Inferred a baseline OpenAPI description from traffic: ${Pe(o)} operation(s).
|
|
47
47
|
`);let s=v(o);if(e["with-ai"]){let c=e["ai-provider"];S.info(`Refining the description with AI provider "${c}"...
|
|
48
48
|
`),S.warn(`Note: --with-ai sends samples of the recorded traffic (URLs, query strings, request and response bodies) to the selected AI provider. Make sure the traffic contains no secrets or personal data you are not allowed to share.
|
|
49
49
|
`);let i=await ke({trafficPath:n,format:r,server:e.server});try{let a=await Ee({provider:c,model:e["ai-model"],baseline:o,samplesByOperation:i,concurrency:e["ai-concurrency"]});s=a.yaml,S.info(`AI refinement complete: ${a.refined} of ${a.total} operation(s) refined (${c}).
|
|
@@ -4,4 +4,4 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a}from"./
|
|
7
|
+
import{a}from"./F5V42ZYY.js";import"./J3DL5HGI.js";import"./JMFIKCPX.js";import"./VIPV4IEH.js";import"./65AQJO4M.js";import"./WZXA5XPB.js";import"./M4YE5ALG.js";import"./NEWT5A6S.js";import"./LD5MEXEL.js";import"./UW4UC7ZI.js";import"./RFWIIJFG.js";export{a as tanstackQueryGenerator};
|