@redocly/cli 2.47.0 → 2.48.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/lib/chunks/{TEQA5OM7.js → 2GJPOM5H.js} +1 -1
- package/lib/chunks/{W2NJCZOS.js → 3CR6IHZV.js} +1 -1
- package/lib/chunks/3JJEI7CJ.js +456 -0
- package/lib/chunks/{QRD3XQNU.js → 3M6ARSHY.js} +1 -1
- package/lib/chunks/3X52NOC5.js +7 -0
- package/lib/chunks/46OWEERC.js +19 -0
- package/lib/chunks/4IA3ZTGK.js +20 -0
- package/lib/chunks/{TO2KJ36N.js → 5E3L4HJN.js} +1 -1
- package/lib/chunks/5EG7SNNU.js +177 -0
- package/lib/chunks/5L3FH5WQ.js +16 -0
- package/lib/chunks/5L5WOOWA.js +7 -0
- package/lib/chunks/5ZEWVWOC.js +14 -0
- package/lib/chunks/6O3ZHZZ2.js +7 -0
- package/lib/chunks/{KEUH3PST.js → AJZAID3R.js} +1 -1
- package/lib/chunks/BD5JG7YZ.js +7 -0
- package/lib/chunks/{B6HS7CVY.js → BEOYUN4L.js} +48 -48
- package/lib/chunks/CF5YCHNA.js +7 -0
- package/lib/chunks/D27SC2KR.js +90 -0
- package/lib/chunks/{SN2EC2ZR.js → DYAVWTVD.js} +1 -1
- package/lib/chunks/E35Q6YJN.js +7 -0
- package/lib/chunks/EB2V4VMP.js +7 -0
- package/lib/chunks/{QVV2EKMT.js → FL3CA53Z.js} +1 -1
- package/lib/chunks/FVBSRIWC.js +18 -0
- package/lib/chunks/G2XR6TRU.js +67 -0
- package/lib/chunks/G3YJARF7.js +57 -0
- package/lib/chunks/GA6WYGKY.js +7 -0
- package/lib/chunks/GBRES7WG.js +5400 -0
- package/lib/chunks/GHPAE4DZ.js +20 -0
- package/lib/chunks/{SL6AH3N2.js → GJRJZYC4.js} +1 -1
- package/lib/chunks/{REBHK2JR.js → GOJNDGZT.js} +1 -1
- package/lib/chunks/HJYFWIVE.js +9 -0
- package/lib/chunks/HLZCPNF7.js +16 -0
- package/lib/chunks/KIQI3UBS.js +177 -0
- package/lib/chunks/KNPQJVYA.js +14 -0
- package/lib/chunks/L3TZNNJJ.js +13 -0
- package/lib/chunks/{34J2ZJDK.js → LUC2DWUK.js} +1 -1
- package/lib/chunks/MBHFDTYI.js +78 -0
- package/lib/chunks/NB54XRRU.js +10 -0
- package/lib/chunks/NSIQWNYL.js +7 -0
- package/lib/chunks/NWMTC4AN.js +7 -0
- package/lib/chunks/PFYPTG4G.js +7 -0
- package/lib/chunks/{5NR4DJW4.js → PVM7EVWV.js} +1 -1
- package/lib/chunks/Q5FNL2RM.js +22 -0
- package/lib/chunks/QW5MTOU2.js +22 -0
- package/lib/chunks/REFX2EKS.js +13 -0
- package/lib/chunks/S4GQKQ5G.js +7 -0
- package/lib/chunks/SGBB4RNM.js +11 -0
- package/lib/chunks/{YQW463Z7.js → SPPRUUK3.js} +1 -1
- package/lib/chunks/SQVG3CEM.js +8 -0
- package/lib/chunks/TSB6PODJ.js +13 -0
- package/lib/chunks/U2A6GEAN.js +42 -0
- package/lib/chunks/UDBINQ2S.js +42 -0
- package/lib/chunks/UKSQ7B5H.js +2268 -0
- package/lib/chunks/{QL4V2A4A.js → V3JMSQFP.js} +1 -1
- package/lib/chunks/VWSPU27A.js +30 -0
- package/lib/chunks/W62VKXGM.js +26 -0
- package/lib/chunks/WIZYCYZG.js +7 -0
- package/lib/chunks/XDK4JK3V.js +9 -0
- package/lib/chunks/{5PXRDPHV.js → YJGI7CZ2.js} +1 -1
- package/lib/chunks/YQS3OX36.js +11 -0
- package/lib/chunks/{S4MX7JPH.js → Z2AXUXMK.js} +1 -1
- package/lib/chunks/ZBL4IVEW.js +11 -0
- package/lib/chunks/ZGMTMVBB.js +19 -0
- package/lib/chunks/{RIFZSMUA.js → ZVUMPMHU.js} +1 -1
- package/lib/eject-assets/AGENTS.md +137 -0
- package/lib/eject-assets/generators/cli/docs.ts +224 -0
- package/lib/eject-assets/generators/cli/engine-source.ts +21 -0
- package/lib/eject-assets/generators/cli/index.ts +90 -0
- package/lib/eject-assets/generators/cli/render.ts +348 -0
- package/lib/eject-assets/generators/go/client.ts +57 -0
- package/lib/eject-assets/generators/go/descriptor.ts +41 -0
- package/lib/eject-assets/generators/go/index.ts +336 -0
- package/lib/eject-assets/generators/go/models.ts +179 -0
- package/lib/eject-assets/generators/go/naming.ts +49 -0
- package/lib/eject-assets/generators/go/operations.ts +296 -0
- package/lib/eject-assets/generators/go/pagination.ts +194 -0
- package/lib/eject-assets/generators/go/types.ts +60 -0
- package/lib/eject-assets/generators/mock/faker.ts +214 -0
- package/lib/eject-assets/generators/mock/index.ts +35 -0
- package/lib/eject-assets/generators/mock/render.ts +282 -0
- package/lib/eject-assets/generators/mock/sample.ts +316 -0
- package/lib/eject-assets/generators/mock/values.ts +63 -0
- package/lib/eject-assets/generators/php/client.ts +63 -0
- package/lib/eject-assets/generators/php/descriptor.ts +58 -0
- package/lib/eject-assets/generators/php/index.ts +237 -0
- package/lib/eject-assets/generators/php/models.ts +275 -0
- package/lib/eject-assets/generators/php/naming.ts +51 -0
- package/lib/eject-assets/generators/php/operations.ts +232 -0
- package/lib/eject-assets/generators/php/pagination.ts +133 -0
- package/lib/eject-assets/generators/php/types.ts +148 -0
- package/lib/eject-assets/generators/python/client.ts +123 -0
- package/lib/eject-assets/generators/python/descriptor.ts +52 -0
- package/lib/eject-assets/generators/python/index.ts +251 -0
- package/lib/eject-assets/generators/python/models.ts +242 -0
- package/lib/eject-assets/generators/python/naming.ts +46 -0
- package/lib/eject-assets/generators/python/operations.ts +147 -0
- package/lib/eject-assets/generators/python/pagination.ts +128 -0
- package/lib/eject-assets/generators/python/types.ts +54 -0
- package/lib/eject-assets/generators/swr/index.ts +37 -0
- package/lib/eject-assets/generators/swr/render.ts +78 -0
- package/lib/eject-assets/generators/tanstack-query/index.ts +48 -0
- package/lib/eject-assets/generators/tanstack-query/render.ts +346 -0
- package/lib/eject-assets/generators/transformers/index.ts +46 -0
- package/lib/eject-assets/generators/transformers/render.ts +506 -0
- package/lib/eject-assets/generators/typescript/banner.ts +35 -0
- package/lib/eject-assets/generators/typescript/client.ts +254 -0
- package/lib/eject-assets/generators/typescript/descriptor.ts +137 -0
- package/lib/eject-assets/generators/typescript/index.ts +101 -0
- package/lib/eject-assets/generators/typescript/inline-runtime.ts +135 -0
- package/lib/eject-assets/generators/typescript/operation-signature.ts +62 -0
- package/lib/eject-assets/generators/typescript/operation-types.ts +17 -0
- package/lib/eject-assets/generators/typescript/operations.ts +524 -0
- package/lib/eject-assets/generators/typescript/response-headers.ts +74 -0
- package/lib/eject-assets/generators/typescript/type-guards.ts +159 -0
- package/lib/eject-assets/generators/typescript/types.ts +172 -0
- package/lib/eject-assets/generators/zod/index.ts +32 -0
- package/lib/eject-assets/generators/zod/schemas.ts +456 -0
- package/lib/eject-assets/skills/cli-generator/SKILL.md +121 -0
- package/lib/eject-assets/skills/client-generators/SKILL.md +142 -0
- package/lib/eject-assets/skills/go-generator/SKILL.md +96 -0
- package/lib/eject-assets/skills/mock-generator/SKILL.md +50 -0
- package/lib/eject-assets/skills/php-generator/SKILL.md +112 -0
- package/lib/eject-assets/skills/python-generator/SKILL.md +110 -0
- package/lib/eject-assets/skills/swr-generator/SKILL.md +50 -0
- package/lib/eject-assets/skills/tanstack-query-generator/SKILL.md +55 -0
- package/lib/eject-assets/skills/transformers-generator/SKILL.md +47 -0
- package/lib/eject-assets/skills/typescript-generator/SKILL.md +95 -0
- package/lib/eject-assets/skills/zod-generator/SKILL.md +54 -0
- package/lib/index.js +272 -193
- package/package.json +1 -1
- package/lib/chunks/PIJLRHNN.js +0 -8
- package/lib/chunks/Y5HLCNL5.js +0 -2542
|
@@ -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{la as e}from"./
|
|
7
|
+
import{la as e}from"./BEOYUN4L.js";var t=class extends Error{};function o(r){throw new e(r)}export{t as a,o as b};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{d as a,e as b,f as c}from"./D27SC2KR.js";import"./UKSQ7B5H.js";import"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";export{b as typescriptDocs,a as typescriptGenerator,c as typescriptSample};
|
|
@@ -0,0 +1,19 @@
|
|
|
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 R}from"./SQVG3CEM.js";import{c as L}from"./UKSQ7B5H.js";import{b as J,c as E,d as F,e as W,f as ne,g as B,h as te}from"./YQS3OX36.js";import{c as z,d as w,e as A,g as U,h as C,i as Q,j as X,k as Z,n as ee}from"./HJYFWIVE.js";var k=z.python,f=new R;function O(e){return f.typeName(e)}function q(e){let{identifier:n,renamed:s}=f.memberName(e);return{python:n,renamed:s}}function I(e){let n=e.services.flatMap(t=>t.operations),s=A(n.map(t=>t.name),{style:"snake",reserved:k});return n.map((t,r)=>({op:t,ident:s[r]}))}var T=["self","body","headers","timeout","retry","idempotency_key"];function se(e){return f.literal(e)}function oe(e){if(e!==void 0)return{style:e.style,...e.param!==void 0?{param:e.param}:{},...e.nextCursor!==void 0?{next_cursor:e.nextCursor}:{},...e.hasMore!==void 0?{has_more:e.hasMore}:{},...e.limitParam!==void 0?{limit_param:e.limitParam}:{},...e.items!==void 0?{items:e.items}:{}}}function ae(e,n){let s=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let a=w(r.name,{style:"snake",reserved:k}),c=a,i=2;for(;s.has(c);)c=`${a}_${i++}`;s.add(c);let m=ee(r.schema,n);return`(${f.string(r.name)}, ${f.string(c)}, ${f.string(m)})`}).join(", ")}]`}function y(e,n="string"){if(Q(e))return`Optional[${y(X(e),n)}]`;switch(e.kind){case"scalar":if(n==="Date"&&e.scalar==="string"){if(e.metadata?.format==="date-time")return"datetime";if(e.metadata?.format==="date")return"date"}return{string:"str",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":return`List[${y(e.items,n)}]`;case"record":return`Dict[str, ${y(e.value,n)}]`;case"ref":return O(e.name);case"literal":return`Literal[${f.literal(e.value)}]`;case"enum":return{string:"str",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"union":return`Union[${e.members.map(s=>y(s,n)).join(", ")}]`;case"null":return"None";case"omit":return O(e.base);case"object":case"intersection":case"unknown":return"Any"}}function H(e,n,s,t,r,a,c,i=!1){let m=A([...n.pathParams,...n.queryParams].map(N=>N.name),{style:"snake",reserved:k,taken:T}),l=n.pathParams.map((N,S)=>({param:N,python:m[S]})),o=n.queryParams.map((N,S)=>({param:N,python:m[n.pathParams.length+S]})),p=l.map(({param:N,python:S})=>`${S}: ${y(N.schema,a)}`),u=n.requestBody?[`body: ${y(n.requestBody.schema,a)}`]:[],$=[...o.map(({param:N,python:S})=>{let D=y(N.schema,a),j=D.startsWith("Optional[")?D:`Optional[${D}]`;return`${S}: ${j} = None`}),"headers: Optional[Dict[str, str]] = None","timeout: Optional[float] = None","retry: Optional[Dict[str, Any]] = None","idempotency_key: Any = None"],h=E(n),g=F(n),v=i?`Envelope[${h===void 0?"None":y(h,a)}]`:g!==void 0?`${r?"AsyncIterator":"Iterator"}[ServerSentEvent]`:t==="result"?"Result":h===void 0?"None":y(h,a),P=r&&g===void 0?"async def":"def",d=r?"await ":"",_=r?"send_async":"send",b=["self",...p,...u,"*",...$].join(", "),x=i?`${s}_with_headers`:s;e.block(`${P} ${x}(${b}) -> ${v}:`,()=>{e.doc(i?`Like ${s}(), returning an Envelope with the declared response headers.`:n.summary),e.line(`op = _OPERATIONS["${s}"]`),e.line('auth_headers, auth_query = resolve_auth(op.get("security") or [], self._auth)'),e.line("params: Dict[str, Any] = dict(auth_query)");for(let{param:j,python:M}of o)e.block(`if ${M} is not None:`,()=>{e.line(`params[${f.string(j.name)}] = encode(${M})`)});let N=l.map(({param:j,python:M})=>`${f.string(j.name)}: ${M}`).join(", ");if(e.line(`url = build_url(self._server_url, op["path"], {${N}})`),g!==void 0){let j=g.schema!==void 0&&g.schema.kind!=="unknown"?"json":"text";e.block("def _open(extra_headers: Dict[str, str]):",()=>{e.line('return self._http.stream(op["method"], url, headers={**auth_headers, **(headers or {}), **extra_headers}, params=params, timeout=timeout)')}),e.line(`return ${r?"aiter_sse":"iter_sse"}(_open, data_kind="${j}")`);return}W(n)&&e.line("form_data, form_files = to_multipart(body)");let S=n.requestBody?W(n)?", data=form_data, files=form_files":", json_body=encode(body)":"";e.line(`response = ${d}${_}(self._http, self._config, op, url, method=op["method"], headers={**auth_headers, **(headers or {})}, params=params${S}, timeout=timeout, retry=retry, idempotency_key=idempotency_key)`);let D=h===void 0?"None":`decode(${y(h,a)}, _safe_json(response))`;i?(e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line(`return Envelope(data=${D}, headers=read_envelope_headers(response, ${ae(n,c)}), response=response)`)):t==="result"?(e.block("if not response.is_success:",()=>{e.line("return Result(data=None, error=_safe_json(response), response=response)")}),e.line(`return Result(data=${D}, error=None, response=response)`)):(e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line(h===void 0?"return None":`return ${D}`))}),e.blank()}function re(e,n,s,t,r,a){let c=E(n),i=c===void 0?"Any":y(c,a),m=A([...n.pathParams,...n.queryParams].map(d=>d.name),{style:"snake",reserved:k,taken:T}),l=n.pathParams.map((d,_)=>({param:d,python:m[_]})),o=n.queryParams.map((d,_)=>({param:d,python:m[n.pathParams.length+_]})),p=l.map(({param:d,python:_})=>`${_}: ${y(d.schema,a)}`),u=[...o.map(({param:d,python:_})=>{let b=y(d.schema,a),x=b.startsWith("Optional[")?b:`Optional[${b}]`;return`${_}: ${x} = None`}),"headers: Optional[Dict[str, str]] = None","timeout: Optional[float] = None","retry: Optional[Dict[str, Any]] = None"],$=["self",...p,"*",...u].join(", "),h=t?"AsyncIterator":"Iterator",g=t?"aiter_pages":"iter_pages",v=t?"aiter_items":"iter_items",P=()=>{e.line("base: Dict[str, Any] = {}");for(let{param:b,python:x}of o)e.block(`if ${x} is not None:`,()=>{e.line(`base[${f.string(b.name)}] = encode(${x})`)});let d=t?"async def":"def",_=t?"await ":"";e.block(`${d} _page(page_params: Dict[str, Any]) -> Tuple[Any, Any]:`,()=>{e.line('auth_headers, auth_query = resolve_auth(op.get("security") or [], self._auth)');let b=l.map(({param:x,python:N})=>`${f.string(x.name)}: ${N}`).join(", ");e.line(`url = build_url(self._server_url, op["path"], {${b}})`),e.line(`response = ${_}${t?"send_async":"send"}(self._http, self._config, op, url, method=op["method"], headers={**auth_headers, **(headers or {})}, params={**page_params, **auth_query}, timeout=timeout, retry=retry)`),e.block("if not response.is_success:",()=>{e.line("raise ApiError(url, response.status_code, response.reason_phrase, _safe_json(response))")}),e.line("return _safe_json(response), response")})};t?(e.block(`async def ${s}_pages(${$}) -> ${h}[${i}]:`,()=>{e.line(`op = _OPERATIONS["${s}"]`),P(),e.block(`async for page in ${g}(_page, op["pagination"], base):`,()=>{e.line(i==="Any"?"yield page":`yield decode(${i}, page)`)})}),e.blank(),e.block(`async def ${s}_items(${$}) -> ${h}[${r}]:`,()=>{e.line(`op = _OPERATIONS["${s}"]`),P(),e.block(`async for item in ${v}(_page, op["pagination"], base):`,()=>{e.line(r==="Any"?"yield item":`yield decode(${r}, item)`)})})):(e.block(`def ${s}_pages(${$}) -> ${h}[${i}]:`,()=>{e.line(`op = _OPERATIONS["${s}"]`),P(),e.line(i==="Any"?`return ${g}(_page, op["pagination"], base)`:`return (decode(${i}, page) for page in ${g}(_page, op["pagination"], base))`)}),e.blank(),e.block(`def ${s}_items(${$}) -> ${h}[${r}]:`,()=>{e.line(`op = _OPERATIONS["${s}"]`),P(),e.line(r==="Any"?`return ${v}(_page, op["pagination"], base)`:`return (decode(${r}, item) for item in ${v}(_page, op["pagination"], base))`)})),e.blank()}function le(e){return ne(e).map(s=>s.kind==="literal"?f.string(s.value):q(s.name).python).join(" + ")}function ie(e,n){let s=n.servers??[];if(s.length===0)return;let t=new Set;e.block("class Servers:",()=>{e.line('"""The declared servers; variables default to the values from the description."""'),e.blank(),s.forEach((r,a)=>{let c=w(r.description??`server${a+1}`,{style:"snake",reserved:k});t.has(c)&&(c=`${c}_${a+1}`),t.add(c);let i=r.variables.map(m=>`${q(m.name).python}: str = ${f.string(m.default)}`);a>0&&e.blank(),e.line("@staticmethod"),e.block(`def ${c}(${i.join(", ")}) -> str:`,()=>{e.line(`return ${le(r)}`)})})}),e.blank()}function K(e,n,s,t,r,a,c){let i=t?"AsyncClient":"Client",m=t?"httpx.AsyncClient":"httpx.Client";e.block(`class ${i}:`,()=>{e.doc(`${t?"Async ":""}client for ${n.title} (${n.version}).`),e.block(`def __init__(self, server_url: str = ${f.string(a)}, *, auth: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout: Optional[float] = None, retry: Optional[Dict[str, Any]] = None, middleware: Optional[List[Any]] = None, idempotency_key: Any = None, http_client: Optional[${m}] = None) -> None:`,()=>{e.line("self._server_url = server_url"),e.line("self._auth = auth or {}"),e.line("self._config: Dict[str, Any] = {"),e.indent(()=>{e.line('"headers": headers or {},'),e.line('"timeout": timeout,'),e.line('"retry": retry or {},'),e.line('"middleware": middleware or [],'),e.line('"idempotency_key": idempotency_key,')}),e.line("}"),e.line(`self._http = http_client or ${m}()`)}),e.blank();for(let{op:l,ident:o}of I(n)){H(e,l,o,s,t,c),F(l)===void 0&&(l.successResponseHeaders?.length??0)>0&&H(e,l,o,s,t,c,n,!0);let p=r.get(o);if(p!==void 0){let u=E(l),$=te(u,typeof p.items=="string"?p.items:void 0,n);re(e,l,o,t,$===void 0?"Any":y($,c),c)}}}),e.blank()}function Y(e){let n=new Map,s=new Set,t=[];for(let{name:a,schema:c}of e.schemas){let i=C(c,e);if(!(i===void 0||!i.cases.every(l=>U(l.schema,e)?.properties.some(o=>o.name===i.property)===!0))){for(let l of i.cases){let o=n.get(l.schemaName);if(o!==void 0&&o.value!==l.value){s.add(l.schemaName);continue}n.set(l.schemaName,{property:i.property,value:l.value})}t.push({name:a,property:i.property,members:i.cases.map(l=>l.schemaName)})}}let r=new Map;for(let a of t)a.members.some(c=>s.has(c))||r.set(a.name,q(a.property).python);for(let a of s)n.delete(a);return{pins:n,unions:r}}function pe(e,n,s,t,r,a,c){let i=r==="pydantic";i||e.line("@dataclass");let m=i?`class ${O(n)}(BaseModel):`:`class ${O(n)}:`;e.block(m,()=>{e.doc(a),i&&(e.line("model_config = ConfigDict(populate_by_name=True)"),e.blank());let l=[...s.filter(p=>p.required),...s.filter(p=>!p.required)],o=[];l.length===0&&e.line("pass");for(let p of l){let{python:u,renamed:$}=q(p.name);$&&!i&&o.push([u,p.name]);let h=$&&i?`alias=${f.string(p.name)}`:void 0,g=c?.property===p.name?`Literal[${f.literal(c.value)}]`:y(p.schema,t);if(p.required){let v=h===void 0?"":` = Field(${h})`;e.line(`${u}: ${g}${v}`)}else{let v=g.startsWith("Optional[")?g:`Optional[${g}]`,P=h===void 0?"None":`Field(default=None, ${h})`;e.line(`${u}: ${v} = ${P}`)}}if(o.length>0){e.blank(),e.line("# Python field name -> wire (JSON) name, for (de)serialization.");let p=o.map(([u,$])=>`"${u}": ${f.string($)}`).join(", ");e.line(`_field_map: ClassVar[Dict[str, str]] = {${p}}`)}}),e.blank(),e.blank()}function G(e,n="string",s="dataclass"){let t=new R,{pins:r,unions:a}=s==="pydantic"?Y(e):{pins:new Map,unions:new Map};t.line("from __future__ import annotations"),t.blank(),s==="dataclass"&&t.line("from dataclasses import dataclass"),t.line("from enum import Enum");let c=["Any","AsyncIterator","Dict","Iterator","List","Literal","Optional","Tuple","Union"];s==="dataclass"&&c.splice(2,0,"ClassVar"),a.size>0&&c.unshift("Annotated"),t.line(`from typing import ${c.join(", ")}`),s==="pydantic"&&t.line("from pydantic import BaseModel, ConfigDict, Field"),n==="Date"&&t.line("from datetime import date, datetime"),t.blank(),t.blank();let i=[];for(let{name:m,schema:l}of e.schemas){let o=Z(l);if(o!==void 0){let p=o.scalar==="string"?"str, Enum":"int, Enum";t.block(`class ${O(m)}(${p}):`,()=>{t.doc(l.description),o.values.forEach((u,$)=>{t.line(`${o.memberNames[$]} = ${f.literal(u)}`)})}),t.blank(),t.blank();continue}if(l.kind==="object"||l.kind==="intersection"){let p=U(l,e);if(p!==void 0){pe(t,m,p.properties,n,s,p.description??l.description,r.get(m));continue}}i.push(()=>{let p=C(l,e);if(p!==void 0){let h=p.cases.map(g=>`${g.value} -> ${O(g.schemaName)}`).join(", ");t.line(`# Discriminated by "${p.property}": ${h}`)}let u=a.get(m),$=u===void 0?y(l,n):`Annotated[${y(l,n)}, Field(discriminator=${f.string(u)})]`;t.line(`${O(m)} = ${$}`),t.blank()})}for(let m of i)m();return t.toString()}function ce(e,n){let s=[];for(let{name:t,schema:r}of e.schemas){if(n.has(t))continue;let a=C(r,e);if(a===void 0)continue;let c=a.cases.map(i=>`${f.string(i.value)}: ${O(i.schemaName)}`).join(", ");s.push(`DISCRIMINATORS[${O(t)}] = (${f.string(a.property)}, {${c}})`)}return s}var Ve={type:"object",properties:{models:{enum:["dataclass","pydantic"],default:"dataclass",description:"Model style: standard-library dataclasses (default, httpx is the only dependency), or pydantic BaseModel classes (adds pydantic)."}},additionalProperties:!1};function V(e){let n=e.lastIndexOf("/")>=0?"/":"\\",s=e.lastIndexOf(n),t=s>=0?e.slice(0,s+1):"",r=(s>=0?e.slice(s+1):e).replace(/\.[^.]+$/,"");return`${t}${w(r,{style:"snake",reserved:k})}.py`}var ze=({model:e,output:n,banner:s,emit:t,options:r,pagination:a})=>{let c=t.errorMode??"throw",i=t.dateType??"string",m=r?.models??"dataclass",l=m==="pydantic"?Y(e):void 0,o=new R;if(o.line(`# Generated by @redocly/client-generator (python) from "${e.title}" ${e.version}.`),o.line("# Do not edit by hand \u2014 regenerate with `redocly generate-client`."),o.line(m==="pydantic"?"# Requires Python >= 3.9, httpx, and pydantic: pip install httpx pydantic":"# Requires Python >= 3.9 and httpx: pip install httpx"),o.blank(),o.line(G(e,i,m).trimEnd()),o.blank(),o.blank(),ie(o,e),t.runtime==="module"){o.line("# \u2500\u2500\u2500 Runtime (real modules beside this file, written by the same run) \u2500\u2500\u2500");for(let d of Object.keys(L))o.line(`from ${d.replace(/\.py$/,"")} import *`);o.blank(),o.blank()}else{o.line("# \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator python runtime) \u2500\u2500\u2500");for(let d of Object.values(L)){let _=d.split(`
|
|
8
|
+
`).filter(b=>!b.startsWith("from __future__")&&!b.startsWith("from ._")).join(`
|
|
9
|
+
`).trim();o.line(_),o.blank()}o.blank()}let p=ce(e,new Set(l?.unions.keys()));if(p.length>0){o.line("# Discriminated unions dispatch by their property inside decode().");for(let d of p)o.line(d);o.blank()}o.block("def _safe_json(response: httpx.Response) -> Any:",()=>{o.block("try:",()=>{o.line("return response.json()")}),o.block("except Exception:",()=>{o.line("return None")})}),o.blank();let u=new Map;for(let{op:d,ident:_}of I(e))u.set(_,oe(a?.get(d.name)?.spec));o.line("_OPERATIONS = {"),o.indent(()=>{for(let{op:d,ident:_}of I(e)){let b={id:d.specName??d.name,method:d.method.toUpperCase(),path:d.path,...B(d,e).length>0?{security:B(d,e)}:{},...u.get(_)!==void 0?{pagination:u.get(_)}:{}};o.line(`"${_}": ${se(b)},`)}}),o.line("}"),o.blank(),o.blank();let $=t.serverUrl??e.serverUrl??"";K(o,e,c,!1,u,$,i),K(o,e,c,!0,u,$,i);let h={path:V(n.path),content:o.toString()};if(t.runtime!=="module")return[h];let g=s.map(d=>`# ${d}`).join(`
|
|
10
|
+
`),v=V(n.path).replace(/[^\\/]+$/,""),P=Object.entries(L).map(([d,_])=>({path:`${v}${d}`,content:`${g}
|
|
11
|
+
|
|
12
|
+
${_.split(`
|
|
13
|
+
`).map(b=>b.startsWith("from ._")?b.replace("from ._","from _"):b).join(`
|
|
14
|
+
`).trim()}
|
|
15
|
+
`}));return[h,...P]};function de(e,n){let s=V(n.outputPath).replace(/^.*[\\/]/,"").replace(/\.py$/,""),t=I(n.model).find(a=>a.op.name===e.name)?.ident??w(e.name,{style:"snake",reserved:k}),r=[...e.pathParams.map(a=>{let c=w(a.name,{style:"snake",reserved:k});return`${c}="<${c}>"`}),...e.queryParams.filter(a=>a.required).map(a=>`${w(a.name,{style:"snake",reserved:k})}=...`),...e.requestBody?["body=..."]:[]];return{lang:"python",label:"Python SDK",source:`from ${s} import Client
|
|
16
|
+
|
|
17
|
+
client = Client()
|
|
18
|
+
result = client.${t}(${r.join(", ")})
|
|
19
|
+
`}}var Je=({model:e,output:n,emit:s,pagination:t})=>[{path:n.path.replace(/\.[^.\\/]+$/,".python.md"),content:J(e,{title:`${e.title} Python SDK reference`,frontmatter:s.docsFrontmatter===!0,language:{name:"python",label:"Python",fence:"python",requires:"The SDK needs `httpx`."},sample:r=>de(r,{model:e,emit:s,outputPath:n.path}),paginated:new Set(t?.keys()??[])})}];export{y as a,G as b,Ve as c,ze as d,de as e,Je as f};
|
|
@@ -0,0 +1,20 @@
|
|
|
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 N}from"./NSIQWNYL.js";import{b as U}from"./UKSQ7B5H.js";import{b as Q,c as D,d as R,e as I,f as X,g as Z,h as ee}from"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import{c as z,d as P,e as w,f as q,g as _,h as E,i as V,j as H,k as O,n as Y}from"./HJYFWIVE.js";import"./RFWIIJFG.js";var m=z.php,G=new N;function h(e){return G.typeName(e)}function y(e){return G.memberName(e)}function l(e){return G.string(e)}function ne(e){return P(e.name,{style:"camel",reserved:m})}function B(e){let n=e.services.flatMap(i=>i.operations),a=w(n.map(i=>i.name),{style:"camel",reserved:m});return new Map(n.map((i,r)=>[i.name,a[r]]))}function ue(e){return X(e).map(a=>a.kind==="literal"?l(a.value):`$${y(a.name)}`).join(" . ")}function te(e,n){let a=n.servers??[];if(a.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("{",()=>{a.forEach((r,t)=>{let s=P(r.description??`server${t+1}`,{style:"camel",reserved:m});i.has(s)&&(s=`${s}${t+1}`),i.add(s);let o=r.variables.map(c=>`string $${y(c.name)} = ${l(c.default)}`);t>0&&e.blank(),e.line(`public static function ${s}(${o.join(", ")}): string`),e.block("{",()=>{e.line(`return ${ue(r)};`)},"}")})},"}"),e.blank()}function re(e,n){let a=Z(e,n).map(i=>`[${i.map(t=>t.kind==="apiKey"?`['kind' => 'apiKey', 'scheme' => ${l(t.scheme)}, 'name' => ${l(t.name)}, 'in' => ${l(t.in)}]`:`['kind' => ${l(t.kind)}, 'scheme' => ${l(t.scheme)}]`).join(", ")}]`);if(a.length!==0)return`[${a.join(", ")}]`}function ie(e){return`[${[`'style' => ${l(e.style)}`,...e.param!==void 0?[`'param' => ${l(e.param)}`]:[],...e.nextCursor!==void 0?[`'nextCursor' => ${l(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`'hasMore' => ${l(e.hasMore)}`]:[],...e.limitParam!==void 0?[`'limitParam' => ${l(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${l(e.items)}`]:[]].join(", ")}]`}function ae(e,n){let a=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let t=P(r.name,{style:"camel",reserved:m}),s=2;for(;a.has(t);)t=`${P(r.name,{style:"camel",reserved:m})}_${s++}`;a.add(t);let o=Y(r.schema,n);return`[${l(r.name)}, ${l(t)}, ${l(o)}]`}).join(", ")}]`}function T(e,n){let a=n.schemas.find(t=>t.name===e);if(a===void 0)return"other";let i=a.schema,r=O(i);return r!==void 0&&(r.scalar==="string"||r.scalar==="integer")?"enum":(i.kind==="object"||i.kind==="intersection")&&_(i,n)!==void 0?"class":"other"}function f(e,n,a="string"){if(V(e)){let i=f(H(e),n,a);return x(i)}switch(e.kind){case"scalar":return a==="Date"&&e.scalar==="string"&&F(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let i=T(e.name,n);if(i==="class"||i==="enum")return h(e.name);let r=q(e,n);return r===void 0?"mixed":f(r,n,a)}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 h(e.base);case"union":return de(e.members,n,a);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function F(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function x(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function de(e,n,a){let i=[];for(let r of e){if(r.kind==="null")continue;let t=f(r,n,a);if(t==="mixed")return"mixed";let s=t.startsWith("?")?t.slice(1):t;i.includes(s)||i.push(s),t.startsWith("?")&&!i.includes("null")&&i.push("null")}return i.length===0?"mixed":i.join("|")}function K(e,n,a){if(e===void 0)return;let i=H(e);if(i.kind==="ref"){let t=q(i,n);return T(i.name,n)==="other"?K(t,n,a):void 0}if(i.kind!=="array")return;let r=f(i.items,n,a);return r==="mixed"?void 0:r}function se(e,n){let a=n.schemas.find(i=>i.name===e);return a!==void 0&&E(a.schema,n)!==void 0}function M(e,n,a,i){let r=H(e);if(i==="Date"&&r.kind==="scalar"&&r.scalar==="string"&&F(r))return`new \\DateTimeImmutable(${n})`;if(r.kind==="omit")return M({kind:"ref",name:r.base},n,a,i);if(r.kind==="ref"){let t=T(r.name,a);if(t==="class")return`${h(r.name)}::fromArray(${n})`;if(t==="enum")return`${h(r.name)}::from(${n})`;if(se(r.name,a))return`unmarshal${h(r.name)}(${n})`;let s=q(r,a);return s===void 0?void 0:M(s,n,a,i)}if(r.kind==="array"){let t=M(r.items,"$item",a,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(r.kind==="record"){let t=M(r.value,"$item",a,i);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function A(e,n,a,i="string"){let r=H(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 A({kind:"ref",name:r.base},n,a,i);if(r.kind==="ref"){let t=T(r.name,a);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(se(r.name,a))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let s=q(r,a);return s===void 0?void 0:A(s,n,a,i)}if(r.kind==="array"||r.kind==="record"){let t=r.kind==="array"?r.items:r.value,s=A(t,"$item",a,i);return s===void 0?void 0:`array_map(static fn ($item) => ${s}, ${n})`}}function pe(e,n,a,i,r,t){let s=[...a.filter(o=>o.required),...a.filter(o=>!o.required)];e.doc(h(n),t),e.line(`final class ${h(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let o of s){let c=f(o.schema,i,r);if(o.required)e.line(`public ${c} $${y(o.name)},`);else{let u=x(c);e.line(`public ${u} $${y(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 s){let c=`$data[${l(o.name)}]`,u=M(o.schema,c,i,r),p=y(o.name);o.required?e.line(`${p}: ${u??c},`):u===void 0?e.line(`${p}: ${c} ?? null,`):e.line(`${p}: isset(${c}) ? ${u} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let o of s){let c=`$this->${y(o.name)}`,u=A(o.schema,c,i,r)??c;o.required?e.line(`$data[${l(o.name)}] = ${u};`):e.block(`if (${c} !== null) {`,()=>{e.line(`$data[${l(o.name)}] = ${u};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function L(e,n="string"){let a=new N;for(let{name:i,schema:r}of e.schemas){let t=O(r);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let o=t.scalar==="string"?"string":"int";a.doc(h(i),r.description),a.line(`enum ${h(i)}: ${o}`),a.block("{",()=>{let c=w(t.values.map(u=>String(u)),{style:"pascal",reserved:m});t.values.forEach((u,p)=>{let g=typeof u=="string"?l(u):String(u);a.line(`case ${c[p]} = ${g};`)})},"}"),a.blank();continue}if(r.kind==="object"||r.kind==="intersection"){let o=_(r,e);if(o!==void 0){pe(a,i,o.properties,e,n,o.description??r.description);continue}}let s=E(r,e);if(s!==void 0){let o=h(i),c=s.cases.map(u=>`${u.value} -> ${h(u.schemaName)}`).join(", ");a.line(`/** ${o} is a discriminated union (${l(s.property)}): ${c}. */`),a.line(`function unmarshal${o}(array $data): mixed`),a.block("{",()=>{a.block(`return match ($data[${l(s.property)}] ?? null) {`,()=>{for(let u of s.cases)a.line(`${l(u.value)} => ${h(u.schemaName)}::fromArray($data),`);a.line("default => $data,")},"};")},"}"),a.blank();continue}}return a.toString()}var oe=new Set(["post","put","patch"]),$e=["body","headers","idempotencyKey"];function W(e,n,a,i){let r=w([...e.pathParams,...e.queryParams].map(c=>c.name),{style:"camel",reserved:m,taken:$e}),t=e.pathParams.map((c,u)=>({php:r[u],wire:c.name,type:f(c.schema,n,i)})),s=e.queryParams.map((c,u)=>{let p=r[e.pathParams.length+u];return{php:p,wire:c.name,type:f(c.schema,n,i),value:A(c.schema,`$${p}`,n,i)??`$${p}`}}),o=[...t.map(({php:c,type:u})=>`${u} $${c}`),...a&&e.requestBody?[`${I(e)?"array":f(e.requestBody.schema,n,i)} $body`]:[],...s.map(({php:c,type:u})=>`${x(u)} $${c} = null`),"?array $headers = null",...a&&oe.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:s,signature:o}}function fe(e,n,a){e.line(`$op = OPERATIONS[${l(n.specName??n.name)}];`),e.line("[$authHeaders, $query, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);");for(let{php:r,wire:t,value:s}of a.queryArgs)e.block(`if ($${r} !== null) {`,()=>{e.line(`$query[${l(t)}] = ${s};`)},"}");let i=a.pathArgs.map(({php:r,wire:t})=>`${l(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 J(e,n,a,i,r,t=!1){let s=W(n,i,!0,r),o=R(n),c=D(n),u=o===void 0&&c===void 0&&n.successResponses.some(b=>b.contentType!==""),p=t?"Envelope":o!==void 0?"\\Generator":c!==void 0?f(c,i,r):u?"string":"void",g=t?`${a}WithHeaders`:a,S=t?void 0:K(c,i,r);e.doc(g,t?`Like ${a}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,S===void 0?[]:[`@return ${S}[]`]),e.line(`public function ${g}(${s.signature.join(", ")}): ${p}`),e.block("{",()=>{if(fe(e,n,s),o!==void 0){let $=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, ${$?"true":"false"});`);return}let b=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(n.requestBody&&I(n))e.line("[$contentType, $encoded] = toMultipart($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let $=A(n.requestBody.schema,"$body",i,r)??"$body";e.line(`$payload = json_encode(${$});`),b.push("'body' => $payload",`'contentType' => ${l(n.requestBody.contentType)}`)}oe.has(n.method.toLowerCase())&&n.requestBody&&b.push("'idempotencyKey' => $idempotencyKey"),e.line(`$response = send($this->config, [${b.join(", ")}]);`),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}");let d=u?"$response['body']":(c===void 0?void 0:M(c,"decodeJson($response)",i,r))??"decodeJson($response)";if(t){e.line(`$data = ${d};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${ae(n,i)}), status: $response['status']);`);return}if(u){e.line("return $response['body'];");return}if(p==="void"){e.line("decodeJson($response);");return}e.line(`return ${d};`)},"}"),e.blank()}function le(e,n,a,i,r,t,s,o,c){let u=W(n,i,!1,r),p=a,g=()=>{e.line(`$op = OPERATIONS[${l(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:$,wire:k,value:v}of u.queryArgs)e.block(`if ($${$} !== null) {`,()=>{e.line(`$base[${l(k)}] = ${v};`)},"}");let d=u.pathArgs.map(({php:$,wire:k})=>`${l(k)} => $${$}`).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'], [${d}]);`),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];")},"};")},S=f(D(n)??{kind:"unknown"},i,r),b=S==="mixed"?"mixed":S;e.line("/**"),e.line(` * ${p} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${b}>`),e.line(" */"),e.line(`public function ${p}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 ${p} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${c}>`),e.line(" */"),e.line(`public function ${p}Items(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{g(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${l(o??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${s??"$item"};`)},"}")},"}")},"}"),e.blank()}function me(e){let n=e.split(`
|
|
8
|
+
`),a=0;for(let i=0;i<n.length;i++)if(n[i].trim().startsWith("namespace ")){a=i+1;break}return n.slice(a).join(`
|
|
9
|
+
`).trim()}var nn=({model:e,output:n,banner:a,emit:i,pagination:r})=>{let t=new N,s=i.dateType??"string",o=P(e.title,{style:"pascal",reserved:m});t.line("<?php"),t.blank(),t.line(`// Code generated by @redocly/client-generator (php) from ${l(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(L(e,s)),te(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(me(U)),t.blank());let c=e.services.flatMap(d=>d.operations),u=B(e),p=new Map;for(let d of c){let $=r?.get(d.name)?.spec;$!==void 0&&p.set(d.name,$)}t.block("const OPERATIONS = [",()=>{for(let d of c){let $=d.specName??d.name,k=re(d,e),v=p.get(d.name),j=[`'id' => ${l($)}`,`'method' => ${l(d.method.toUpperCase())}`,`'path' => ${l(d.path)}`,...k!==void 0?[`'security' => ${k}`]:[],...v!==void 0?[`'pagination' => ${ie(v)}`]:[]];t.line(`${l($)} => [${j.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 = ${l(i.serverUrl??e.serverUrl??"")};`)},"}")},"}"),t.blank();for(let d of c){let $=u.get(d.name);J(t,d,$,e,s),R(d)===void 0&&(d.successResponseHeaders?.length??0)>0&&J(t,d,$,e,s,!0);let k=p.get(d.name);if(k===void 0)continue;let v=D(d),j=v===void 0?void 0:M(v,"$page",e,s),C=ee(v,k.items,e),ce=C===void 0?void 0:M(C,"$item",e,s);le(t,d,$,e,s,j,ce,k.items,C===void 0?"mixed":f(C,e,s))}},"}");let g={path:n.path.replace(/\.[^.\\/]+$/,".php"),content:t.toString()};if(i.runtime!=="module")return[g];let S=a.map(d=>`// ${d}`).join(`
|
|
10
|
+
`),b=U.replace(/^namespace .*$/m,`namespace ${o};`).replace(/^<\?php\n/,`<?php
|
|
11
|
+
|
|
12
|
+
${S}
|
|
13
|
+
`).trimEnd();return[g,{path:g.path.replace(/[^\\/]+$/,"runtime.php"),content:`${b}
|
|
14
|
+
`}]};function he(e,n){let a=[...e.pathParams.map(t=>`${l(`<${y(t.name)}>`)}`),...e.requestBody?["$body"]:[],...e.queryParams.length>0?[`${y(e.queryParams[0].name)}: ${l("<value>")}`]:[]],i=P(n.model.title,{style:"pascal",reserved:m});return{lang:"php",label:"PHP SDK",source:`require '${n.outputPath.replace(/^.*[\\/]/,"").replace(/\.[^.]+$/,".php")}';
|
|
15
|
+
|
|
16
|
+
use ${i}\\{Client, Config};
|
|
17
|
+
|
|
18
|
+
$client = new Client(new Config());
|
|
19
|
+
$result = $client->${B(n.model).get(e.name)??ne(e)}(${a.join(", ")});
|
|
20
|
+
`}}var tn=({model:e,output:n,emit:a,pagination:i})=>[{path:n.path.replace(/\.[^.\\/]+$/,".php.md"),content:Q(e,{title:`${e.title} PHP SDK reference`,frontmatter:a.docsFrontmatter===!0,language:{name:"php",label:"PHP",fence:"php",requires:"The SDK needs the curl extension."},sample:r=>he(r,{model:e,emit:a,outputPath:n.path}),paginated:new Set(i?.keys()??[])})}];export{tn as phpDocs,nn as phpGenerator,he as phpSample,f as phpType,L as renderPhpModels};
|
|
@@ -4,6 +4,6 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as m,j as C,o as a,p,q as T,r as l,s as h,t as f,u as d}from"./
|
|
7
|
+
import{b as m,j as C,o as a,p,q as T,r as l,s as h,t as f,u as d}from"./SPPRUUK3.js";import{c as g}from"./BEOYUN4L.js";import A from"node:path";function L(e,n){if(C(e)!=="application/x-www-form-urlencoded"||!Array.isArray(n))return;let o=new URLSearchParams;for(let s of n){if(!g(s))continue;let t=a(s.name);t!==void 0&&o.append(t,a(s.value)??"")}return o.size>0?o.toString():void 0}function K(e,n,o){let s=e?.request,t=e?.response;if(!s)return null;let r=s?.postData,i=a(r?.mimeType),u=r?.text??L(i,r?.params),c=a(r?.encoding),y=t?.content?.text,S=a(t?.content?.encoding),q=p(t?.status);return l({method:a(s?.method),url:a(s?.url),requestHeaders:s?.headers,requestBody:T(u,c),requestContentType:i,responseStatus:q===0?void 0:q,responseStatusText:a(t?.statusText),responseHeaders:t?.headers,responseBody:T(y,S),responseContentType:a(t?.content?.mimeType),startedAt:a(e?.startedDateTime),raw:e},n,o)}var b=class{id="har";canParse(n,o){if(A.extname(n).toLowerCase()===".har")return!0;let t=o.toLowerCase();return t.includes('"log"')&&t.includes('"entries"')}async*parse(n){let o=0;for await(let s of f(n,"log.entries")){let t=K(s,o,n);t&&(yield t),o+=1}}};import $ from"node:path";function H(e){let n=a(e.url??e.uri);if(n)return{url:n};let o=a(e.host??e.headers?.host),s=a(e.path??e.request_uri),t=a(e.scheme??e.forwarded_proto);return o&&s?{url:`${t??"http"}://${o}${s}`,schemeKnown:!!t}:{url:s,schemeKnown:!!t}}function z(e,n,o){let s=e?.request??e?.req??e?.http?.request;if(!s)return null;let t=e?.response??e?.res??e?.http?.response,r=t?.body??t?.raw_body??t?.payload??t?.data,i=s?.body??s?.raw_body??s?.payload??s?.data,{url:u,schemeKnown:c}=H(s);return l({method:a(s?.method??s?.http_method),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:i,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode),responseHeaders:t?.headers,responseBody:r,responseContentType:d(t?.headers),startedAt:a(e?.started_at??e?.startedAt??e?.timestamp),raw:e},n,o)}var x=class{id="kong";canParse(n,o){if($.extname(n).toLowerCase()===".kong")return!0;let t=o.toLowerCase();return t.includes('"latencies"')||t.includes('"request"')&&t.includes('"response"')&&t.includes('"route"')}async*parse(n){let o=(await m(n,16)).trim().slice(0,1),s=0;if(o==="["){for await(let t of f(n)){let r=z(t,s,n);r&&(yield r),s+=1}return}for await(let t of h(n)){let r=z(t,s,n);r&&(yield r),s+=1}}};import R from"node:path";function U(e){return e?.request??e?.req??e?.httpRequest??e?.http?.request??e}function I(e){return e?.response??e?.res??e?.httpResponse??e?.http?.response}function O(e,n){let o=a(n?.url??n?.uri??n?.requestUrl??e?.url);if(o)return{url:o};let s=a(n?.host??n?.headers?.host??e?.host),t=a(n?.path??e?.path??n?.pathname),r=a(n?.scheme??e?.scheme);return s&&t?{url:`${r??"http"}://${s}${t}`,schemeKnown:!!r}:{url:t,schemeKnown:!!r}}function k(e,n,o){let s=U(e),t=I(e),r=s?.body??s?.bodyText??s?.payload??s?.data??s?.rawBody,i=t?.body??t?.bodyText??t?.payload??t?.data??t?.rawBody,{url:u,schemeKnown:c}=O(e,s);return l({method:a(s?.method??s?.httpMethod??e?.method??e?.httpMethod),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:r,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode??e?.status??e?.statusCode),responseHeaders:t?.headers,responseBody:i,responseContentType:d(t?.headers),startedAt:a(e?.startedAt??e?.timestamp??e?.time),raw:e},n,o)}var w=class{id="ndjson";canParse(n,o){let s=R.extname(n).toLowerCase();if(s===".ndjson"||s===".jsonl"||s===".jsonlines")return!0;let t=o.lastIndexOf(`
|
|
8
8
|
`),i=(t===-1?o:o.slice(0,t)).split(`
|
|
9
9
|
`).map(u=>u.trim()).find(Boolean);if(!i?.startsWith("{")||!i.endsWith("}"))return!1;try{return JSON.parse(i),!0}catch{return!1}}async*parse(n){let o=0;for await(let s of h(n)){let t=k(s,o,n);t&&(yield t),o+=1}}};import J from"node:path";function P(e){if(!e)return{};let n=e.trim().split(/\s+/);return n.length<2?{}:{method:n[0],path:n[1],protocol:n[2]}}function W(e,n){let o=a(n?.url??n?.request_uri??n?.uri??e?.url??e?.request_url??e?.absolute_uri),s=P(a(e?.request??n?.request_line)),t=a(n?.request_uri??n?.uri??n?.path??e?.request_uri??e?.uri)??s.path;if(o?.startsWith("http://")||o?.startsWith("https://"))return{url:o};let r=a(n?.host??n?.headers?.host??e?.host??e?.http_host??e?.server_name??e?.vhost),i=a(e?.scheme??n?.scheme??e?.request_scheme),u=!!i;if(r&&(o||t)){let c=i??"http",y=o??t;return y?.startsWith("/")?{url:`${c}://${r}${y}`,schemeKnown:u}:{url:`${c}://${r}/${y}`,schemeKnown:u}}return{url:o??t,schemeKnown:u}}function E(e,n,o){let s=g(e?.request)?e.request:e,t=g(e?.response)?e.response:void 0,r=P(a(e?.request)),i=a(s?.method??s?.request_method??e?.request_method??e?.method)??r.method,{url:u,schemeKnown:c}=W(e,s);return l({method:i,url:u,schemeKnown:c,requestHeaders:s?.headers??s?.request_headers??e?.request_headers??e?.headers,requestBody:s?.body??s?.request_body??e?.request_body??e?.body,requestContentType:d(s?.headers??s?.request_headers??e?.request_headers),responseStatus:p(t?.status??t?.status_code??e?.status??e?.status_code??e?.response_status),responseHeaders:t?.headers??t?.response_headers??e?.response_headers??e?.headers_out,responseBody:t?.body??t?.response_body??e?.response_body,responseContentType:d(t?.headers??t?.response_headers??e?.response_headers),startedAt:a(e?.time_iso8601??e?.timestamp??e?.time??e?.time_local??e?.["@timestamp"]),raw:e},n,o)}async function*j(e){if((await m(e,16)).trim().slice(0,1)==="["){yield*f(e);return}for await(let o of h(e))yield o}var N=class{id="nginx-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("nginx"))return!0;let r=o.toLowerCase();return r.includes('"request_uri"')||r.includes('"time_iso8601"')||r.includes('"upstream_response_time"')||r.includes('"remote_addr"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}},_=class{id="apache-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("apache"))return!0;let r=o.toLowerCase();return r.includes('"request_method"')||r.includes('"request_uri"')||r.includes('"vhost"')||r.includes('"response_status"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}};var B=[new b,new x,new N,new _,new w];async function le(e,n){if(n!=="auto"){let s=B.find(t=>t.id===n);if(!s)throw new Error(`Unsupported parser format: ${n}`);return s}let o=await m(e);return B.find(s=>s.canParse(e,o))}export{le as a};
|
|
@@ -0,0 +1,177 @@
|
|
|
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 h}from"./GBRES7WG.js";import{e as g,h as p,k as $}from"./NB54XRRU.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
|
+
${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
|
+
`)}
|
|
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(`
|
|
11
|
+
`)}var S=`/** \`request\`/\`response\` validators for one operation (an absent side is not validated). */
|
|
12
|
+
export type OperationSchemaSet = { request?: z.ZodType; response?: z.ZodType };
|
|
13
|
+
|
|
14
|
+
const schemaIndex: Partial<Record<string, OperationSchemaSet>> = operationSchemas;
|
|
15
|
+
|
|
16
|
+
/** One flattened validation problem: the full nested path and a short preview of the value. */
|
|
17
|
+
export type ZodViolation = { path: string; message: string; received: string };
|
|
18
|
+
|
|
19
|
+
/** A request or response payload failed validation. Requests throw it; response handling is configurable. */
|
|
20
|
+
export class ZodValidationError extends Error {
|
|
21
|
+
// Declared and assigned in the body, NOT as constructor parameter properties: those
|
|
22
|
+
// need a transform, so they break \`node --experimental-strip-types\` for anything
|
|
23
|
+
// importing this module (the generated CLI runs that way).
|
|
24
|
+
readonly operationId: string;
|
|
25
|
+
readonly direction: "request" | "response";
|
|
26
|
+
readonly issues: z.ZodError["issues"];
|
|
27
|
+
readonly violations: ZodViolation[];
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
operationId: string,
|
|
31
|
+
direction: "request" | "response",
|
|
32
|
+
issues: z.ZodError["issues"],
|
|
33
|
+
violations: ZodViolation[]
|
|
34
|
+
) {
|
|
35
|
+
const detail = violations
|
|
36
|
+
.slice(0, 5)
|
|
37
|
+
.map((violation) => \`\${violation.path || "(root)"}: \${violation.message} (received \${violation.received})\`)
|
|
38
|
+
.join("; ");
|
|
39
|
+
const more = violations.length > 5 ? \`; \u2026and \${violations.length - 5} more\` : "";
|
|
40
|
+
super(\`\${direction === "request" ? "Request" : "Response"} validation failed for operation "\${operationId}": \${detail}\${more}\`);
|
|
41
|
+
this.operationId = operationId;
|
|
42
|
+
this.direction = direction;
|
|
43
|
+
this.issues = issues;
|
|
44
|
+
this.violations = violations;
|
|
45
|
+
this.name = "ZodValidationError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Flatten zod issues into leaf violations. Union branches (zod 3 \`unionErrors\`, zod 4
|
|
50
|
+
// nested \`errors\`) are recursed into, so the message names the actual failing fields
|
|
51
|
+
// instead of just the union root ("Invalid input").
|
|
52
|
+
function flattenIssues(
|
|
53
|
+
issues: z.ZodError["issues"],
|
|
54
|
+
value: unknown,
|
|
55
|
+
base: PropertyKey[] = []
|
|
56
|
+
): ZodViolation[] {
|
|
57
|
+
const violations: ZodViolation[] = [];
|
|
58
|
+
for (const issue of issues) {
|
|
59
|
+
const path = [...base, ...issue.path];
|
|
60
|
+
const nested = nestedIssueLists(issue);
|
|
61
|
+
if (nested.length > 0) {
|
|
62
|
+
for (const sub of nested) violations.push(...flattenIssues(sub, value, path));
|
|
63
|
+
} else {
|
|
64
|
+
violations.push({
|
|
65
|
+
path: path.map(String).join("."),
|
|
66
|
+
message: issue.message,
|
|
67
|
+
received: preview(valueAt(value, path)),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return violations;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The nested issue lists of a union-ish issue, across zod 3 (\`unionErrors\`) and zod 4 (\`errors\`). */
|
|
75
|
+
function nestedIssueLists(issue: unknown): Array<z.ZodError["issues"]> {
|
|
76
|
+
const candidate = issue as {
|
|
77
|
+
unionErrors?: Array<{ issues: z.ZodError["issues"] }>;
|
|
78
|
+
errors?: Array<z.ZodError["issues"]>;
|
|
79
|
+
};
|
|
80
|
+
if (Array.isArray(candidate.unionErrors)) return candidate.unionErrors.map((error) => error.issues);
|
|
81
|
+
if (Array.isArray(candidate.errors)) return candidate.errors;
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function valueAt(value: unknown, path: PropertyKey[]): unknown {
|
|
86
|
+
let current = value;
|
|
87
|
+
for (const key of path) {
|
|
88
|
+
if (current === null || typeof current !== "object") return undefined;
|
|
89
|
+
current = (current as Record<PropertyKey, unknown>)[key];
|
|
90
|
+
}
|
|
91
|
+
return current;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A short single-line preview of the offending value. NOTE: validation output can surface
|
|
95
|
+
* payload data \u2014 route \`onViolation\` to a scrubbed logger when responses may carry secrets. */
|
|
96
|
+
function preview(value: unknown): string {
|
|
97
|
+
let text: string;
|
|
98
|
+
try {
|
|
99
|
+
text = JSON.stringify(value) ?? String(value);
|
|
100
|
+
} catch {
|
|
101
|
+
text = String(value);
|
|
102
|
+
}
|
|
103
|
+
return text.length > 80 ? \`\${text.slice(0, 77)}\u2026\` : text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type ZodValidationOptions = {
|
|
107
|
+
/** Validate request bodies before any network call; a failure THROWS (it is the caller's own bug). Default: true. */
|
|
108
|
+
request?: boolean;
|
|
109
|
+
/** Replace the outgoing body with the parsed result, dropping keys the schema does not declare
|
|
110
|
+
* (for strict-DTO servers that 400 on excess properties). Runs request validation. Default: false. */
|
|
111
|
+
stripRequestBodies?: boolean;
|
|
112
|
+
/** Response drift handling: \`"warn"\` (default) reports via \`onViolation\` and lets the call
|
|
113
|
+
* succeed \u2014 a server drifting from its description should not crash the consumer;
|
|
114
|
+
* \`"throw"\` fails the call (even on result-mode clients); \`false\` skips response validation. */
|
|
115
|
+
response?: "warn" | "throw" | false;
|
|
116
|
+
/** Sink for \`"warn"\` mode. Default: \`console.warn\` with the error message. */
|
|
117
|
+
onViolation?: (error: ZodValidationError) => void;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Schema-validation middleware for the generated client: \`use(zodValidation())\`.
|
|
122
|
+
* Request bodies are validated before any network call and throw on failure; successful
|
|
123
|
+
* JSON responses are validated against the operation's response schema and WARN by
|
|
124
|
+
* default (see \`ZodValidationOptions.response\`). Operations without a schema pass
|
|
125
|
+
* through untouched. Payloads are never mutated unless \`stripRequestBodies\` is set.
|
|
126
|
+
*/
|
|
127
|
+
export function zodValidation(options: ZodValidationOptions = {}) {
|
|
128
|
+
const { request = true, stripRequestBodies = false, response = "warn", onViolation } = options;
|
|
129
|
+
const report = onViolation ?? ((error: ZodValidationError) => console.warn(error.message));
|
|
130
|
+
return {
|
|
131
|
+
onRequest(context: { body?: unknown; operation: { id: string } }): void {
|
|
132
|
+
if ((!request && !stripRequestBodies) || context.body === undefined) return;
|
|
133
|
+
const schema = schemaIndex[context.operation.id]?.request;
|
|
134
|
+
if (!schema) return;
|
|
135
|
+
const result = schema.safeParse(context.body);
|
|
136
|
+
if (!result.success) {
|
|
137
|
+
throw new ZodValidationError(
|
|
138
|
+
context.operation.id,
|
|
139
|
+
"request",
|
|
140
|
+
result.error.issues,
|
|
141
|
+
flattenIssues(result.error.issues, context.body)
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
// zod object schemas drop undeclared keys during parsing, so the parsed value
|
|
145
|
+
// IS the declared shape (intersections keep their own zod semantics).
|
|
146
|
+
if (stripRequestBodies) context.body = result.data;
|
|
147
|
+
},
|
|
148
|
+
async onResponse(incoming: Response, context: { operation: { id: string } }): Promise<void> {
|
|
149
|
+
if (response === false || !incoming.ok) return;
|
|
150
|
+
const schema = schemaIndex[context.operation.id]?.response;
|
|
151
|
+
if (!schema) return;
|
|
152
|
+
const contentType = (incoming.headers.get("content-type") ?? "").toLowerCase();
|
|
153
|
+
if (!contentType.includes("json")) return;
|
|
154
|
+
const payload: unknown = await incoming.clone().json();
|
|
155
|
+
const result = schema.safeParse(payload);
|
|
156
|
+
if (!result.success) {
|
|
157
|
+
const error = new ZodValidationError(
|
|
158
|
+
context.operation.id,
|
|
159
|
+
"response",
|
|
160
|
+
result.error.issues,
|
|
161
|
+
flattenIssues(result.error.issues, payload)
|
|
162
|
+
);
|
|
163
|
+
if (response === "throw") throw error;
|
|
164
|
+
report(error);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}`;function v(e){let r=new Map(e.schemas.map(o=>[o.name,o.schema])),t=Z(e,r);if(e.schemas.length===0&&t.length===0)return"";let n=['import { z } from "zod";',...e.schemas.map(o=>`export const ${m(o.name)} = ${u(o.schema,r)};`)];return t.length===0?n.join(`
|
|
169
|
+
|
|
170
|
+
`):(n.push(I(t)),`${n.join(`
|
|
171
|
+
|
|
172
|
+
`)}
|
|
173
|
+
${S}
|
|
174
|
+
`)}var M=({model:e,output:r,banner:t})=>{let n=v(e);if(n==="")return[];let o=t.map(s=>`// ${s}`).join(`
|
|
175
|
+
`);return[{path:R(r.dir,`${r.stem}.zod.ts`),content:`${o}
|
|
176
|
+
|
|
177
|
+
${n}`}]};export{M as a};
|
|
@@ -0,0 +1,16 @@
|
|
|
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 $,b as a,c,d as i,e as m,f}from"./XDK4JK3V.js";import{k as l}from"./NB54XRRU.js";import{join as p}from"node:path";function k(t,n){let e=$(t,"swr");if(e.length===0)return"";let s=e.some(a),o=e.some(r=>!a(r));return[...s?['import useSWR from "swr";']:[],...o?['import useSWRMutation from "swr/mutation";']:[],f(e,n.sdkModule,s),...e.flatMap(r=>a(r)?g(r):[S(r)])].join(`
|
|
8
|
+
|
|
9
|
+
`)}function y(t,n,e){return`export function use${l(t.name)}(${n}) {
|
|
10
|
+
return ${e};
|
|
11
|
+
}`}function g(t){let n=c(t),e=n?`vars: ${i(t)}`:"",s=n?`[${JSON.stringify(t.name)}, vars]`:`[${JSON.stringify(t.name)}]`,o=`export const ${t.name}Key = (${e}) => ${s} as const;`,r=`useSWR(${`${t.name}Key(${n?"vars":""})`}, () => ${m(t,"vars",!0)})`,d=n?`vars: ${i(t)}, init?: Omit<RequestOptions, "envelope">`:'init?: Omit<RequestOptions, "envelope">';return[o,y(t,d,r)]}function S(t){let n=c(t)?`(_key: string, { arg }: {
|
|
12
|
+
arg: ${i(t)};
|
|
13
|
+
}) => ${m(t,"arg",!1)}`:`() => ${m(t,"arg",!1)}`,e=`useSWRMutation(${JSON.stringify(t.name)}, ${n})`;return y(t,"",e)}var x=({model:t,output:n,banner:e,emit:s})=>{let o=k(t,{sdkModule:`./${n.stem}.${s.importExt??"js"}`});if(o==="")return[];let u=e.map(r=>`// ${r}`).join(`
|
|
14
|
+
`);return[{path:p(n.dir,`${n.stem}.swr.ts`),content:`${u}
|
|
15
|
+
|
|
16
|
+
${o}`}]};export{x as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a}from"./U2A6GEAN.js";import"./XDK4JK3V.js";import"./VWSPU27A.js";import"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";export{a as tanstackQueryGenerator};
|
|
@@ -0,0 +1,14 @@
|
|
|
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 S,b as d}from"./REFX2EKS.js";import{a as C}from"./UKSQ7B5H.js";import{b as H,c as D,d as G,e as K,f as J,g as z,h as Q}from"./YQS3OX36.js";import"./GBRES7WG.js";import{a as j}from"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import{b as A,c as I,d as v,e as L,g as E,h as x,i as B,j as F,k as W,n as _}from"./HJYFWIVE.js";import"./RFWIIJFG.js";var c=new S,b=I.go;function V(e){if(e===void 0)return"client";if(!/^[a-z_][a-z0-9_]*$/.test(e)||b.has(e))throw new j(`goPackage "${e}" is not a valid Go package name: use lowercase letters, digits, and underscores, don't start with a digit, and avoid Go keywords.`);return e}function w(e){let t=new Set,n=[];for(let r of e.services)for(let o of r.operations){let a=d(o.name),i=2;for(;t.has(a);)a=`${d(o.name)}${i++}`;t.add(a),n.push({op:o,ident:a})}return n}function oe(e){return J(e).map(n=>n.kind==="literal"?c.string(n.value):v(n.name,{style:"camel",reserved:b})).join(" + ")}function X(e,t){let n=t.servers??[];if(n.length===0)return;let r=new Set;n.forEach((o,a)=>{let i=`${d(o.description??`server${a+1}`)}URL`;r.has(i)&&(i=`${i}${a+1}`),r.add(i);let s=o.variables.map(l=>`${v(l.name,{style:"camel",reserved:b})} string`),u=o.variables.map(l=>`${v(l.name,{style:"camel",reserved:b})} default: ${c.string(l.default)}`).join(", ");e.line(`// ${i} returns the ${c.string(o.description??o.url)} base URL${u===""?".":` (${u}).`}`),e.block(`func ${i}(${s.join(", ")}) string {`,()=>{e.line(`return ${oe(o)}`)},"}"),e.blank()})}function Y(e,t){let n=z(e,t).map(r=>r.map(o=>o.kind==="apiKey"?`{Scheme: ${c.string(o.scheme)}, Kind: "apiKey", Name: ${c.string(o.name)}, In: ${c.string(o.in)}}`:`{Scheme: ${c.string(o.scheme)}, Kind: ${c.string(o.kind)}}`));if(n.length!==0)return`[][]SecuritySpec{${n.map(r=>`{${r.join(", ")}}`).join(", ")}}`}function Z(e){return`&PaginationSpec{${[`Style: ${c.string(e.style)}`,...e.param!==void 0?[`Param: ${c.string(e.param)}`]:[],...e.nextCursor!==void 0?[`NextCursor: ${c.string(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`HasMore: ${c.string(e.hasMore)}`]:[],...e.limitParam!==void 0?[`LimitParam: ${c.string(e.limitParam)}`]:[],...e.items!==void 0?[`Items: ${c.string(e.items)}`]:[]].join(", ")}}`}function g(e,t="string"){if(B(e)){let n=g(F(e),t);return n.startsWith("*")||n==="any"?n:`*${n}`}switch(e.kind){case"scalar":if(t==="Date"&&e.scalar==="string"){if(e.metadata?.format==="date-time")return"time.Time";if(e.metadata?.format==="date")return"Date"}return{string:"string",integer:"int64",number:"float64",boolean:"bool"}[e.scalar];case"array":return`[]${g(e.items,t)}`;case"record":return`map[string]${g(e.value,t)}`;case"ref":return d(e.name);case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float64";case"enum":return{string:"string",integer:"int64",number:"float64",boolean:"bool"}[e.scalar];case"omit":return d(e.base);case"union":case"null":case"object":case"intersection":case"unknown":return"any"}}function ae(e,t,n,r,o){e.doc(d(t),o),e.block(`type ${d(t)} struct {`,()=>{for(let a of n){let i=d(a.name),s=g(a.schema,r),u=`\`json:"${a.name}"\``;a.required||(!s.startsWith("*")&&!s.startsWith("[]")&&!s.startsWith("map[")&&s!=="any"&&(s=`*${s}`),u=`\`json:"${a.name},omitempty"\``),e.line(`${i} ${s} ${u}`)}},"}"),e.blank()}function N(e,t="string"){let n=new S;n.line("package client"),n.blank(),e.schemas.some(({schema:a})=>x(a,e)!==void 0)&&(n.line('import "encoding/json"'),n.blank());let o=ie(e,t);return t==="Date"&&o.includes("time.Time")&&(n.line('import "time"'),n.blank()),n.line(o),n.toString()}function ie(e,t){let n=new S;for(let{name:r,schema:o}of e.schemas){let a=W(o);if(a!==void 0){let s=a.scalar==="string"?"string":"int64";n.doc(d(r),o.description),n.line(`type ${d(r)} ${s}`),n.blank(),n.block("const (",()=>{let u=new Set;a.values.forEach(l=>{let f=A.pascal(String(l))||"Value",m="";for(let k=2;u.has(f+m);k++)m=String(k);u.add(f+m);let h=d(r)+f+m;n.line(`${h} ${d(r)} = ${c.literal(l)}`)})},")"),n.blank();continue}if(o.kind==="object"||o.kind==="intersection"){let s=E(o,e);if(s!==void 0){ae(n,r,s.properties,t,s.description??o.description);continue}}let i=x(o,e);if(i!==void 0){let s=d(r),u=i.cases.map(l=>`${l.value} -> ${d(l.schemaName)}`).join(", ");n.line(`// ${s} is a discriminated union ("${i.property}"): ${u}.`),n.line(`type ${s} = any`),n.blank(),n.line(`// Unmarshal${s} decodes into the member selected by "${i.property}".`),n.block(`func Unmarshal${s}(data []byte) (${s}, error) {`,()=>{n.block("var probe struct {",()=>{n.line(`Discriminant string \`json:"${i.property}"\``)},"}"),n.block("if err := json.Unmarshal(data, &probe); err != nil {",()=>{n.line("return nil, err")},"}"),n.line("switch probe.Discriminant {");for(let l of i.cases)n.block(`case ${c.string(l.value)}:`,()=>{n.line(`var value ${d(l.schemaName)}`),n.line("err := json.Unmarshal(data, &value)"),n.line("return value, err")});n.line("}"),n.line("var fallback any"),n.line("err := json.Unmarshal(data, &fallback)"),n.line("return fallback, err")},"}"),n.blank();continue}n.doc(d(r),o.description),n.line(`type ${d(r)} = ${g(o,t)}`),n.blank()}return n.toString()}function R(e,t){if(t==="string")return e;let n=e.startsWith("*")?`(${e})`:e;return t==="time.Time"?`${n}.Format(time.RFC3339)`:t==="Date"?`${n}.Format("2006-01-02")`:t==="int64"?`strconv.FormatInt(${e}, 10)`:t==="float64"?`strconv.FormatFloat(${e}, 'f', -1, 64)`:t==="bool"?`strconv.FormatBool(${e})`:`fmt.Sprint(${e})`}var se=["c","ctx","body","params","out","op"];function T(e,t){let n=L(e.pathParams.map(r=>r.name),{style:"camel",reserved:b,taken:se});return e.pathParams.map((r,o)=>({param:r,go:n[o],type:g(r.schema,t)}))}function le(e,t){let n=new Set;return(e.successResponseHeaders??[]).map(r=>{let o=d(r.name),a=o,i=2;for(;n.has(a);)a=`${o}${i++}`;n.add(a);let s=_(r.schema,t),u={integer:{goType:"*int64",helper:"headerInt64"},number:{goType:"*float64",helper:"headerFloat64"},boolean:{goType:"*bool",helper:"headerBool"},string:{goType:"*string",helper:"headerString"}}[s];return{field:a,name:r.name,...u}})}function U(e,t,n,r,o,a=!1){let i=T(t,r),s=t.queryParams.length>0,u=D(t),l=u===void 0?void 0:g(u,r),f=a?le(t,o):[];a&&(e.line(`// ${n}Headers carries the declared response headers of ${n}WithHeaders (nil when absent or unparsable).`),e.block(`type ${n}Headers struct {`,()=>{for(let p of f)e.line(`${p.field} ${p.goType}`)},"}"),e.blank());let m=["ctx context.Context",...i.map(({go:p,type:P})=>`${p} ${P}`),...t.requestBody?[`body ${g(t.requestBody.schema,r)}`]:[],...s?[`params *${n}Params`]:[]],h=G(t),k=a?l===void 0?`(${n}Headers, error)`:`(${l}, ${n}Headers, error)`:h!==void 0?"func(yield func(ServerSentEvent, error) bool)":l===void 0?"error":`(${l}, error)`,$=p=>a?l===void 0?`return headers, ${p}`:`return out, headers, ${p}`:l===void 0?`return ${p}`:`return out, ${p}`,M=a?`${n}WithHeaders`:n;e.doc(M,a?`Like ${n}, also returning the declared response headers.`:t.summary),e.block(`func (c *Client) ${M}(${m.join(", ")}) ${k} {`,()=>{h===void 0&&l!==void 0&&e.line(`var out ${l}`),a&&e.line(`var headers ${n}Headers`),e.line(`op := operations[${c.string(t.specName??t.name)}]`),e.line("authHeaders, query := resolveAuth(op.Security, c.config.Auth)"),s&&e.block("if params != nil {",()=>{for(let y of t.queryParams){let O=d(y.name);e.block(`if params.${O} != nil {`,()=>{if(y.schema.kind==="array"){let q=g(y.schema.items,r);e.block(`for _, item := range *params.${O} {`,()=>{e.line(`query.Add(${c.string(y.name)}, ${R("item",q)})`)},"}")}else e.line(`query.Set(${c.string(y.name)}, ${R(`*params.${O}`,g(y.schema,r))})`)},"}")}},"}");let p=i.map(({param:y,go:O,type:q})=>`${c.string(y.name)}: ${R(O,q)}`).join(", ");if(e.line(`requestURL := buildURL(c.config.ServerURL, op.Path, map[string]string{${p}})`),h!==void 0){e.block("open := func(extraHeaders map[string]string) (*http.Response, error) {",()=>{e.line("merged := map[string]string{}"),e.block("for key, value := range authHeaders {",()=>{e.line("merged[key] = value")},"}"),e.block("for key, value := range extraHeaders {",()=>{e.line("merged[key] = value")},"}"),e.line("return send(ctx, &c.config, requestSpec{OperationID: op.ID, Method: op.Method, URL: requestURL, Headers: merged, Query: query})")},"}"),e.line(`return iterSSE(open, ${h.schema!==void 0&&h.schema.kind!=="unknown"})`);return}let P=["OperationID: op.ID","Method: op.Method","URL: requestURL","Headers: authHeaders","Query: query"];if(t.requestBody&&K(t)?(e.line("contentType, reader, err := toMultipart(body)"),e.block("if err != nil {",()=>{e.line($("err"))},"}"),P.push("Body: reader"),P.push("ContentType: contentType")):t.requestBody&&(e.line("payload, err := json.Marshal(body)"),e.block("if err != nil {",()=>{e.line($("err"))},"}"),P.push("Body: bytes.NewReader(payload)"),P.push(`ContentType: ${c.string(t.requestBody.contentType)}`)),e.line(`resp, err := send(ctx, &c.config, requestSpec{${P.join(", ")}})`),e.block("if err != nil {",()=>{e.line($("err"))},"}"),e.block("if resp.StatusCode >= 400 {",()=>{e.line($("apiErrorFrom(resp, requestURL)"))},"}"),a){e.block(`if err := decodeJSON(resp, ${l===void 0?"nil":"&out"}); err != nil {`,()=>{e.line($("err"))},"}");for(let y of f)e.line(`headers.${y.field} = ${y.helper}(resp.Header, ${c.string(y.name)})`);e.line(l===void 0?"return headers, nil":"return out, headers, nil")}else l===void 0?e.line("return decodeJSON(resp, nil)"):(e.block("if err := decodeJSON(resp, &out); err != nil {",()=>{e.line("return out, err")},"}"),e.line("return out, nil"))},"}"),e.blank()}function ee(e,t,n,r,o,a){let i=T(t,r),s=t.queryParams.length>0,u=["ctx context.Context",...i.map(({go:f,type:m})=>`${f} ${m}`),...s?[`params *${n}Params`]:[]].join(", "),l=()=>{e.line(`op := operations[${c.string(t.specName??t.name)}]`),e.line("base := url.Values{}"),s&&e.block("if params != nil {",()=>{for(let f of t.queryParams){let m=d(f.name);e.block(`if params.${m} != nil {`,()=>{e.line(`base.Set(${c.string(f.name)}, ${R(`*params.${m}`,g(f.schema,r))})`)},"}")}},"}"),e.block("call := func(pageParams url.Values) (any, *http.Response, error) {",()=>{e.line("authHeaders, query := resolveAuth(op.Security, c.config.Auth)"),e.block("for key, values := range pageParams {",()=>{e.block("for _, value := range values {",()=>{e.line("query.Set(key, value)")},"}")},"}");let f=i.map(({param:m,go:h,type:k})=>`${c.string(m.name)}: ${R(h,k)}`).join(", ");e.line(`requestURL := buildURL(c.config.ServerURL, op.Path, map[string]string{${f}})`),e.line("resp, err := send(ctx, &c.config, requestSpec{OperationID: op.ID, Method: op.Method, URL: requestURL, Headers: authHeaders, Query: query})"),e.block("if err != nil {",()=>{e.line("return nil, nil, err")},"}"),e.block("if resp.StatusCode >= 400 {",()=>{e.line("return nil, resp, apiErrorFrom(resp, requestURL)")},"}"),e.line("var raw any"),e.block("if err := decodeJSON(resp, &raw); err != nil {",()=>{e.line("return nil, resp, err")},"}"),e.line("return raw, resp, nil")},"}"),e.line("pages := iterPages(call, *op.Pagination, base)")};e.line(`// ${n}Pages iterates ${n} response pages; use with \`for page, err := range\`.`),e.block(`func (c *Client) ${n}Pages(${u}) func(yield func(${o}, error) bool) {`,()=>{l(),e.block(`return func(yield func(${o}, error) bool) {`,()=>{e.block("pages(func(raw any, err error) bool {",()=>{e.line(`var page ${o}`),e.block("if err == nil {",()=>{e.line("err = reencode(raw, &page)")},"}"),e.line("return yield(page, err)")},"})")},"}")},"}"),e.blank(),e.line(`// ${n}Items iterates the items of every ${n} page.`),e.block(`func (c *Client) ${n}Items(${u}) func(yield func(${a}, error) bool) {`,()=>{l(),e.block(`return func(yield func(${a}, error) bool) {`,()=>{e.block("pages(func(raw any, err error) bool {",()=>{e.block("if err != nil {",()=>{e.line(`var zero ${a}`),e.line("return yield(zero, err)")},"}"),e.line("pageItems, _ := resolvePointer(raw, op.Pagination.Items).([]any)"),e.block("for _, item := range pageItems {",()=>{e.line(`var typed ${a}`),e.block("if err := reencode(item, &typed); err != nil {",()=>{e.line("return yield(typed, err)")},"}"),e.block("if !yield(typed, nil) {",()=>{e.line("return false")},"}")},"}"),e.line("return true")},"})")},"}")},"}"),e.blank()}function ne(e){let t=e.split(`
|
|
8
|
+
`),n=[],r=!1;for(let o of t)if(!o.startsWith("package ")){if(o.startsWith("import (")){r=!0;continue}if(r){o.startsWith(")")&&(r=!1);continue}o.startsWith("import ")||n.push(o)}return n.join(`
|
|
9
|
+
`).trim()}var te=["bytes","context","encoding/base64","encoding/json","errors","fmt","io","math/rand","mime/multipart","net/http","net/url","strconv","strings","time"];function re(e,t,n,r,o,a){e.line(ne(N(t,r))),e.blank(),X(e,t),a&&(e.line("// \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator go runtime) \u2500\u2500\u2500"),e.line(ne(C)),e.blank()),e.block("type operationMeta struct {",()=>{e.line("ID string"),e.line("Method string"),e.line("Path string"),e.line("Security [][]SecuritySpec"),e.line("Pagination *PaginationSpec")},"}"),e.blank(),e.block("var operations = map[string]operationMeta{",()=>{for(let{op:i,ident:s}of w(t)){let u=i.specName??i.name,l=Y(i,t),f=o.get(s),m=[`ID: ${c.string(u)}`,`Method: ${c.string(i.method.toUpperCase())}`,`Path: ${c.string(i.path)}`,...l!==void 0?[`Security: ${l}`]:[],...f!==void 0?[`Pagination: ${Z(f)}`]:[]];e.line(`${c.string(u)}: {${m.join(", ")}},`)}},"}"),e.blank();for(let{op:i,ident:s}of w(t))i.queryParams.length!==0&&(e.block(`type ${s}Params struct {`,()=>{for(let u of i.queryParams){let l=g(u.schema,r);e.line(`${d(u.name)} ${l.startsWith("*")?l:`*${l}`}`)}},"}"),e.blank());e.doc("Client",`Client for ${t.title} (${t.version}).`),e.block("type Client struct {",()=>{e.line("config Config")},"}"),e.blank(),e.block("func New(config Config) *Client {",()=>{e.block('if config.ServerURL == "" {',()=>{e.line(`config.ServerURL = ${c.string(n.serverUrl??t.serverUrl??"")}`)},"}"),e.line("return &Client{config: config}")},"}"),e.blank();for(let{op:i,ident:s}of w(t)){U(e,i,s,r),G(i)===void 0&&(i.successResponseHeaders?.length??0)>0&&U(e,i,s,r,t,!0);let u=o.get(s);if(u===void 0)continue;let l=D(i),f=l===void 0?"any":g(l,r),m=Q(l,u.items,t);ee(e,i,s,r,f,m===void 0?"any":g(m,r))}}var ze=({model:e,output:t,banner:n,emit:r,pagination:o})=>{let a=new S,i=r.dateType??"string",s=V(r.goPackage),u=new Map;for(let{op:$,ident:M}of w(e)){let p=o?.get($.name)?.spec;p!==void 0&&u.set(M,p)}a.line(`// Code generated by @redocly/client-generator (go) from "${e.title}" ${e.version}. DO NOT EDIT.`),a.line("// Regenerate with `redocly generate-client`. Standard library only \u2014 zero dependencies."),a.line(`package ${s}`),a.blank();let l=r.runtime!=="module",f=l?te:(()=>{let $=new S;re($,e,r,i,u,!1);let M=$.toString();return te.filter(p=>new RegExp(`\\b${p.split("/").pop()}\\.`).test(M))})();a.block("import (",()=>{for(let $ of f)a.line(c.string($))},")"),a.blank(),re(a,e,r,i,u,l);let m={path:t.path.replace(/\.[^.\\/]+$/,".go"),content:a.toString()};if(l)return[m];let h=n.map($=>`// ${$}`).join(`
|
|
10
|
+
`),k=C.replace(/^package .*$/m,`package ${s}`);return[m,{path:m.path.replace(/[^\\/]+$/,"runtime.go"),content:`${h}
|
|
11
|
+
${k.trimEnd()}
|
|
12
|
+
`}]};function ce(e,t){let n=t.emit.dateType??"string",r=t.emit.goPackage??"client",o=w(t.model).find(u=>u.op.name===e.name)?.ident??d(e.name),a=["ctx",...e.pathParams.map(u=>`"<${v(u.name,{style:"camel",reserved:b})}>"`),...e.requestBody?[`${g(e.requestBody.schema,n)}{ /* \u2026 */ }`]:[],...e.queryParams.length>0?["nil"]:[]],i=`client.${o}(${a.join(", ")})`,s=G(e)!==void 0?`stream := ${i}`:D(e)===void 0?`err := ${i}`:`result, err := ${i}`;return{lang:"go",label:"Go SDK",source:`client := ${r}.New(${r}.Config{})
|
|
13
|
+
${s}
|
|
14
|
+
`}}var Qe=({model:e,output:t,emit:n,pagination:r})=>[{path:t.path.replace(/\.[^.\\/]+$/,".go.md"),content:H(e,{title:`${e.title} Go SDK reference`,frontmatter:n.docsFrontmatter===!0,language:{name:"go",label:"Go",fence:"go",requires:"The SDK needs the standard library only."},sample:o=>ce(o,{model:e,emit:n,outputPath:t.path}),paginated:new Set(r?.keys()??[])})}];export{Qe as goDocs,ze as goGenerator,ce as goSample,g as goType,N as renderGoModels};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a}from"./5L3FH5WQ.js";import"./XDK4JK3V.js";import"./VWSPU27A.js";import"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";export{a as swrGenerator};
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as G}from"./
|
|
7
|
+
import{a as G}from"./5E3L4HJN.js";import{c as I,d as N,e as fe,h as q,j as _,k as ue,v as D,w as B}from"./SPPRUUK3.js";import{a as ce,c as pe}from"./ZVUMPMHU.js";import{b as ae}from"./3M6ARSHY.js";import{B as oe,C as P,O as y,c as b,ca as se,ia as ie,l as $}from"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{mkdir as Bt,writeFile as zt}from"node:fs/promises";import Ht from"node:path";import*as Ce from"node:process";var Ve=/^[a-zA-Z][a-zA-Z0-9]*(?:[_\-.][a-zA-Z0-9]+)*$/,Fe=/^[0-9a-f-]{8,}$/i,Ye=[["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)$/]],J=new WeakMap;function z(e){return{formats:Ye.filter(([,t])=>t.test(e)).map(([t])=>t),values:[e],count:1,overflow:!1}}function C(e,t){if(!e)return t;if(!t)return e;let r={formats:e.formats.filter(n=>t.formats.includes(n)),values:[],count:e.count+t.count,overflow:e.overflow||t.overflow};if(!r.overflow){let n=[...e.values];for(let o of t.values)n.includes(o)||n.push(o);n.length>10?r.overflow=!0:r.values=n}return r}function H(e,t){J.set(e,t)}function L(e){return J.get(e)}function U(e,t){let r=J.get(e);r&&J.set(t,r)}function Ke(e){return e.length<=30&&!Fe.test(e)&&Ve.test(e)}function W(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(Ke)?{enum:[...e.values].sort()}:{}}function R(e){let t=J.get(e);if(t){let r=typeof e.type=="string"?[e.type]:e.type??[];r.includes("string")&&Object.assign(e,W(t,r.length===1))}for(let r of Object.values(e.properties??{}))R(r);e.additionalProperties&&R(e.additionalProperties),e.items&&R(e.items);for(let r of e.oneOf??[])R(r)}function me(e){for(let t of Object.values(e.paths))for(let r of Object.values(t)){for(let n of Object.values(r.requestBody?.content??{}))R(n.schema);for(let n of Object.values(r.responses))for(let o of Object.values(n.content??{}))R(o.schema)}for(let t of Object.values(e.components?.schemas??{}))R(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+$/,We=/^[0-9a-hjkmnp-tv-z]{26}$/i,Xe=/^[a-z][a-z0-9]*_(?=[0-9a-z]*\d)[0-9a-z]{10,}$/i,Ze=/^[a-z](?=[a-z0-9]*\d)[a-z0-9]{23,24}$/,Z=new Set(ce),Qe=new Set(["get","head"]),de="application/x-www-form-urlencoded",le="multipart/form-data";function et(e){return e?F.test(e)||be.test(e)||We.test(e)||Xe.test(e)||Ze.test(e)?!0:/^[0-9a-f]{16,}$/i.test(e):!1}function Q(e){let t=e.split("/"),r=[],n=new Set;return{template:t.map((s,a)=>{if(!et(s))return s;let i=t[a-1],c=i?`${$(i,1)}Id`:"id",p=1;for(;n.has(c);)p+=1,c=i?`${$(i,1)}Id${p}`:`id${p}`;return n.add(c),r.push({name:c,value:s}),`{${c}}`}).join("/")||"/",params:r}}function A(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(A);return{type:"array",items:x(t)}}switch(typeof e){case"string":{let t={type:"string"};return H(t,z(e)),t}case"boolean":return{type:"boolean"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"object":{let t=Object.entries(e);if(t.length>0&&(t.every(([a])=>F.test(a))||t.every(([a])=>be.test(a))))return{type:"object",additionalProperties:x(t.map(([,a])=>A(a)))};let r={},n=[];for(let[s,a]of t)r[s]=A(a),n.push(s);let o={type:"object",properties:r};return n.length>0&&(o.required=n),o}default:return{}}}function x(e){if(e.length===0)return{};let[t,...r]=e,n=t;for(let o of r)n=V(n,o);return n}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 X(e){return e.oneOf?e.oneOf.flatMap(X):Array.isArray(e.type)?e.type.map(t=>{if(t==="object"){let n={type:"object"};return e.properties&&(n.properties=e.properties),e.required&&(n.required=e.required),e.additionalProperties&&(n.additionalProperties=e.additionalProperties),n}if(t==="array")return e.items?{type:"array",items:e.items}:{type:"array"};let r={type:t};return t==="string"&&U(e,r),r}):[e]}var tt=.5,rt=3;function we(e,t){let r=Object.keys(e.properties??{}),n=Object.keys(t.properties??{});if(r.length===0||n.length===0)return 1;let o=new Set(n),s=r.filter(a=>o.has(a)).length;return s/(r.length+n.length-s)}function nt(e,t){let r=k(e);if(r!==k(t))return!1;switch(r){case"scalar":return e.type===t.type||e.type==="integer"&&t.type==="number"||e.type==="number"&&t.type==="integer";case"object":return we(e,t)>=tt;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 r=C(L(e),L(t));if(r){let n={type:"string"};return H(n,r),n}}return e}case"map":return{type:"object",additionalProperties:V(e.additionalProperties??{},t.additionalProperties??{})};case"object":{let r={...e.properties??{}};for(let[a,i]of Object.entries(t.properties??{}))r[a]=r[a]?V(r[a],i):i;let n=new Set(t.required??[]),o=(e.required??[]).filter(a=>n.has(a)),s={type:"object",properties:r};return o.length>0&&(s.required=o),s}case"array":{if(!e.items||!t.items){let r=e.items??t.items;return r?{type:"array",items:r}:{type:"array"}}return{type:"array",items:V(e.items,t.items)}}}}function ot(e){let t=[...e],r=()=>t.filter(n=>k(n)==="object").length;for(;r()>rt;){let n=-1,o=-1,s=-1;for(let a=0;a<t.length;a++)if(k(t[a])==="object")for(let i=a+1;i<t.length;i++){if(k(t[i])!=="object")continue;let c=we(t[a],t[i]);c>s&&(s=c,n=a,o=i)}t[n]=ve(t[n],t[o]),t.splice(o,1)}return t}var st=["boolean","integer","number","string","null"];function it(e){if(e.length===1)return e[0];let t=[],r=new Set,n;for(let i of e)k(i)==="scalar"&&typeof i.type=="string"?(r.add(i.type),i.type==="string"&&(n=C(n,L(i)))):t.push(i);let o=st.filter(i=>r.has(i)),s=i=>{let c={type:i};return(typeof i=="string"?i==="string":i.includes("string"))&&n&&H(c,n),c};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 a=[...t];return o.length===1?a.push(s(o[0])):o.length>1&&a.push(s(o)),{oneOf:a}}function V(e,t){if(he(e)||he(t))return{};let r=X(e);for(let n of X(t)){let o=r.findIndex(s=>nt(s,n));o===-1?r.push(n):r[o]=ve(r[o],n)}return it(ot(r))}function at(e){if(!e)return;let t=e.trim();if(!(!t.startsWith("{")&&!t.startsWith("[")))try{return JSON.parse(t)}catch{return}}function ct(e,t){let r=t?.match(/boundary="?([^";,]+)"?/i)?.[1];if(!r)return;let n={};for(let o of e.split(`--${r}`)){let s=o.match(/^\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)\r?\n$/);if(!s)continue;let[,a,i]=s,c=a.match(/\bname="([^"]*)"/i)?.[1];c!==void 0&&(n[c]=/\bfilename="/i.test(a)?{type:"string",format:"binary"}:A(i))}if(Object.keys(n).length!==0)return{type:"object",properties:n,required:Object.keys(n)}}function ge(e){let t=_(e.contentType);if(e.bodyJson!==void 0)return{mime:ue(t)?t:"application/json",schema:A(e.bodyJson)};if(t===de&&e.bodyText){let n={};for(let[o,s]of new URLSearchParams(e.bodyText))n[o]=s;return Object.keys(n).length===0?void 0:{mime:de,schema:A(n)}}if(t===le&&e.bodyText){let n=ct(e.bodyText,e.contentType);return n?{mime:le,schema:n}:void 0}let r=at(e.bodyText);if(r!==void 0)return{mime:"application/json",schema:A(r)}}function ye(e,t,r){let n=e.get(t);e.set(t,n?x([n,r]):r)}async function Oe(e){let t=await N(e.trafficPath);if(t.length===0)throw new Error("No traffic files found in the provided traffic path.");let r=D(e.server),n=new Map,o=new Set,s=0,a=c=>{let p=c.request.method.toLowerCase();if(!Z.has(p))return;let f=c.request.path||"/";if(r){let u=B(c.request,r);if(u===void 0)return;f=u}else c.request.host&&!fe(c.request.host)&&o.add(`${c.request.protocol}//${c.request.host}`);let{template:l,params:m}=Q(q(f)),w=`${p} ${l}`,d=n.get(w);d||(d={method:p,template:l,pathParams:new Map,queryParams:new Map,requestBodies:new Map,responses:new Map},n.set(w,d));for(let{name:u,value:h}of m){let g=d.pathParams.get(u);d.pathParams.set(u,{numeric:(g?.numeric??!0)&&F.test(h),observations:C(g?.observations,z(h))})}for(let u of new Set(c.request.query.keys())){let h=c.request.query.getAll(u),g=d.queryParams.get(u),v=h.length>0&&h.every(O=>F.test(O)),S=g?.observations;for(let O of h)S=C(S,z(O));d.queryParams.set(u,{numeric:(g?.numeric??!0)&&v,observations:S})}if(!Qe.has(p)){let u=ge(c.request);u&&ye(d.requestBodies,u.mime,u.schema)}if(c.response&&c.response.status>=100){let u=String(c.response.status),h=d.responses.get(u);h||(h={bodies:new Map},d.responses.set(u,h)),h.statusText??=c.response.statusText||void 0;let g=ge(c.response);g&&ye(h.bodies,g.mime,g.schema)}};for(let c of t){let p=await G(c,e.format);if(!p){y.warn(`Skipping traffic file with unrecognized format: ${c}
|
|
8
8
|
`);continue}s+=1;for await(let f of p.parse(c))a(f)}if(s===0)throw new Error("No supported traffic files found to generate an OpenAPI description from.");if(n.size===0)throw new Error(r?`No HTTP exchanges in the traffic matched the server "${r}".`:"No HTTP exchanges were observed in the traffic. Cannot generate an OpenAPI description.");let i=r?[r]:Array.from(o).sort();return pt(n,e.title??"Generated API",i)}function $e(e){return Object.values(e.paths).reduce((t,r)=>t+Object.keys(r).length,0)}function Se(e,t){if(e.numeric)return{type:"integer"};let r={type:"string"};return e.observations&&Object.assign(r,W(e.observations,t)),r}function pt(e,t,r){let n={};for(let o of e.values()){let s=n[o.template]??={},a=[...Array.from(o.pathParams).map(([c,p])=>({name:c,in:"path",required:!0,schema:Se(p,!1)})),...Array.from(o.queryParams).map(([c,p])=>({name:c,in:"query",required:!1,schema:Se(p,!0)}))],i={operationId:ft(o.method,o.template),responses:{}};if(a.length>0&&(i.parameters=a),o.requestBodies.size>0){let c={};for(let[p,f]of o.requestBodies)c[p]={schema:f};i.requestBody={content:c}}if(o.responses.size===0)i.responses.default={description:"Observed response"};else for(let[c,p]of o.responses){let f={description:p.statusText||"Observed response"};if(p.bodies.size>0){let l={};for(let[m,w]of p.bodies)l[m]={schema:w};f.content=l}i.responses[c]=f}s[o.method]=i}return{openapi:"3.2.0",info:{title:t,version:"1.0.0"},...r.length>0?{servers:r.map(o=>({url:o}))}:{},paths:n}}function ft(e,t){let r=t.split("/").filter(Boolean).map(n=>n.replace(/[{}]/g,"")).join("-");return`${e}-${r||"root"}`}function Y(e,t){return`${e.toUpperCase()} ${t}`}function Pe(e,t){let r;if(e.bodyJson!==void 0)try{r=JSON.stringify(e.bodyJson)}catch{r=void 0}if(r??=e.bodyText,!r)return;let n=r.trim();if(n)return n.length>t?`${n.slice(0,t)}\u2026[truncated]`:n}function Te(e){if(!e)return"";let t=e.bodyJson;return t===void 0?e.bodyText?_(e.contentType)||"text":"":t===null?"null":Array.isArray(t)?`array<${t.length>0?Ee(t[0]):""}>`:Ee(t)}function Ee(e){return b(e)?Object.keys(e).sort().join(","):e===null?"null":typeof e}async function Re(e){let t=e.perGroup??2,r=e.perOperation??4,n=e.maxBodyChars??2e3,o=D(e.server),s=await N(e.trafficPath),a=new Map;for(let c of s){let p=await G(c,e.format);if(p)for await(let f of p.parse(c)){let l=f.request.method.toUpperCase();if(!Z.has(l.toLowerCase()))continue;let m=f.request.path||"/";if(o){let ne=B(f.request,o);if(ne===void 0)continue;m=ne}let w=q(m),{template:d}=Q(w),u=f.response&&f.response.status>=100?f.response:void 0,h=u?.status,g=`${Te(f.request)}\u2192${Te(u)}`,v=a.get(Y(l,d));v||(v=new Map,a.set(Y(l,d),v));let S=`${h??""} ${g}`,O=v.get(S);O||(O=[],v.set(S,O)),!(O.length>=t)&&O.push({method:l,path:w,query:f.request.query.toString(),status:h,requestContentType:f.request.contentType,requestBody:Pe(f.request,n),responseContentType:u?.contentType,responseBody:u?Pe(u,n):void 0})}}let i=new Map;for(let[c,p]of a){let f=[];for(let l=0;l<t&&f.length<r;l++)for(let m of p.values()){if(f.length>=r)break;m[l]&&f.push(m[l])}i.set(c,f)}return i}var ut=`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:
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a}from"./5EG7SNNU.js";import"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";export{a as zodGenerator};
|