@redocly/openapi-docs 3.17.0-next.2 → 3.17.0-next.4
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/dist/redocly-openapi-docs.min.js +1998 -1863
- package/lib/components/PayloadSamples/ExampleValue.js +1 -1
- package/lib/components/Replay/utils.js +1 -1
- package/lib/components/SchemaDefinition/SchemaDefinition.js +2 -4
- package/lib/components/TagItem/OperationNavigationItems.js +5 -4
- package/lib/components/TagItem/TagItem.js +35 -9
- package/lib/jotai/operation.d.ts +1 -1
- package/lib/jotai/operation.js +1 -1
- package/lib/models/example.js +1 -1
- package/lib/models/mediaType.js +1 -1
- package/lib/services/code-samples/generator.js +1 -1
- package/lib/services/code-samples/httpsnippet/index.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/csharp/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/httpclient.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/go/native.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java/httpclient.js +3 -3
- package/lib/services/code-samples/httpsnippet/targets/java8/apachehttp.js +2 -2
- package/lib/services/code-samples/httpsnippet/targets/javascript/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/node/fetch.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/php/curl.js +9 -5
- package/lib/services/code-samples/httpsnippet/targets/python/requests.js +8 -5
- package/lib/services/code-samples/httpsnippet/targets/r/httr.js +7 -1
- package/lib/services/code-samples/httpsnippet/targets/ruby/native.js +1 -1
- package/lib/services/code-samples/httpsnippet/targets/shell/curl.js +6 -6
- package/lib/types/open-api.d.ts +2 -0
- package/package.json +11 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as i}from"react/jsx-runtime";import{useAtomValue as m}from"jotai";import{XMLBuilder as c}from"fast-xml-parser";import{JsonViewer as a}from"@redocly/theme/components/JsonViewer/JsonViewer";import{isFormUrlEncoded as d,isJsonLike as f,isXmlLike as p,langFromMime as x,urlFormEncodePayload as g,isSequentialMediaType as y}from"../../utils/index.js";import{globalOptionsAtom as j}from"../../jotai/store.js";import{StyledCodeBlock as k}from"./styled.js";const L=new c({format:!0});function F({value:o,mimeType:r,encoding:n,onCopyClick:e,onPanelToggle:s}){const{jsonSamplesExpandLevel:l}=m(j);if(f(r)&&!y(r)){let t;try{t=typeof o=="string"?JSON.parse(o):o}catch{t=o}return i(a,{data:t,expandLevel:l,onCopyClick:e,onPanelToggle:s})}if(typeof o=="object")if(d(r))o=g(o,n);else if(p(r)){const t=Array.isArray(o)?o:{root:o};o=L.build(t)}else o=JSON.stringify(o,null,2);return i(k,{lang:x(r),source:o,header:{className:"code-block-header",controls:{copy:{onClick:e}}}})}export{F as ExampleValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPrimitive as h}from"@redocly/theme/core/openapi";import{getOperation as v}from"../../models/index.js";import{normalizeOptions as
|
|
1
|
+
import{isPrimitive as h}from"@redocly/theme/core/openapi";import{getOperation as v}from"../../models/index.js";import{normalizeOptions as O,OpenAPIParser as b}from"../../services/index.js";import{JsonPointer as E}from"../../utils/index.js";function V(t,r,n,a,e,i,m){if(!n)return;const o=new b(n),u=o.definition.paths?.[t];let l=u?.[r];!l&&u?.additionalOperations&&(l=u.additionalOperations[r]);const s=v(o,{...l,pathName:t,httpVerb:r,pathParameters:u.parameters||[],pathServers:u.servers||[]},void 0,O({}),"",{isCallback:!1},a,m);if(!s)return;const x=i?.activeMimeName||s.requestBody?.content?.mediaTypes[0]?.name||"application/json";return{id:s.id,name:s.name,method:s.httpVerb,operationId:s.operationId,parameters:y(s.parameters,e?.requestValues),body:S(s.requestBody,n,e?.requestValues?.body?{activeExampleName:e?.activeExampleName,[x]:e?.requestValues?.body}:e?.activeExampleName?{activeExampleName:e?.activeExampleName}:void 0),path:s.path,href:s.href,servers:s.servers,security:q(s.security),responses:Object.fromEntries(s.responses.map(c=>[c.code,{code:c.code,description:c.description,mediaTypes:c.content?.mediaTypes.reduce((d,f)=>(d[f.name]={name:f.name,schema:p(f.schema?.rawSchema,n)},d),{})}]))}}function R(t,r){return function(n,a,e){const i=V(n,a,e,t,void 0,void 0,r);if(i)return{...i,operationId:i.operationId||E.compile(["paths",i.path,i.method])}}}function y(t,r){const n=new Set,a=t.map(e=>(n.add(e.in+":"+e.name),{name:e.name,in:e.in,required:e.required,description:e.description,example:r?.[String(e.in)]?.[e.name]||e.example,schema:e.schema}));for(const[e,i]of Object.entries(r||{}))for(const[m,o]of Object.entries(i||{}))n.has(e+":"+m)||a.push({name:m,in:e,required:!1,description:"",example:String(o),schema:void 0});return a}function g({type:t,format:r,enum:n}){return t==="string"&&(r==="binary"||r==="base64")?"file":t==="object"?"multiline":n.length>0?"select":"text"}function N(t,r){const n=t[0]?.example||t[0]?.examples;if(n)return n;if(t.schema?.example)return t.schema.example;const a=r?.default?.value||r?.default?.rawValue;return a?.[t.name]?h(a?.[t.name])?String(a?.[t.name]):JSON.stringify(a?.[t.name]):""}function w(t){if(t?.fields)return t.fields;if(t?.oneOf){for(const r of t.oneOf)if(r?.fields)return r.fields}}function S(t,r,n){if(!t||!t.content?.mediaTypes){if(!n)return;const{activeExampleName:a,...e}=n;return{activeExampleName:a,mediaTypes:Object.fromEntries(Object.entries(e).map(([i,m])=>[i,{name:i,examples:{default:{value:m}},schema:{},parameters:[]}]))}}return{required:t.required,activeExampleName:n?.activeExampleName,mediaTypes:t.content.mediaTypes.reduce((a,e)=>{const i=e.schema,m=n?.[e.name]?{default:{value:n?.[e.name],rawValue:n?.[e.name],mime:e.name}}:e.examples||e.formExamples,o=w(i);return a[e.name]={name:e.name,examples:m,schema:p(e.schema?.rawSchema,r),parameters:o?.map(u=>({inputType:g(u.schema),name:u.name,example:N(u,m)}))},a},{})}}function p(t,r){if(!(!t||!r))return{...t,components:r?.components||{}}}function q(t){if(t)return t.map(({schemes:r})=>r.map(n=>{const a={id:n.id,type:n.type,in:n.in,openIdConnectUrl:n.openIdConnectUrl,scopes:n.scopes,scheme:n.scheme,name:n.name,flows:n.flows,serverValues:n.serverValues,"x-defaultAccessToken":n["x-defaultAccessToken"],"x-defaultTokenType":n["x-defaultTokenType"],"x-defaultClientId":n["x-defaultClientId"],"x-defaultClientSecret":n["x-defaultClientSecret"],"x-defaultUsername":n["x-defaultUsername"],"x-defaultPassword":n["x-defaultPassword"]};return Object.keys(a).forEach(e=>a[e]===void 0&&delete a[e]),a}))}export{V as convertOperationToReplayValue,R as convertOperationToReplayValueForRedoc,q as convertRequestSecurity};
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import{jsx as o,jsxs as S}from"react/jsx-runtime";import{memo as C,useCallback as
|
|
1
|
+
import{jsx as o,jsxs as S}from"react/jsx-runtime";import{memo as C,useCallback as M,useMemo as k}from"react";import{LayoutVariant as A}from"@redocly/config";import{useAtom as j,useAtomValue as x}from"jotai";import{useWriteAtom as T}from"../../jotai/use-write-atom.js";import{SamplesMiddlePanel as D,SamplesPanel as E,Row as N,Section as b,CodeBlockPanel as P}from"../common/index.js";import{getMediaType as w}from"../../models/index.js";import{MediaTypeSamples as I}from"../PayloadSamples/index.js";import{Schema as L}from"../Schema/index.js";import{Markdown as V}from"../Markdown/index.js";import{layoutAtom as W}from"../../jotai/app.js";import{globalStoreAtom as _}from"../../jotai/store.js";import{operationStore as O}from"../../jotai/operation.js";import{styled as $}from"../../styled-components.js";import{SchemaCatalogLink as B}from"../SchemaCatalogLink/SchemaCatalogLink.js";const K=(t,i)=>{if(!t)return{};const n={schema:{$ref:t}};return i&&(n.examples={example:{$ref:i}}),n};function q({schemaRef:t,exampleRef:i,showReadOnly:n=!0,showWriteOnly:v=!1}){const s=x(W),{parser:c,options:p}=x(_),l=T(),e=k(()=>w(c,"json",!1,K(t,i),p,{operation:{pointer:"SchemaDefinitionComponent"}}),[i,p,c,t]),[f,d]=j(O(e.operation?.pointer)),y=M(r=>{if(!e.schema)return;const a=e.schema,u=a.oneOf;if(u&&e?.examples&&Object.keys(e?.examples).includes(r)){const m=u.findIndex(g=>g.title===r);m!==-1&&a&&l(O(a.operationPointer),{activeExampleName:a.oneOf?.[m]?.title,activeOneOf:{[a.pointer]:m}})}f.activeExampleName!==r&&d({activeExampleName:r})},[e?.examples,e.schema,f.activeExampleName,d,l]),h=s===A.STACKED;return o(b,{children:S(N,{layout:s,children:[S(D,{isStacked:h,children:[t&&o(B,{schemaRef:t}),e.schema?.description&&o(z,{children:o(V,{source:e.schema?.description})}),o(L,{skipWriteOnly:!v,skipReadOnly:!n,schema:e.schema,level:1})]}),o(E,{isStacked:h,children:o(P,{className:"panel-response-samples",children:o(I,{mediaType:e,onChange:y})})})]})})}const ne=C(q),z=$.div`
|
|
2
2
|
margin-bottom: var(--spacing-vertical);
|
|
3
|
-
|
|
4
|
-
padding-left: 0;
|
|
5
|
-
`;export{re as SchemaDefinition};
|
|
3
|
+
`;export{ne as SchemaDefinition};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as e,jsxs as s,Fragment as w}from"react/jsx-runtime";import{memo as j}from"react";import{getOperationColor as z}from"@redocly/theme/core/openapi";import{Tooltip as k}from"@redocly/theme/components/Tooltip/Tooltip";import{joinWithSeparator as C}from"../../services/index.js";import{encodeBackSlashes as O}from"../../utils/index.js";import{HttpVerb as B,NavigationBadge as p}from"../common/index.js";import{styled as o}from"../../styled-components.js";import{StyledButton as I}from"./styled.js";function N({title:l,items:c,onClick:d,routingBasePath:h,translate:m}){return s(w,{children:[e(S,{children:l}),c.map(t=>{const{id:g,href:f,deprecated:r,badges:v,isAdditionalOperation:b,name:a}=t,x=t.type==="operation"?t.path:a,i=t.type==="operation"?t.httpVerb:t.type,u=z({isAdditionalOperation:b,deprecated:r,httpVerb:i});return e(k,{tip:a,placement:"left",children:e(V,{variant:"outlined",size:"large",onClick:()=>d(C(h,O(f))),children:s("span",{children:[e(B,{color:u,children:i}),e(_,{children:x}),r&&e(p,{deprecated:!0,children:m("openapi.badges.deprecated","Deprecated")}),v?.map(({name:n,color:y})=>e(p,{color:y,children:n},n))]})})},g)})]})}const G=j(N),S=o.span`
|
|
2
2
|
font-size: var(--font-size-base);
|
|
3
3
|
line-height: var(--line-height-base);
|
|
4
4
|
font-weight: var(--font-weight-bold);
|
|
5
5
|
color: var(--text-color-primary);
|
|
6
6
|
margin: var(--spacing-sm) 0 var(--spacing-xxs) 0;
|
|
7
|
-
`,
|
|
7
|
+
`,V=o(I)`
|
|
8
8
|
border-radius: var(--border-radius);
|
|
9
9
|
background: var(--bg-color);
|
|
10
10
|
justify-content: space-between;
|
|
11
|
+
width: 100%;
|
|
11
12
|
|
|
12
13
|
& > span {
|
|
13
14
|
display: flex;
|
|
@@ -24,7 +25,7 @@ import{jsx as r,jsxs as i,Fragment as y}from"react/jsx-runtime";import{memo as w
|
|
|
24
25
|
content: '→';
|
|
25
26
|
line-height: var(--line-height-base);
|
|
26
27
|
}
|
|
27
|
-
`,
|
|
28
|
+
`,_=o.span`
|
|
28
29
|
font-family: var(--font-family-base);
|
|
29
30
|
font-size: var(--font-size-base);
|
|
30
31
|
line-height: var(--line-height-base);
|
|
@@ -33,4 +34,4 @@ import{jsx as r,jsxs as i,Fragment as y}from"react/jsx-runtime";import{memo as w
|
|
|
33
34
|
white-space: nowrap;
|
|
34
35
|
text-overflow: ellipsis;
|
|
35
36
|
overflow-x: hidden;
|
|
36
|
-
`;export{
|
|
37
|
+
`;export{G as OperationNavigationItems};
|
|
@@ -1,33 +1,59 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as r,jsxs as t}from"react/jsx-runtime";import{memo as w,useCallback as $}from"react";import{useNavigate as y}from"react-router-dom";import{useAtomValue as z}from"jotai";import{LayoutVariant as j}from"@redocly/config";import{css as M}from"styled-components";import{Markdown as p}from"@redocly/theme/components/Markdown/Markdown";import{breakpoints as T}from"@redocly/theme/core/openapi";import{Button as C}from"@redocly/theme/components/Button/Button";import{PageActions as I}from"@redocly/theme/components/PageActions/PageActions";import{H2 as A}from"@redocly/theme/components/Typography/H2";import{LinkIcon as L}from"@redocly/theme/icons/LinkIcon/LinkIcon";import{joinWithSeparator as P}from"../../services/history/helpers.js";import{Row as W,SamplesMiddlePanel as m,SamplesPanel as f,ShareLink as B}from"../common/index.js";import{Markdown as D}from"../Markdown/index.js";import{OperationsNavigation as H}from"./OperationsNavigation.js";import{layoutAtom as N}from"../../jotai/app.js";import{useTranslate as V}from"../../hooks/index.js";import{styled as l}from"../../styled-components.js";import{StyledShareLink as _}from"../common/linkify.js";function E({item:a,routingBasePath:i="",isExpanded:d}){const v=V(),{description:o,name:s,href:S}=a,c=y(),g=z(N),e=P(i,a.href),x=$(()=>{c(e)},[c,e]),n=!!a.items.length,k=typeof o=="object"?o?.raw:o,h=g===j.STACKED,b=k?.includes?.("{% schemaDefinition");return t(K,{expanded:d,isSchema:b,isStacked:h,children:[t(W,{layout:g,children:[t(m,{fullWidth:!n,isStacked:h,children:[t(u,{expandable:n,children:[r(B,{to:S,"aria-label":`link to ${s}`}),s,r(I,{pageSlug:e})]}),r(D,{source:o})]}),n&&r(H,{items:a.items,routingBasePath:i})]}),n&&!d&&t(O,{type:"button",variant:"text",size:"medium",onClick:x,children:["+ ",v("openapi.actions.show","Show")]})]})}const da=w(E),K=l.div`
|
|
2
2
|
padding-top: var(--spacing-lg);
|
|
3
|
-
padding-bottom: ${({expanded:
|
|
3
|
+
padding-bottom: ${({expanded:a})=>a?"var(--spacing-xxl)":""};
|
|
4
4
|
|
|
5
5
|
/*
|
|
6
6
|
Markdoc components inside markdown that use SamplesPanel should not have padding.
|
|
7
7
|
E.g. SchemaDefinition, McpTool
|
|
8
8
|
padding is added by the TagItem itself
|
|
9
9
|
*/
|
|
10
|
-
${
|
|
11
|
-
padding-left: 0;
|
|
10
|
+
${p} ${f} {
|
|
12
11
|
padding-right: 0;
|
|
12
|
+
padding-left: 0;
|
|
13
13
|
}
|
|
14
|
-
|
|
14
|
+
|
|
15
|
+
${({isSchema:a,isStacked:i})=>a&&!i&&M`
|
|
16
|
+
${m} {
|
|
17
|
+
padding-left: 0;
|
|
18
|
+
padding-right: 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
${p} ${m} {
|
|
22
|
+
padding-left: calc(var(--panel-gap-horizontal) * 2);
|
|
23
|
+
padding-right: var(--panel-gap-horizontal);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
${p} ${f} {
|
|
27
|
+
padding-right: calc(var(--panel-gap-horizontal) * 2);
|
|
28
|
+
padding-left: var(--panel-gap-horizontal);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
${u} {
|
|
32
|
+
padding-left: calc(var(--panel-gap-horizontal) * 2);
|
|
33
|
+
padding-right: var(--panel-gap-horizontal);
|
|
34
|
+
width: calc(100% - var(--panel-samples-width));
|
|
35
|
+
${_} {
|
|
36
|
+
left: unset;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
`}
|
|
40
|
+
`,O=l(C)`
|
|
15
41
|
margin: var(--spacing-md) var(--spacing-xl) var(--spacing-xxs);
|
|
16
42
|
width: calc(100% - var(--spacing-xl) * 2);
|
|
17
43
|
|
|
18
|
-
@media screen and (min-width: ${
|
|
44
|
+
@media screen and (min-width: ${T.medium}) {
|
|
19
45
|
--button-margin-md: calc(var(--spacing-xl) * 2);
|
|
20
46
|
|
|
21
47
|
margin-left: var(--button-margin-md);
|
|
22
48
|
margin-right: var(--button-margin-md);
|
|
23
49
|
width: calc(100% - var(--button-margin-md) * 2);
|
|
24
50
|
}
|
|
25
|
-
`,
|
|
51
|
+
`,u=l(A)`
|
|
26
52
|
display: flex;
|
|
27
53
|
:hover {
|
|
28
|
-
${
|
|
54
|
+
${L} {
|
|
29
55
|
opacity: 1;
|
|
30
56
|
visibility: visible;
|
|
31
57
|
}
|
|
32
58
|
}
|
|
33
|
-
`;export{
|
|
59
|
+
`;export{da as TagItem,E as TagItemComponent};
|
package/lib/jotai/operation.d.ts
CHANGED
|
@@ -34,4 +34,4 @@ export declare function getDefaultOperationStore(pointer: string, requestValues?
|
|
|
34
34
|
export declare const allOperations: import("jotai").PrimitiveAtom<Record<string, OperationStore>> & {
|
|
35
35
|
init: Record<string, OperationStore>;
|
|
36
36
|
};
|
|
37
|
-
export declare const operationStore: import("jotai
|
|
37
|
+
export declare const operationStore: import("jotai-family").AtomFamily<string, import("jotai").WritableAtom<OperationStore, [update: Partial<OperationStore>], void>>;
|
package/lib/jotai/operation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{atom as a}from"jotai";import{atomFamily as s}from"jotai
|
|
1
|
+
import{atom as a}from"jotai";import{atomFamily as s}from"jotai-family";import u from"deepmerge";function l(e,t={},o){return{activeExampleName:o,activeOneOf:{[e]:0},requestValues:t,request:{expandedAll:void 0},response:{expandedAll:void 0}}}const r=a({}),c=s(e=>a(t=>t(r)?.[e]||l(e),(t,o,m)=>{const n=t(r),p=n[e]||l(e);o(r,{...n,[e]:u(p,m)})}));export{r as allOperations,l as getDefaultOperationStore,c as operationStore};
|
package/lib/models/example.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getValueFromMdParsedExtension as
|
|
1
|
+
import{getValueFromMdParsedExtension as l}from"../utils/index.js";function m({parser:r,infoOrRef:s,mime:t,encoding:i}){const{resolved:e}=r.deref(s);let a;e.dataValue!==void 0?a=e.dataValue:e.serializedValue!==void 0?a=e.serializedValue:a=e.value;const n=a,d=l(e,"summary"),u=l(e,"description");return{value:a,rawValue:n,summary:d,description:u,mime:t,encoding:i}}export{m as getExamples};
|
package/lib/models/mediaType.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getSchema as
|
|
1
|
+
import{getSchema as E}from"./schema.js";import{isFormUrlEncoded as M,isJsonLike as D,isXmlLike as j,isMultipartFormData as w,isSequentialMediaType as k,JsonPointer as U,mapValues as F}from"../utils/index.js";import{getExamples as c}from"./example.js";import{safeSample as R,convertSampleToString as O}from"../services/code-samples/index.js";function A({parser:t,info:{encoding:l,schema:x,itemSchema:r},schema:o,mime:n,options:{isRequestType:h,onlyRequiredInSamples:P,generatedSamplesMaxDepth:I,format:v="json"}}){const m={skipReadOnly:h,skipWriteOnly:!h,skipNonRequired:h&&P,maxSampleDepth:I,quiet:!0,format:v};let a={};const b=k(n),S=!!r,d=o?.rawSchema?.prefixItems||o?.schema?.prefixItems||Array.isArray(o?.rawSchema?.items),u=r?t.deref(r).resolved:null,y=u&&Array.isArray(u.oneOf)&&u.oneOf.length>0||o&&o.oneOf;if(o&&o.oneOf)if(b&&S&&!d){const i=[];for(const e of o.oneOf){let f=R(e.rawSchema,m,t.definition);f!==null&&(o.discriminatorProp&&typeof f=="object"&&f&&f[o.discriminatorProp]&&!e.isDefaultMapping&&(f[o.discriminatorProp]=e.title),i.push(f))}if(i.length>0){const e=O(i,n,o);a.default=c({parser:t,infoOrRef:{value:e},mime:n,encoding:l})}}else for(const i of o.oneOf){let e=R(i.rawSchema,m,t.definition);e!==null&&(o.discriminatorProp&&typeof e=="object"&&e&&e[o.discriminatorProp]&&!i.isDefaultMapping&&(e[o.discriminatorProp]=i.title),e=O(e,n,i),a[i.title]=c({parser:t,infoOrRef:{value:e},mime:n,encoding:l}))}else if(y&&u&&Array.isArray(u.oneOf))if(b&&S&&!d){const i=[];for(const e of u.oneOf){const f=t.deref(e).resolved;let p=R(f,m,t.definition);p!==null&&i.push(p)}if(i.length>0){const e=O(i,n,o);a.default=c({parser:t,infoOrRef:{value:e},mime:n,encoding:l})}}else for(const i of u.oneOf){const e=t.deref(i).resolved;let f=R(e,m,t.definition);if(f===null)continue;f=O(f,n,o);const p=e.title||(i.$ref?t.deref(i).resolved.title:"")||"variant";a[p]=c({parser:t,infoOrRef:{value:f},mime:n,encoding:l})}else if(o){let e=R(x||r,m,t.definition);e!==null?(e=O(e,n,o,!0),a={default:c({parser:t,infoOrRef:{value:e},mime:n,encoding:l})}):a={default:c({parser:t,infoOrRef:{value:null},mime:n,encoding:l})}}else a={default:c({parser:t,infoOrRef:{value:null},mime:n,encoding:l})};return a}function N(t,l,x,r,o,{operation:n,type:h,response:P,absolutePointer:I=""}){let v,m;const a=r?.itemSchema??r.schema,b=r?.itemSchema?"itemSchema":"schema";let S;const d=a&&E({parser:t,schemaOrRef:a,pointer:"",absolutePointer:U.join(I,["content",l,b]),options:o,deps:{operation:n,type:h,response:P}}),{onlyRequiredInSamples:u,generatedSamplesMaxDepth:y}=o,{encoding:i,examples:e,example:f}=r;if(!o.unstable_skipSamples){const p=s=>typeof s=="string"?s:O(s,l,d);if(e!==void 0)v=F(e,s=>{const g=t.deref(s).resolved.dataValue||t.deref(s).resolved.serializedValue||t.deref(s).resolved.value,V=p(g);return c({parser:t,infoOrRef:{value:V},mime:l,encoding:i})});else if(f!==void 0){const s=t.deref(f).resolved,g=typeof s=="object"&&s!==null&&"value"in s?s.dataValue||s.serializedValue||s.value:s,V=p(g);v={default:c({parser:t,infoOrRef:{value:V},mime:l,encoding:i})}}else D(l)||j(l)||k(l)?(v=A({parser:t,info:r,schema:d,mime:l,options:{isRequestType:x,onlyRequiredInSamples:u,generatedSamplesMaxDepth:y,format:j(l)?"xml":"json"}}),S=d?.pointer):(M(l)||w(l))&&(S=d?.pointer,m=A({parser:t,info:r,schema:d,mime:l,options:{isRequestType:x,onlyRequiredInSamples:u,generatedSamplesMaxDepth:y}}))}return{examples:v,schema:d,examplesPointer:S,name:l,isRequestType:x,formExamples:m,onlyRequiredInSamples:u,operation:n}}export{N as getMediaType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as oe from"openapi-sampler";import $ from"deepmerge";import{isObject as ce}from"@redocly/theme/core/openapi";import{areArraysEqual as ie,serializeParameterValue as I,getSecurityDetails as ue,getParameterValue as M,queryString as P,isArrayOfObjects as le,deleteEmptyArrayItem as pe}from"../../utils/index.js";import{normalizeMimeType as me,arrayMergeStrategy as J}from"../utils.js";import{MediaTypes as p}from"../../constants.js";import{HTTPSnippet as de}from"./httpsnippet/index.js";import{getActiveMediaType as fe}from"../../models/mediaContent.js";import Y from"./httpsnippet/helpers/string-utility.js";function g(t,a,o){try{return oe.sample(t,a,o)}catch(n){return console.error(`Error sampling schema: ${n.message}`),null}}function ye(t,a){return t.find(o=>{const n=o.schemes.map(s=>s.id);return ie(n,a||[])})}function he(t,{exampleName:a="",skipOptionalParameters:o=!1,withOAuth2Call:n=!1,spec:s,generatedPayloadSamplesMaxDepth:r=8,pathParams:i={},properties:u={},activeMimeName:c=""},{environment:f,requestValues:C,activeSecuritySchemeIds:T}){const l=f.server,A=t.servers.find(e=>e.url===l)||t.servers[0],b=ye(t.security,T),{securityHeaders:w,securityCookies:F,securityQueries:X,securityOAuth2ExtraCalls:K,basicAuth:Q}=Se(b||t.security?.[0],n,f),m=t?.requestBody?.content&&fe(t.requestBody.content,c),O={skipNonRequired:o,skipReadOnly:!0,maxSampleDepth:r,quiet:!0},h=C;let N=!1;const H=t.parameters.filter(e=>e.in==="header").filter(e=>!(o&&!e.required)).map(e=>({name:e.name,value:h.header?.[e.name]||M("header",e.name)||e.serverValues?.[l]?.example||e.example||I(e,g(e.schema.rawSchema,O,s))})).map(e=>(m?.name&&e.name.toLowerCase()==="content-type"&&(N=!0,e.value=m.name),e)).concat(w);!N&&m?.name&&H.unshift({name:"Content-Type",value:m?.name});const G=t.parameters.filter(e=>e.in==="cookie").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||g(e.schema.rawSchema,O,s)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:String(h.cookie?.[y]||S)});return e},[]).concat(F),W=t.parameters.filter(e=>e.in==="query").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||g(e.schema.rawSchema,O,s)))).reduce((e,_)=>{for(const[y,S]of Object.entries(_))e.push({name:y,value:le(h.query?.[y])&&JSON.stringify(pe(h.query?.[y]))||String(h.query?.[y]||S)});return e},[]).concat(X),Z=A?.url.replace(/\/$/,""),ee=t.path.replace(/^\//,""),te=`${Z}/${ee}`,re=t.parameters.filter(e=>e.in==="path").reduce((e,_)=>{const{in:y,name:S}=_;return e[S]=h.path?.[S]||_.serverValues?.[l]?.example||_.example||i[S]||M(y,S),e},{}),E=m?.name.toLowerCase(),q=E===p.MULTIPART||E===p.URL_ENCODED,R=q?m?.formExamples?.[a]:m?.examples?.[a],ae=q?m?.formExamples||{}:m?.examples||{},[U]=Object.values(ae),L=R?.serverValues?.[l]?.value||U?.serverValues?.[l]?.value,D=e=>!e||typeof e!="object"||!m?.schema?.rawSchema?null:g(ge(m.schema.rawSchema,e),{...O,format:"xml"},s),k=(()=>{if(h?.body)return h.body;if(E===p.XML){const e=D(L)||D(R?.value)||D(U?.value);if(e)return e;if(m?.schema)return g(m.schema.rawSchema,{...O,format:"xml"},s)}else{const e=m?.schema&&g(m.schema.rawSchema,{...O,format:"json"},s);return L||R?.value||U?.value||e}return""})();let v="",z=[];switch(me(E)){case p.JSON:v=JSON.stringify(j(k,u));break;case p.XML:v=k;break;case p.URL_ENCODED:case p.MULTIPART:v=P.stringify(j(k,u)),z=B(j(k,u));break;default:v=String(k||"")}const se=v?{mimeType:m?.name||p.OCTET_STREAM,text:v,params:z}:void 0,ne=t.responses.map(e=>e.code);return{method:t.httpVerb,url:te,httpVersion:"HTTP/1.1",cookies:G,headers:H,queryString:W,postData:se,headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:K,basicAuth:Q,pathParameters:re,serverVariables:f,allResponseCodes:ne}}const d={withImports:!0,withComments:!1},x={curl:{code:"shell",defaultTarget:"curl",defaultOptions:{...d,short:!0}},JavaScript:{code:"javascript",defaultTarget:"fetch",defaultOptions:{...d,withImports:!1}},"Node.js":{code:"node",defaultTarget:"fetch",defaultOptions:{...d}},Python:{code:"python",defaultTarget:"requests",defaultOptions:{...d}},"Java8+Apache":{code:"java8",defaultTarget:"apachehttp",defaultOptions:{...d}},Java:{code:"java",defaultTarget:"httpclient",defaultOptions:{...d}},"C#":{code:"csharp",defaultTarget:"httpclient",defaultOptions:{...d}},"C#+Newtonsoft":{code:"csharpNewtonsoft",defaultTarget:"httpclient",defaultOptions:{...d}},Go:{code:"go",defaultTarget:"http.DefaultClient",defaultOptions:{...d}},PHP:{code:"php",defaultTarget:"curl",defaultOptions:{...d}},Ruby:{code:"ruby",defaultTarget:"net::http",defaultOptions:{...d}},R:{code:"r",defaultTarget:"httr",defaultOptions:{...d}}};function De({lang:t,operation:a,exampleName:o,pathParams:n,properties:s,options:r={},environment:i,translate:u}){try{const{skipOptionalParameters:c,withOAuth2Call:f,spec:C,generatedPayloadSamplesMaxDepth:T,store:l,activeMimeName:A}=r,b=he(a,{exampleName:o,pathParams:n,properties:s,skipOptionalParameters:c,withOAuth2Call:f,spec:C,generatedPayloadSamplesMaxDepth:T,activeMimeName:A},{environment:i,requestValues:l.requestValues,activeSecuritySchemeIds:l.activeSecuritySchemeIds}),w=new de(b);return x[t]?w.convert(x[t].code,x[t].defaultTarget,{...x[t].defaultOptions,...r}):u("openapi.unsupportedLanguage","Language is not supported.")}catch(c){return console.error(c),u("openapi.failedToGenerateCodeSample","Failed to generate code sample.")}}function Se(t,a,o){const n={securityHeaders:[],securityCookies:[],securityQueries:[],securityOAuth2ExtraCalls:[],basicAuth:void 0},s=o?.server;for(const r of t?.schemes||[]){const i=ue(r.id,o),u=s&&r.serverValues&&r.serverValues[s],c={access_token:u?.["x-defaultAccessToken"]||r["x-defaultAccessToken"],token_type:u?.["x-defaultTokenType"]||r["x-defaultTokenType"],client_id:u?.["x-defaultClientId"]||r["x-defaultClientId"],client_secret:u?.["x-defaultClientSecret"]||r["x-defaultClientSecret"]},f=u?.["x-defaultUsername"]||r["x-defaultUsername"],C=u?.["x-defaultPassword"]||r["x-defaultPassword"],T=u&&"scopes"in u?u.scopes||[]:r.scopes||[];switch(r.type){case"openIdConnect":n.securityHeaders?.push({name:"Authorization",value:c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${c.token_type||i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>"});break;case"oauth2":{const l=c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>";r.flows.deviceAuthorization&&a?n.securityOAuth2ExtraCalls.push(Te(r.flows.deviceAuthorization,T)):r.flows.clientCredentials&&a?n.securityOAuth2ExtraCalls.push(Oe(r.flows.clientCredentials,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})):r.flows.password&&a&&n.securityOAuth2ExtraCalls.push(_e(r.flows.password,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})),n.securityHeaders?.push({name:"Authorization",value:l});break}case"apiKey":{const l=c.access_token||i.raw||"YOUR_API_KEY_HERE";r.in==="header"&&n.securityHeaders?.push({name:r.name,value:l}),r.in==="cookie"&&n.securityCookies.push({name:r.name,value:l}),r.in==="query"&&n.securityQueries.push({name:r.name,value:l});break}case"http":if(r.scheme==="basic")n.basicAuth={username:f||i.username||`<${Y.toSnakeCase("Username")}>`,password:C||i.password||`<${Y.toSnakeCase("Password")}>`};else{const l=c?.access_token||i.token?.access_token||`<YOUR_${r.bearerFormat||"TOKEN"}_HERE>`;n.securityHeaders?.push({name:"Authorization",value:`${ve(r.scheme||"bearer")} ${l}`})}break}}return n}function Te(t,a){const o=t["x-defaultClientId"]??"YOUR_CLIENT_ID",{tokenUrl:n,deviceAuthorizationUrl:s}=t;return{method:"POST",url:s,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"client_id",value:o},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"deviceAuthorization",tokenUrl:n,clientId:o}}function _e(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"grant_type",value:"password"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},{name:"username",value:o.username||"<username>"},{name:"password",value:o.password||"<password>"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"password",tokenUrl:n,clientId:s}}function Oe(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:p.URL_ENCODED},{name:"Accept",value:p.JSON}],queryString:[],postData:{mimeType:p.URL_ENCODED,text:"",params:[{name:"grant_type",value:"client_credentials"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"clientCredentials",tokenUrl:n,clientId:s}}function j(t,a){if(t){if(ce(t))return Object.keys(t).length>0&&Object.keys(a).length===0?t:$(t,a,{arrayMerge:J});try{return $(JSON.parse(t),a,{arrayMerge:J})}catch{return!1}}return!1}function B(t,a=""){const o=[];for(const[n,s]of Object.entries(t)){const r=a?`${a}[${n}]`:n;if(typeof s=="object"&&s!==null)o.push(...B(s,r));else{const i=Array.isArray(t)&&typeof s=="string"&&a?a:r;o.push({name:i,value:String(s)})}}return o}function V(t){return t!==void 0}function ve(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ge(t,a){if(!t||typeof t!="object"||!a||typeof a!="object")return t;const o=JSON.parse(JSON.stringify(t));function n(s,r){if(!(!s||!r||typeof s!="object"||typeof r!="object")&&s.properties){for(const i in s.properties)if(r[i]!==void 0){const u=s.properties[i],c=r[i];if(u.type==="object"&&typeof c=="object"&&!Array.isArray(c))n(u,c);else if(u.type==="array"&&Array.isArray(c)&&c.length>0){const f=c[0];u.items&&u.items.properties&&n(u.items,f)}else u.example=c}}}return n(o,a),o}export{ve as capitalizeFirst,De as getCodeSample,j as getDataRequest,V as isDefined,g as safeSample};
|
|
1
|
+
import*as ne from"openapi-sampler";import L from"deepmerge";import{isObject as oe}from"@redocly/theme/core/openapi";import{areArraysEqual as ce,serializeParameterValue as I,getSecurityDetails as ie,getParameterValue as $,queryString as P,isArrayOfObjects as ue,deleteEmptyArrayItem as le}from"../../utils/index.js";import{normalizeMimeType as pe,arrayMergeStrategy as M}from"../utils.js";import{MediaTypes as m}from"../../constants.js";import{HTTPSnippet as me}from"./httpsnippet/index.js";import{getActiveMediaType as de}from"../../models/mediaContent.js";import J from"./httpsnippet/helpers/string-utility.js";function C(t,a,o){try{return ne.sample(t,a,o)}catch(n){return console.error(`Error sampling schema: ${n.message}`),null}}function fe(t,a){return t.find(o=>{const n=o.schemes.map(s=>s.id);return ce(n,a||[])})}function ye(t,{exampleName:a="",skipOptionalParameters:o=!1,withOAuth2Call:n=!1,spec:s,generatedPayloadSamplesMaxDepth:r=8,pathParams:i={},properties:u={},activeMimeName:c=""},{environment:y,requestValues:k,activeSecuritySchemeIds:T}){const l=y.server,b=t.servers.find(e=>e.url===l)||t.servers[0],w=fe(t.security,T),{securityHeaders:R,securityCookies:B,securityQueries:F,securityOAuth2ExtraCalls:X,basicAuth:K}=he(w||t.security?.[0],n,y),p=t?.requestBody?.content&&de(t.requestBody.content,c),g={skipNonRequired:o,skipReadOnly:!0,maxSampleDepth:r,quiet:!0},S=k;let H=!1;const N=t.parameters.filter(e=>e.in==="header").filter(e=>!(o&&!e.required)).map(e=>({name:e.name,value:S.header?.[e.name]||$("header",e.name)||e.serverValues?.[l]?.example||e.example||I(e,C(e.schema.rawSchema,g,s))})).map(e=>(p?.name&&e.name.toLowerCase()==="content-type"&&(H=!0,e.value=p.name),e)).concat(R);!H&&p?.name&&N.unshift({name:"Content-Type",value:p?.name});const Q=t.parameters.filter(e=>e.in==="cookie").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||C(e.schema.rawSchema,g,s)))).reduce((e,f)=>{for(const[h,_]of Object.entries(f))e.push({name:h,value:String(S.cookie?.[h]||_)});return e},[]).concat(B),G=t.parameters.filter(e=>e.in==="query").filter(e=>!(o&&!e.required)).map(e=>P.parse(I(e,e.serverValues?.[l]?.example||e.example||C(e.schema.rawSchema,g,s)))).reduce((e,f)=>{for(const[h,_]of Object.entries(f))e.push({name:h,value:ue(S.query?.[h])&&JSON.stringify(le(S.query?.[h]))||String(S.query?.[h]||_)});return e},[]).concat(F),W=b?.url.replace(/\/$/,""),Z=t.path.replace(/^\//,""),ee=`${W}/${Z}`,te=t.parameters.filter(e=>e.in==="path").reduce((e,f)=>{const{in:h,name:_}=f;return e[_]=S.path?.[_]||f.serverValues?.[l]?.example||f.example||i[_]||$(h,_),e},{}),q=p?.name.toLowerCase(),E=p?.examples?.[a]||p?.formExamples?.[a],re={...p?.formExamples||{},...p?.examples||{}},[x]=Object.values(re),U=E?.serverValues?.[l]?.value||x?.serverValues?.[l]?.value,D=e=>!e||typeof e!="object"||!p?.schema?.rawSchema?null:C(Oe(p.schema.rawSchema,e),{...g,format:"xml"},s),v=(()=>{if(S?.body)return S.body;if(q===m.XML){const e=U||E?.value||x?.value;if(typeof e=="string")return e;const f=D(U)||D(E?.value)||D(x?.value);if(f)return f;if(p?.schema)return C(p.schema.rawSchema,{...g,format:"xml"},s)}else{const e=p?.schema&&C(p.schema.rawSchema,{...g,format:"json"},s);return U||E?.value||x?.value||e}return""})();let O="",z=[];switch(pe(q)){case m.JSON:O=JSON.stringify(j(v,u));break;case m.XML:O=v;break;case m.MULTIPART:case m.URL_ENCODED:typeof v=="string"?O=v:(O=P.stringify(j(v,u)),z=Y(j(v,u)));break;default:O=String(v||"")}const ae=O?{mimeType:p?.name||m.OCTET_STREAM,text:O,params:z}:void 0,se=t.responses.map(e=>e.code);return{method:t.httpVerb,url:ee,httpVersion:"HTTP/1.1",cookies:Q,headers:N,queryString:G,postData:ae,headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:X,basicAuth:K,pathParameters:te,serverVariables:y,allResponseCodes:se}}const d={withImports:!0,withComments:!1},A={curl:{code:"shell",defaultTarget:"curl",defaultOptions:{...d,short:!0}},JavaScript:{code:"javascript",defaultTarget:"fetch",defaultOptions:{...d,withImports:!1}},"Node.js":{code:"node",defaultTarget:"fetch",defaultOptions:{...d}},Python:{code:"python",defaultTarget:"requests",defaultOptions:{...d}},"Java8+Apache":{code:"java8",defaultTarget:"apachehttp",defaultOptions:{...d}},Java:{code:"java",defaultTarget:"httpclient",defaultOptions:{...d}},"C#":{code:"csharp",defaultTarget:"httpclient",defaultOptions:{...d}},"C#+Newtonsoft":{code:"csharpNewtonsoft",defaultTarget:"httpclient",defaultOptions:{...d}},Go:{code:"go",defaultTarget:"http.DefaultClient",defaultOptions:{...d}},PHP:{code:"php",defaultTarget:"curl",defaultOptions:{...d}},Ruby:{code:"ruby",defaultTarget:"net::http",defaultOptions:{...d}},R:{code:"r",defaultTarget:"httr",defaultOptions:{...d}}};function Ue({lang:t,operation:a,exampleName:o,pathParams:n,properties:s,options:r={},environment:i,translate:u}){try{const{skipOptionalParameters:c,withOAuth2Call:y,spec:k,generatedPayloadSamplesMaxDepth:T,store:l,activeMimeName:b}=r,w=ye(a,{exampleName:o,pathParams:n,properties:s,skipOptionalParameters:c,withOAuth2Call:y,spec:k,generatedPayloadSamplesMaxDepth:T,activeMimeName:b},{environment:i,requestValues:l.requestValues,activeSecuritySchemeIds:l.activeSecuritySchemeIds}),R=new me(w);return A[t]?R.convert(A[t].code,A[t].defaultTarget,{...A[t].defaultOptions,...r}):u("openapi.unsupportedLanguage","Language is not supported.")}catch(c){return console.error(c),u("openapi.failedToGenerateCodeSample","Failed to generate code sample.")}}function he(t,a,o){const n={securityHeaders:[],securityCookies:[],securityQueries:[],securityOAuth2ExtraCalls:[],basicAuth:void 0},s=o?.server;for(const r of t?.schemes||[]){const i=ie(r.id,o),u=s&&r.serverValues&&r.serverValues[s],c={access_token:u?.["x-defaultAccessToken"]||r["x-defaultAccessToken"],token_type:u?.["x-defaultTokenType"]||r["x-defaultTokenType"],client_id:u?.["x-defaultClientId"]||r["x-defaultClientId"],client_secret:u?.["x-defaultClientSecret"]||r["x-defaultClientSecret"]},y=u?.["x-defaultUsername"]||r["x-defaultUsername"],k=u?.["x-defaultPassword"]||r["x-defaultPassword"],T=u&&"scopes"in u?u.scopes||[]:r.scopes||[];switch(r.type){case"openIdConnect":n.securityHeaders?.push({name:"Authorization",value:c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${c.token_type||i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>"});break;case"oauth2":{const l=c.access_token?`${c.token_type||"Bearer"} ${c.access_token}`:i.token?`${i.token.token_type||"Bearer"} ${i.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>";r.flows.deviceAuthorization&&a?n.securityOAuth2ExtraCalls.push(Se(r.flows.deviceAuthorization,T)):r.flows.clientCredentials&&a?n.securityOAuth2ExtraCalls.push(Te(r.flows.clientCredentials,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})):r.flows.password&&a&&n.securityOAuth2ExtraCalls.push(_e(r.flows.password,T,{...i,client_id:c.client_id||i.client_id,client_secret:c.client_secret||i.client_secret})),n.securityHeaders?.push({name:"Authorization",value:l});break}case"apiKey":{const l=c.access_token||i.raw||"YOUR_API_KEY_HERE";r.in==="header"&&n.securityHeaders?.push({name:r.name,value:l}),r.in==="cookie"&&n.securityCookies.push({name:r.name,value:l}),r.in==="query"&&n.securityQueries.push({name:r.name,value:l});break}case"http":if(r.scheme==="basic")n.basicAuth={username:y||i.username||`<${J.toSnakeCase("Username")}>`,password:k||i.password||`<${J.toSnakeCase("Password")}>`};else{const l=c?.access_token||i.token?.access_token||`<YOUR_${r.bearerFormat||"TOKEN"}_HERE>`;n.securityHeaders?.push({name:"Authorization",value:`${ve(r.scheme||"bearer")} ${l}`})}break}}return n}function Se(t,a){const o=t["x-defaultClientId"]??"YOUR_CLIENT_ID",{tokenUrl:n,deviceAuthorizationUrl:s}=t;return{method:"POST",url:s,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:m.URL_ENCODED},{name:"Accept",value:m.JSON}],queryString:[],postData:{mimeType:m.URL_ENCODED,text:"",params:[{name:"client_id",value:o},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"deviceAuthorization",tokenUrl:n,clientId:o}}function _e(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:m.URL_ENCODED},{name:"Accept",value:m.JSON}],queryString:[],postData:{mimeType:m.URL_ENCODED,text:"",params:[{name:"grant_type",value:"password"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},{name:"username",value:o.username||"<username>"},{name:"password",value:o.password||"<password>"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"password",tokenUrl:n,clientId:s}}function Te(t,a,o){const{tokenUrl:n}=t,s=o.client_id??"YOUR_CLIENT_ID";return{method:"POST",url:t.tokenUrl,httpVersion:"HTTP/1.1",headers:[{name:"Content-Type",value:m.URL_ENCODED},{name:"Accept",value:m.JSON}],queryString:[],postData:{mimeType:m.URL_ENCODED,text:"",params:[{name:"grant_type",value:"client_credentials"},{name:"client_id",value:s},{name:"client_secret",value:o.client_secret||"YOUR_CLIENT_SECRET"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(V)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[],flowType:"clientCredentials",tokenUrl:n,clientId:s}}function j(t,a){if(t){if(oe(t))return Object.keys(t).length>0&&Object.keys(a).length===0?t:L(t,a,{arrayMerge:M});try{return L(JSON.parse(t),a,{arrayMerge:M})}catch{return!1}}return!1}function Y(t,a=""){const o=[];for(const[n,s]of Object.entries(t)){const r=a?`${a}[${n}]`:n;if(typeof s=="object"&&s!==null)o.push(...Y(s,r));else{const i=Array.isArray(t)&&typeof s=="string"&&a?a:r;o.push({name:i,value:String(s)})}}return o}function V(t){return t!==void 0}function ve(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Oe(t,a){if(!t||typeof t!="object"||!a||typeof a!="object")return t;const o=JSON.parse(JSON.stringify(t));function n(s,r){if(!(!s||!r||typeof s!="object"||typeof r!="object")&&s.properties){for(const i in s.properties)if(r[i]!==void 0){const u=s.properties[i],c=r[i];if(u.type==="object"&&typeof c=="object"&&!Array.isArray(c))n(u,c);else if(u.type==="array"&&Array.isArray(c)&&c.length>0){const y=c[0];u.items&&u.items.properties&&n(u.items,y)}else u.example=c}}}return n(o,a),o}export{ve as capitalizeFirst,Ue as getCodeSample,j as getDataRequest,V as isDefined,C as safeSample};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeMimeType as
|
|
1
|
+
import{normalizeMimeType as h,unescapeServerVariables as p}from"../../utils.js";import{MediaTypes as c}from"../../../constants.js";import e from"./targets/index.js";import m from"./helpers/reducer.js";import{queryString as b}from"../../../utils/index.js";import{urlParse as j}from"../../../utils/url.js";class D{request;constructor(a){const r={...a};this.request=this.prepare({...r,httpVersion:r.httpVersion||"HTTP/1.1",queryString:r.queryString||[],headers:r.headers||[],cookies:r.cookies||[],postData:r.postData?{...r.postData,jsonObj:void 0,paramsObj:void 0}:void 0,bodySize:0,headersSize:0,queryObj:{},headersObj:{},cookiesObj:{},allHeaders:{},uriObj:{},fullUrl:"",pathParameters:r.pathParameters||{},serverVariables:r.serverVariables||{}})}prepare(a){if(a.queryString&&a.queryString.length&&(a.queryObj=a.queryString.reduce(m,{})),a.headers&&a.headers.length){const i=/^HTTP\/2/;a.headersObj=a.headers.reduce(function(t,s){let n=s.name;return a.httpVersion.match(i)&&(n=n.toLowerCase()),t[n]=s.value,t},{})}a.cookies&&a.cookies.length&&(a.cookiesObj=a.cookies.reduceRight(function(i,t){return i[t.name]=t.value,i},{}));const r=a.cookies.map(function(i){return encodeURIComponent(i.name)+"="+encodeURIComponent(i.value)});if(r.length&&(a.allHeaders.cookie=r.join("; ")),a.postData)switch(h(a.postData.mimeType)){case"multipart/mixed":case"multipart/related":case c.MULTIPART:case"multipart/alternative":break;case c.URL_ENCODED:a.postData?.params?.length>0&&(a.postData.paramsObj=a.postData.params.reduce(m,{}),a.postData.text=b.stringify(a.postData.paramsObj));break;case"text/json":case"text/x-json":case c.JSON:case"application/x-json":if(a.postData.text)try{a.postData.jsonObj=JSON.parse(a.postData.text)}catch{a.postData.mimeType="text/plain"}break}if(a.allHeaders=Object.assign(a.allHeaders,a.headersObj),a.uriObj=j(a.url,!0),!a.uriObj)return{...a,uriObj:{protocol:"",path:"",queryObj:{},query:{}}};if(a.queryObj)for(const[i,t]of Object.entries(a.queryObj))a.uriObj.searchParams.has(i,t)||a.uriObj.searchParams.set(i,t);a.uriObj.query=Object.fromEntries(a.uriObj.searchParams.entries()),a.queryObj=a.uriObj.query,a.uriObj.path=a.uriObj.pathname=p(a.uriObj.pathname);const o=new URL(a.uriObj.toString());return o.search="",a.url=p(o.toString()),a.uriObj.search&&(a.uriObj.path=a.uriObj.pathname+"?"+a.uriObj.search),a.fullUrl=p(a.uriObj.toString()),a}convert(a,r,o){!o&&r&&(o=r);const i=this._matchTarget(a,r);if(i){const t=i(this.request,o,{target:a,client:r});return t.length===1?t[0]:t}throw new Error("Cannot match target")}_matchTarget(a,r){return Object.prototype.hasOwnProperty.call(e,a)?typeof r=="string"&&typeof e[a][r]=="function"?e[a][r]:e[a][e[a].info.default]:!1}}export{D as HTTPSnippet};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isObject as
|
|
2
|
-
`).forEach((s
|
|
1
|
+
import{isObject as T}from"@redocly/theme/core/openapi";import{CodeBuilder as E}from"../../helpers/code-builder.js";import{HTTPSnippet as O}from"../../index.js";import{buildUrlExpression as x,printUrlVariablesDeclarations as k}from"../../helpers/code-helpers.js";import{isEmptyObject as H,normalizeMimeType as m}from"../../../../utils.js";import{capitalizeFirst as v}from"../../../generator.js";import{Lang as M}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{isLastInArray as R,isLastProperty as L}from"../../../../../utils/index.js";import{buildCSharpDeviceAuthorizationCodeSnippet as j}from"../../helpers/device-auth-snippets.js";const N=function(e,d,{target:b,client:w}){const r=Object.assign({indent:" ",withWrapper:!0},d),t=new E({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:!0,lang:M.CSHARP}),A=U(e.method);if(r.withComments&&P(t),r.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(h(i.JSON)||h(i.XML)||e.basicAuth)&&t.push("using System.Text;"),(h(i.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(h(i.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Text.Json;"),(u()||!e.postData?.params?.length&&e.postData?.text&&m(e.postData.mimeType)===i.MULTIPART)&&t.push("using System.IO;"),(u()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"public static async Task Main()"),t.push(1,"{")),e.securityOAuth2ExtraCalls?.length){const a=e.securityOAuth2ExtraCalls?.[0],s=new O(a).convert(b,w,{...r,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(s),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?j(t,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank())}const D=Object.keys(e.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(D.length?(t.push(2,"System.Net.Http.HttpClient client = new()"),t.push(2,"{"),t.push(3,"DefaultRequestHeaders ="),t.push(3,"{"),D.forEach(a=>{const s=a.toLowerCase()==="authorization";t.push(4,'{"%s", %s},',a,e.securityOAuth2ExtraCalls?.length&&s?'"Bearer " + accessToken':`"${e.allHeaders[a]}"`)}),t.push(3,"}"),t.push(2,"};")):t.push(2,"System.Net.Http.HttpClient client = new();"),t.blank(),e.basicAuth){const{username:a,password:s}=e.basicAuth;t.push(2,`string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${s}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);'),t.blank()}if(e.postData)switch(m(e.postData.mimeType)){case i.URL_ENCODED:e.postData.params.length?(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),e.postData.params.forEach(a=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',a.name,a.value)}),t.blank()):e.postData.text&&(t.blank(),t.push(3,'var postData = "%s";',e.postData.text));break;case i.MULTIPART:if(e.postData.params&&e.postData.params.length>0)t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),e.postData.params.forEach(a=>{a.fileName?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',a.fileName,a.name,a.fileName):t.push(2,'postData.Add(new StringContent("%s"), "%s");',a.value,a.name)});else if(e.postData.text){const a=e.postData.text,s=a.match(/^--([^\r\n]+)/);if(s){const n=s[1],p=a.split(new RegExp(`--${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(o=>o.trim().length>0);t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),p.forEach(o=>{const l=o.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(l){const g=l[1],f=l[2],C=o.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),S=(C?C[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');f?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',f,g,f):t.push(2,'postData.Add(new StringContent("%s"), "%s");',S,g)}})}else{t.blank();const n=e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"');t.push(2,'var postData = new StringContent("%s");',n)}}break;case i.JSON:e.postData.jsonObj&&(t.push(2,"string json = JsonSerializer.Serialize(new"),t.push(2,"{"),c(e.postData.jsonObj,3),t.push(2,"});"),t.blank(),t.push(2,'using StringContent postData = new(json, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.XML:e.postData.text&&(e.postData.text.trim().split(`
|
|
2
|
+
`).forEach((a,s)=>{const n=(s===0?'string xml = @"':"")+a.replace(/"/g,'""');t.push(s===0?2:3,n)}),t.push(2,'";'),t.push(2,'using StringContent postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.OCTET_STREAM:e.postData.text&&(t.push(2,'byte[] bytes = Convert.FromBase64String("%s");',e.postData.text),t.push(2,"var postData = new ByteArrayContent(bytes);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));break}else u()&&(t.push(2,"var ms = new MemoryStream();"),t.push(2,"var postData = new StreamContent(ms);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return k(e,t,3),t.push(2,"using HttpResponseMessage %s = await client.%sAsync(%s%s);",t.var("request"),A,x(e,t),r.withImports?F(e.method)?m(e.postData&&e.postData.mimeType)===i.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||u()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),r.withWrapper&&(t.push(2,"string response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function h(a){return e.postData&&m(e.postData.mimeType)===a}function u(){return e.headersObj&&e.headersObj["Content-Type"]===i.OCTET_STREAM}function y(a,s){a.forEach((n,p)=>{const o=!R(a,p);Array.isArray(n)?y(n,s+1):T(n)?(t.push(s+1,"new {"),c(n,s+2),t.push(s+1,"}%s",o?",":"")):t.push(s+1,'"%s"%s',n,o?",":"")}),t.push(s,"},")}function c(a,s){for(const[n,p]of Object.entries(a)){const o=!L(a,n);if(Array.isArray(p))t.push(s,"%s = new[] {",n),y(p,s);else if(T(p)){const l=H(p);t.push(s,"%s = new %s",n,l?"{},":"{"),l||(c(p,s+1),t.push(s,"}%s",o?",":""))}else t.push(s,'%s = "%s"%s',n,p,o?",":"")}}},X={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var Y=N;function P(e){e.push("// Requires >= .NET 5"),e.blank()}function U(e){return v(e.toLowerCase())}function F(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{Y as default,X as info};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
`).forEach((a,
|
|
1
|
+
import w from"stringify-object";import{CodeBuilder as A}from"../../helpers/code-builder.js";import{HTTPSnippet as S}from"../../index.js";import{addIndentation as E,buildUrlExpression as O,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{normalizeMimeType as h}from"../../../../utils.js";import{capitalizeFirst as x}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";import{buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet as R}from"../../helpers/device-auth-snippets.js";const M=function(e,c,{target:g,client:C}){const i=Object.assign({indent:" ",withWrapper:!0},c),t=new A({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:!0,lang:k.CSHARPNEWTONSOFT}),y=H(e.method);if(i.withComments&&N(t),i.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(o(s.JSON)||o(s.XML)||e.basicAuth)&&t.push("using System.Text;"),(o(s.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(o(s.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using Newtonsoft.Json.Linq;"),(r()||!e.postData?.params?.length&&e.postData?.text&&h(e.postData.mimeType)===s.MULTIPART)&&t.push("using System.IO;"),(r()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"private readonly IHttpClientFactory _httpClientFactory;"),t.push(1,"public static async Task Main(string[] args)"),t.push(1,"{"),t.push(2,"var client = _httpClientFactory.CreateClient();")),e.securityOAuth2ExtraCalls?.length){const a=e.securityOAuth2ExtraCalls?.[0],n=new S(a).convert(g,C,{...i,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(n),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?R(t,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank())}const d=Object.keys(e.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(d.length&&d.forEach(a=>{const n=a.toLowerCase()==="authorization";t.push(2,'client.DefaultRequestHeaders.Add("%s", %s);',a,e.securityOAuth2ExtraCalls?.length&&n?'"Bearer " + accessToken':`"${e.allHeaders[a]}"`)}),e.basicAuth){const{username:a,password:n}=e.basicAuth;t.push(2,`var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${n}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);')}if(e.postData)switch(h(e.postData.mimeType)){case s.URL_ENCODED:e.postData.params.length?(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),e.postData.params.forEach(a=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',a.name,a.value)}),t.blank()):e.postData.text&&(t.blank(),t.push(3,'var postData = "%s";',e.postData.text));break;case s.MULTIPART:if(e.postData.params&&e.postData.params.length>0)t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),e.postData.params.forEach(a=>{a.fileName?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',a.fileName,a.name,a.fileName):t.push(2,'postData.Add(new StringContent("%s"), "%s");',a.value,a.name)});else if(e.postData.text){const a=e.postData.text,n=a.match(/^--([^\r\n]+)/);if(n){const p=n[1],T=a.split(new RegExp(`--${p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(l=>l.trim().length>0);t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),T.forEach(l=>{const u=l.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(u){const f=u[1],m=u[2],D=l.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),b=(D?D[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');m?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',m,f,m):t.push(2,'postData.Add(new StringContent("%s"), "%s");',b,f)}})}else{t.blank();const p=e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"');t.push(2,'var postData = new StringContent("%s");',p)}}break;case s.JSON:e.postData.jsonObj&&(t.push(2,`JObject json = JObject.Parse(@"${E(w(e.postData.jsonObj,{indent:i.indent,inlineCharacterLimit:25}).replace(/"/g,'""'),{level:3,firstLine:!1})}");`),t.push(2,'var postData = new StringContent(json.ToString(), Encoding.UTF8, "%s");',e.postData.mimeType));break;case s.XML:e.postData.text&&(e.postData.text.trim().split(`
|
|
2
|
+
`).forEach((a,n)=>{const p=(n===0?'string xml = @"':"")+a.replace(/"/g,'""');t.push(n===0?3:4,p)}),t.push(2,'";'),t.push(2,'var postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break;case s.OCTET_STREAM:e.postData.text&&(t.push(2,'byte[] bytes = Convert.FromBase64String("%s");',e.postData.text),t.push(2,"var postData = new ByteArrayContent(bytes);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));break}else r()&&(t.push(2,"var ms = new MemoryStream();"),t.push(2,"var postData = new StreamContent(ms);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return v(e,t,3),t.push(2,"var %s = await client.%sAsync(%s%s);",t.var("request"),y,O(e,t),i.withImports?L(e.method)?h(e.postData&&e.postData.mimeType)===s.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||r()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),i.withWrapper&&(t.push(2,"var response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function o(a){return e.postData&&h(e.postData.mimeType)===a}function r(){return e.headersObj&&e.headersObj["Content-Type"]===s.OCTET_STREAM}},$={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var z=M;function N(e){e.push("/*"),e.push(" * Requires >= .NET 5"),e.push(" *"),e.push(' * Requires package "Newtonsoft.Json" >= 9.01'),e.push(" * See here for installation details:"),e.push(" * https://www.newtonsoft.com/json"),e.push(" */"),e.blank()}function H(e){return x(e.toLowerCase())}function L(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{z as default,$ as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as
|
|
2
|
-
`).map(
|
|
3
|
-
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${
|
|
1
|
+
import{CodeBuilder as N}from"../../helpers/code-builder.js";import{HTTPSnippet as k}from"../../index.js";import{Lang as R}from"../../helpers/constants.js";import{buildUrlExpression as E,printUrlVariablesDeclarations as O}from"../../helpers/code-helpers.js";import{normalizeMimeType as g}from"../../../../utils.js";import{MediaTypes as l}from"../../../../../constants.js";import{buildGoDeviceAuthorizationCodeSnippet as C}from"../../helpers/device-auth-snippets.js";const t=1;function d(a={},m){return g(a.mimeType)===m}const B=function(a,m,{target:D,client:c}){const i={capitalize:!0,showBoilerplate:!0,checkErrors:!0,printBody:!0,timeout:-1,indent:" ",...m},h=a.securityOAuth2ExtraCalls?.[0],n=i.checkErrors?"err":"_",u=a.method.toUpperCase(),e=new N({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:i.capitalize,lang:R.GO}),p=()=>{i.checkErrors&&e.push(t,"if err != nil {").push(t+1,"panic(err)").push(t,"}")};if(i.showBoilerplate&&(e.push("package main").blank().push("import (").push(t,'"fmt"'),(i.timeout>0||h?.flowType==="deviceAuthorization")&&e.push(t,'"time"'),h&&e.push(t,'"encoding/json"'),d(a.postData,l.MULTIPART)&&(e.push(t,'"mime/multipart"'),e.push(t,'"io"'),e.push(t,'"bytes"')),(d(a.postData,l.URL_ENCODED)||d(a.securityOAuth2ExtraCalls?.[0]?.postData,l.URL_ENCODED))&&(e.push(t,'"net/url"'),e.push(t,'"strconv"')),(d(a.postData,l.JSON)||d(a.securityOAuth2ExtraCalls?.[0]?.postData,l.JSON))&&e.push(t,'"bytes"'),(a.postData&&!d(a.postData,l.JSON)||h)&&e.push(t,'"strings"'),e.push(t,'"net/http"'),i.printBody&&e.push(t,'"io/ioutil"'),e.push(")").blank().push("func main() {")),Object.keys(a.allHeaders).length&&Object.keys(a.allHeaders).forEach(r=>{a.allHeaders[r]=`"${a.allHeaders[r]}"`}),h){const r="oAuth2",s=i.checkErrors?`${n} := `:"",o=i.capitalize?"Res":"res",f=new k(h).convert(D,c,{...i,printBody:!1,variablesPrefix:r,showBoilerplate:!1});e.push(f).blank(),h.flowType==="deviceAuthorization"?(e.push(t,`var ${r}${o}Body struct {`).push(t+1,"Device_code string").push(t+1,"Interval int64").push(t+1,"Expires_in int64").push(t,"}").push(t,`${s}json.NewDecoder(${r}${o}.Body).Decode(&${r}${o}Body)`).blank(),p(),C(e,{tokenUrl:h.tokenUrl??"YOUR_TOKEN_URL",clientId:h.clientId??"YOUR_CLIENT_ID",level:t}),a.allHeaders.Authorization='"Bearer " + accessToken'):(e.push(t,`var ${r}${o}Body struct {`).push(t+1,"Access_token string").push(t,"}").push(t,`${s}json.NewDecoder(${r}${o}.Body).Decode(&${r}${o}Body)`).blank(),p(),a.allHeaders.Authorization=`"Bearer " + ${r}${o}Body.Access_token`)}if(O(a,e,t),i.timeout>0&&(c=e.var("client"),e.push(t,"%s := http.Client{",c).push(t+1,"Timeout: time.Duration(%s * time.Second),",i.timeout).push(t,"}").blank()),e.push(t,`${e.var("reqUrl")} := ${E(a,e)}`),a.postData){let r;switch(g(a.postData.mimeType)){case l.URL_ENCODED:a.postData.params.length?(e.push(t,"%s := url.Values{}",e.var("data")),a.postData.params.forEach(s=>{e.push(t,'%s.Set("%s", "%s")',e.var("data"),s.name,s.value)}),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s.Encode()))',e.var("req"),n,u,e.var("reqUrl"),e.var("data")),a.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}.Encode()))`):a.postData.text&&(e.push(t,'%s := "%s"',e.var("data"),a.postData.text),e.push(t,'%s, %s := http.NewRequest("%s", %s, strings.NewReader(%s))',e.var("req"),n,u,e.var("reqUrl"),e.var("data")),a.allHeaders["Content-Length"]=`strconv.Itoa(len(${e.var("data")}))`);break;case l.JSON:r=JSON.stringify(a.postData.jsonObj,null,2).split(`
|
|
2
|
+
`).map(s=>i.indent+s).join(`
|
|
3
|
+
`).trim(),e.push(t,`var ${e.var("data")} = []byte(\`${r}\`)`),e.push(t,'%s, %s := http.NewRequest("%s", %s, bytes.NewBuffer(%s))',e.var("req"),n,u,e.var("reqUrl"),e.var("data"));break;case l.MULTIPART:if(e.push(t,"%s := &bytes.Buffer{}",e.var("data")).push(t,"writer := multipart.NewWriter(%s)",e.var("data")),a.postData.params&&a.postData.params.length>0)a.postData.params.forEach(s=>{if(!s.fileName&&!s.contentType){e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${s.name}Fw`),s.name).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${s.name}Fw`),s.value),p();return}s.fileName&&(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${s.name}Fw`),n,s.name,s.fileName),p())});else if(a.postData.text){const s=a.postData.text,o=s.match(/^--([^\r\n]+)/);if(o){const f=o[1];s.split(new RegExp(`--${f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(y=>y.trim().length>0).forEach(y=>{const w=y.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(w){const v=w[1],$=w[2],b=y.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),q=(b?b[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');$?(e.push(t,'%s, %s = writer.CreateFormFile("%s", "%s")',e.var(`${v}Fw`),n,v,$),p()):(e.push(t,'%s, _ := writer.CreateFormField("%s")',e.var(`${v}Fw`),v).push(t,'_, %s = io.Copy(%s, strings.NewReader("%s"))',n,e.var(`${v}Fw`),q),p())}})}else{e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(a.postData.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload"));break}}e.push(t,"writer.Close()").blank().push(t,"%s := bytes.NewReader(%s.Bytes())",e.var("payload"),e.var("data")).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload")),a.allHeaders["Content-Type"]="writer.FormDataContentType()";break;default:a.postData.text&&e.push(t,"%s := strings.NewReader(%s)",e.var("payload"),JSON.stringify(a.postData?.text)).push(t,'%s, %s := http.NewRequest("%s", %s, %s)',e.var("req"),n,u,e.var("reqUrl"),e.var("payload"))}}else e.push(t,'%s, %s := http.NewRequest("%s", %s, nil)',e.var("req"),n,u,e.var("reqUrl"));if(Object.getOwnPropertyNames(a.queryObj).length){e.blank().push(t,`${e.var("query")} := ${e.var("req")}.URL.Query()`);for(const r in a.queryObj){const s=a.queryObj[r],f=typeof s=="string"&&/^\[.*\]$/.test(s)?`\`${s}\``:`"${s}"`;e.push(t,`${e.var("query")}.Add("${r}", ${f})`)}e.push(t,`${e.var("req")}.URL.RawQuery = ${e.var("query")}.Encode()`).blank()}if(p(),a.basicAuth){const{username:r,password:s}=a.basicAuth;e.push(t,`%s.SetBasicAuth("${r}", "${s}")`,e.var("req"))}return Object.keys(a.allHeaders).length&&Object.keys(a.allHeaders).forEach(r=>{e.push(t,'%s.Header.Add("%s", %s)',e.var("req"),r,a.allHeaders[r])}),e.push(t,"%s, %s := %s.Do(%s)",e.var("res"),n,c,e.var("req")),p(),i.printBody&&(e.push(t,"defer %s.Body.Close()",e.var("res")).push(t,"%s, %s := ioutil.ReadAll(%s.Body)",e.var("body"),n,e.var("res")),p()),e.blank().push(t,"fmt.Println(%s)",e.var("res")),i.printBody&&e.push(t,"fmt.Println(string(%s))",e.var("body")),i.showBoilerplate&&e.push("}"),e.join()},P={key:"native",title:"NewRequest",link:"http://golang.org/pkg/net/http/#NewRequest",description:"Golang HTTP client request"};var z=B;export{z as default,P as info};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CodeBuilder as
|
|
2
|
-
${
|
|
3
|
-
`).forEach(e=>{const
|
|
1
|
+
import{CodeBuilder as C}from"../../helpers/code-builder.js";import{HTTPSnippet as j}from"../../index.js";import{normalizeMimeType as l}from"../../../../utils.js";import{addIndentation as O,buildUrlExpression as S,printUrlVariablesDeclarations as T}from"../../helpers/code-helpers.js";import{Lang as x}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{buildJavaDeviceAuthorizationCodeSnippet as E}from"../../helpers/device-auth-snippets.js";const h=a=>!!(a.uriObj.query&&Object.keys(a.uriObj.query).length),b=a=>a.postData&&a.postData.mimeType===i.URL_ENCODED?"HttpRequest.BodyPublishers.ofString(form)":!a.postData?.params?.length&&a.postData?.text&&l(a.postData.mimeType)===i.MULTIPART?"body":a.postData?"HttpRequest.BodyPublishers.ofString(payload)":["POST","PUT","PATCH"].includes(a.method.toUpperCase())?'HttpRequest.BodyPublishers.ofString("some body text")':"",A=function(a,s,{target:y,client:g}){const n=Object.assign({indent:" ",withWrapper:!0},s),t=new C({indentation:n.indent,variablesPrefix:n.variablesPrefix,capitalize:!0,lang:x.JAVA});if(n.withComments&&R(t,a),n.withImports&&B(t,a),n.withWrapper&&(t.push("public class App {"),t.push(1,"public static void main(String[] args) throws Exception {"),t.push(2,"var httpClient = HttpClient.newBuilder().build();"),t.blank()),a.securityOAuth2ExtraCalls?.length){const e=a.securityOAuth2ExtraCalls?.[0],p=new j(e).convert(y,g,{...n,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(p),t.blank(),t.push(2,"var oauth2Response = httpClient.send(oauth2Request, HttpResponse.BodyHandlers.ofString());"),e.flowType==="deviceAuthorization"?E(t,{tokenUrl:e.tokenUrl??"YOUR_TOKEN_URL",clientId:e.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,'var accessToken = new JSONObject(oauth2Response.body()).getString("access_token");'),t.blank())}if(a.postData)switch(l(a.postData.mimeType)){case i.URL_ENCODED:a.postData.params.length?(t.push(2,"HashMap<String, String> params = new HashMap<>();"),a.postData.params.forEach(e=>{t.push(2,'params.put("%s", "%s");',e.name,e.value)}),t.blank(),t.push(2,"var form = params.keySet().stream()"),t.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),t.push(3,'.collect(Collectors.joining("&"));'),t.blank()):a.postData.text&&(t.push(2,'var form = "%s";',a.postData.text),t.blank());break;case i.JSON:a.postData.jsonObj&&(t.push(2,`var payload = String.join("\\n"
|
|
2
|
+
${O(JSON.stringify(a.postData.jsonObj,null,1).replace(/"/g,'\\"').replace(/^/gm,', "').replace(/$/gm,'"'),{level:3,indent:n.indent,firstLine:!1})}`),t.push(2,");"),t.blank());break;case i.XML:a.postData.text&&(t.push(2,'var payload = String.join("\\n"'),a.postData.text.trim().split(`
|
|
3
|
+
`).forEach(e=>{const p=e.replace(/"/g,'\\"');t.push(3,`"${p}", `)}),t.push(2,");"),t.blank());break;case i.OCTET_STREAM:a.postData.text&&(t.push(2,'var payload = "%s";',a.postData.text),t.blank());break;case i.MULTIPART:if(a.postData.params&&a.postData.params.length>0)t.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),a.postData.params.forEach(e=>{e.fileName?t.push(2,'multipartBody.append("%s", Path.of("%s"));',e.name,e.fileName):t.push(2,'multipartBody.append("%s", "%s");',e.name,e.value)}),t.push(2,"var body = multipartBody.build();"),t.blank();else if(a.postData.text){const e=a.postData.text,p=e.match(/^--([^\r\n]+)/);if(p){const c=p[1],D=e.split(new RegExp(`--${c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(r=>r.trim().length>0);t.push(2,"var multipartBody = MultipartBodyPublisher.newBuilder();"),D.forEach(r=>{const o=r.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(o){const m=o[1],d=o[2],f=r.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),k=(f?f[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');d?t.push(2,'multipartBody.append("%s", Path.of("%s"));',m,d):t.push(2,'multipartBody.append("%s", "%s");',m,k)}}),t.push(2,"var body = multipartBody.build();"),t.blank()}else t.push(2,'var payload = "%s";',a.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')),t.blank()}break}if(h(a)){t.push(2,"HashMap<String, String> params = new HashMap<>();");for(const[e,p]of Object.entries(a.uriObj.query))t.push(2,'params.put("%s", "%s");',e,p);t.blank(),t.push(2,"var query = params.keySet().stream()"),t.push(3,'.map(key -> key + "=" + URLEncoder.encode(params.get(key), StandardCharsets.UTF_8))'),t.push(3,'.collect(Collectors.joining("&"));'),t.blank()}t.push(2,`var ${t.var("host")} = "%s";`,a.uriObj.protocol+"//"+a.uriObj.host),T(a,t,2);const v={...a,pathname:a.uriObj.pathname};t.push(2,`var ${t.var("pathname")} = %s;`,S(v,t)),t.push(2,`var ${t.var("request")} = HttpRequest.newBuilder()`),a.method.toUpperCase()==="PATCH"?t.push(3,'.method("PATCH", %s)',b(a)):t.push(3,".%s(%s)",a.method.toUpperCase(),b(a)),t.push(3,`.uri(URI.create(${t.var("host")} + ${t.var("pathname")} %s))`,h(a)?"+ '?' + query":""),a.securityOAuth2ExtraCalls?.length&&(a.allHeaders.Authorization='"Bearer " + accessToken');const u=Object.keys(a.allHeaders);if(u.length&&u.forEach(e=>{t.push(3,'.header("%s", %s)',e,e==="Authorization"&&a.securityOAuth2ExtraCalls?.length?a.allHeaders[e]:`"${a.allHeaders[e]}"`)}),a.basicAuth){const{username:e,password:p}=a.basicAuth;t.push(3,`.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("${e}:${p}").getBytes()))`)}return t.push(3,".build();"),n.withWrapper&&(t.blank(),t.push(2,"var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());"),t.blank(),t.push(2,"System.out.println(response.body());"),t.push(1,"}"),t.push("}")),t.join()},I={key:"httpclient",title:"HttpClient",link:"https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html",description:"HttpClient (Java SE 11 & JDK 11 )"};var N=A;function R(a,s){a.push("/**"),a.push(" * Requires JDK >= 11"),s.securityOAuth2ExtraCalls?.length&&(a.push(" *"),a.push(' * Requires package "org.json" >= 20201115'),a.push(" * See here for installation details:"),a.push(" * https://search.maven.org/artifact/org.json/json")),a.push(" */"),a.blank()}function B(a,s){a.push("import java.net.*;"),a.push("import java.net.http.*;"),a.push("import java.util.*;"),(l(s.postData?.mimeType)===i.URL_ENCODED&&s.postData?.params||s.securityOAuth2ExtraCalls?.length||h(s))&&(a.push("import java.nio.charset.StandardCharsets;"),a.push("import java.util.stream.Collectors;")),s.securityOAuth2ExtraCalls?.length&&a.push("import org.json.JSONObject;"),!s.postData?.params?.length&&s.postData?.text&&l(s.postData.mimeType)===i.MULTIPART&&a.push("import java.nio.file.Path;"),a.blank()}export{N as default,I as info};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CodeBuilder as
|
|
2
|
-
`).forEach(a=>{const s=a.replace(/"/g,'\\"');e.push(3,`"${s}", `)}),e.push(2,");"),e.push(2,"%s.setEntity(new StringEntity(payload));",e.var("request")));break}return p.withWrapper&&(e.push(2,`String ${e.var("response")} = EntityUtils.toString(httpClient.execute(request).getEntity());`),e.blank(),e.push(2,"System.out.println(response);"),e.push(1,"}"),e.push("}")),e.join();function
|
|
1
|
+
import{CodeBuilder as D}from"../../helpers/code-builder.js";import{HTTPSnippet as q}from"../../index.js";import{isEmptyObject as S,normalizeMimeType as O}from"../../../../utils.js";import{capitalizeFirst as N}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{buildUrlExpression as T,printUrlVariablesDeclarations as L}from"../../helpers/code-helpers.js";import{MediaTypes as r}from"../../../../../constants.js";import{buildJava8DeviceAuthorizationCodeSnippet as U}from"../../helpers/device-auth-snippets.js";const M=function(t,i,{target:l,client:A}){const p=Object.assign({indent:" ",withWrapper:!0},i),e=new D({indentation:p.indent,variablesPrefix:p.variablesPrefix,capitalize:!0,lang:k.JAVA8}),y=j(t.method);if(p.withComments&&P(e),p.withImports&&R(e,t),p.withWrapper&&(e.push("public class App {"),e.push(1,"public static void main(String[] args ) throws java.io.IOException {"),e.push(2,"HttpClient httpClient = HttpClientBuilder.create().build();"),e.blank()),t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],s=new q(a).convert(l,A,{...p,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});e.push(s),e.push(2,"JSONObject %s = new JSONObject(EntityUtils.toString(httpClient.execute(%s).getEntity()));","oauth2Response","oauth2Request"),a.flowType==="deviceAuthorization"?U(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(e.push(2,'String accessToken = %s.getString("access_token");',"oauth2Response"),e.blank())}L(t,e,2);const C=T(t,e);e.push(2,`%s ${e.var("request")} = new %s(%s);`,y,y,C);const g=Object.keys(t.allHeaders);if(g.length&&!(t.postData&&t.postData.mimeType==r.MULTIPART)&&g.forEach(a=>{const s=a.toLowerCase()==="authorization";e.push(2,'%s.setHeader("%s", %s);',e.var("request"),a,t.securityOAuth2ExtraCalls?.length&&s?'"Bearer " + accessToken':`"${t.allHeaders[a]}"`)}),t.basicAuth){const{username:a,password:s}=t.basicAuth;e.push(2,`String encodedString = Base64.getEncoder().encodeToString("${a}:${s}".getBytes());`),e.push(2,'%s.setHeader("%s", "%s"+encodedString);',e.var("request"),"Authorization","Basic ")}if(t.postData)switch(O(t.postData.mimeType)){case r.URL_ENCODED:t.postData.params.length?(e.blank(),e.push(2,"List<NameValuePair> params = new ArrayList<NameValuePair>();"),t.postData.params.forEach(a=>{e.push(2,'params.add(new BasicNameValuePair("%s", "%s"));',a.name,a.value)}),e.push(2,"%s.setEntity(new UrlEncodedFormEntity(params));",e.var("request")),e.blank()):t.postData.text&&(e.blank(),e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text),e.blank());break;case r.MULTIPART:if(t.postData.params&&t.postData.params.length>0)e.push(2,"MultipartEntity reqEntity = new MultipartEntity();"),t.postData.params.forEach(a=>{a.fileName?e.push(2,'reqEntity.addPart("%s", new FileBody(new File("%s")));',a.name,a.fileName):e.push(2,'reqEntity.addPart("%s", %s);',a.name,v(a.value)?`new StringBody("${a.value}")`:a.value)}),e.push(2,"%s.setEntity(reqEntity);",e.var("request"));else if(t.postData.text){const a=t.postData.text,s=a.match(/^--([^\r\n]+)/);if(s){const n=s[1],o=a.split(new RegExp(`--${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(h=>h.trim().length>0);e.push(2,"MultipartEntity reqEntity = new MultipartEntity();"),o.forEach(h=>{const m=h.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(m){const E=m[1],d=m[2],b=h.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),x=(b?b[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');d?e.push(2,'reqEntity.addPart("%s", new FileBody(new File("%s")));',E,d):e.push(2,'reqEntity.addPart("%s", new StringBody("%s"));',E,x)}}),e.push(2,"%s.setEntity(reqEntity);",e.var("request"))}else e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"'))}break;case r.JSON:if(t.postData.jsonObj){e.push(2,"JSONObject payload = new JSONObject();");for(const[a,s]of Object.entries(t.postData.jsonObj))Array.isArray(s)?(e.push(2,'payload.put("%s", new JSONArray()',a),s.forEach(n=>{c(n)?(e.push(3,".put(new JSONObject()"),u(n,4),e.push(3,")")):e.push(3,".put(%s)",f(n))}),e.push(2,");")):c(s)?(e.push(2,'payload.put("%s", new JSONObject()%s',a,S(s)?");":""),u(s,3),S(s)||e.push(2,");")):e.push(2,'payload.put("%s", %s);',a,f(s));e.push(2,"%s.setEntity(new StringEntity(payload.toString()));",e.var("request"))}break;case r.XML:t.postData.text&&(e.push(2,'String payload = String.join("\\n"'),t.postData.text.trim().split(`
|
|
2
|
+
`).forEach(a=>{const s=a.replace(/"/g,'\\"');e.push(3,`"${s}", `)}),e.push(2,");"),e.push(2,"%s.setEntity(new StringEntity(payload));",e.var("request")));break;case r.OCTET_STREAM:t.postData.text&&e.push(2,'%s.setEntity(new StringEntity("%s"));',e.var("request"),t.postData.text);break}return p.withWrapper&&(e.push(2,`String ${e.var("response")} = EntityUtils.toString(httpClient.execute(request).getEntity());`),e.blank(),e.push(2,"System.out.println(response);"),e.push(1,"}"),e.push("}")),e.join();function u(a,s){for(const[n,o]of Object.entries(a))c(o)?(e.push(s,'.put("%s", new JSONObject()',n),u(o,s+1),e.push(s,")")):e.push(s,'.put("%s", %s)',n,f(o))}},W={key:"apachehttp",title:"Apache http",link:"https://hc.apache.org/httpcomponents-client-4.5.x/",description:"Apache HttpClient"};var K=M;function P(t){t.push("/**"),t.push(" * Requires JDK >= 8"),t.push(" *"),t.push(" * Requires Apache HttpComponents Client >= 4.3.5"),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.apache.httpcomponents/httpcomponents-client"),t.push(" *"),t.push(' * Requires package "junit4"'),t.push(" * See here for installation details:"),t.push(" * https://junit.org/junit4"),t.push(" *"),t.push(' * Requires package "org.json" >= 20180130'),t.push(" * See here for installation details:"),t.push(" * https://search.maven.org/artifact/org.json/json"),t.push(" */"),t.blank()}function R(t,i){t.push("import org.apache.http.util.EntityUtils;"),t.push("import org.apache.http.NameValuePair;"),t.push("import org.apache.http.client.HttpClient;"),t.push("import org.apache.http.client.entity.UrlEncodedFormEntity;"),i.method&&w(t,i.method),i.securityOAuth2ExtraCalls?.length&&i.securityOAuth2ExtraCalls?.[0].method.toLowerCase()!==i.method.toLowerCase()&&w(t,i.securityOAuth2ExtraCalls?.[0].method),t.push("import org.apache.http.impl.client.HttpClientBuilder;"),t.push("import org.apache.http.message.BasicNameValuePair;"),t.push("import org.apache.http.entity.StringEntity;"),t.push("import org.json.JSONObject;"),t.push("import org.json.JSONArray;"),t.push("import java.util.ArrayList;"),t.push("import java.util.List;"),t.push("import org.apache.http.entity.mime.MultipartEntity;"),t.push("import org.apache.http.entity.mime.content.StringBody;"),!i.postData?.params?.length&&i.postData?.text&&O(i.postData.mimeType)===r.MULTIPART&&(t.push("import org.apache.http.entity.mime.content.FileBody;"),t.push("import java.io.File;")),i.basicAuth&&t.push("import java.util.Base64;"),t.blank()}function w(t,i){const l=j(i);t.push(`import org.apache.http.client.methods.${l};`)}function j(t){return"Http"+N(t.toLowerCase())}function v(t){return Object.prototype.toString.call(t)==="[object String]"}function c(t){const i=typeof t;return i==="function"||i==="object"&&!!t}function f(t){return v(t)?JSON.stringify(t):t??"JSONObject.NULL"}export{K as default,W as info};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import l from"stringify-object";import{CodeBuilder as A}from"../../helpers/code-builder.js";import{addIndentation as p,getPreserveTransformer as C,buildUrlExpression as w,printUrlVariablesDeclarations as T}from"../../helpers/code-helpers.js";import{normalizeMimeType as f}from"../../../../utils.js";import{HTTPSnippet as j}from"../../index.js";import{Lang as N}from"../../helpers/constants.js";import{MediaTypes as r}from"../../../../../constants.js";import{buildJSDeviceAuthorizationCodeSnippet as P}from"../../helpers/device-auth-snippets.js";const k=function(e,b,{target:v,client:y}){const i={indent:" ",credentials:null,...b},t=new A({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:!0,lang:N.JAVASCRIPT}),a={method:e.method.toUpperCase()};Object.keys(e.headersObj).length&&(a.headers=e.headersObj);let h=!1;if(i.withComments&&L(t),e.securityOAuth2ExtraCalls?.length){const n=e.securityOAuth2ExtraCalls?.[0],s=new j(n).convert(v,y,{...i,withImports:!1,withComments:!1,variablesPrefix:"oAuth2"});t.push(s),t.blank(),n.flowType==="deviceAuthorization"&&P(t,{tokenUrl:n.tokenUrl??"YOUR_TOKEN_URL",clientId:n.clientId??"YOUR_CLIENT_ID",level:0}),a.headers=a.headers||{},a.headers.Authorization="'Bearer ' + accessToken",h=!0}i.credentials!==null&&(a.credentials=i.credentials);const m=Object.getOwnPropertyNames(e.queryObj).length;if(m&&t.push(`const ${t.var("query")} = new URLSearchParams(${l(e.queryObj,{indent:i.indent,inlineCharacterLimit:25})}).toString();`).blank(),e.postData)switch(f(e.postData.mimeType)){case r.URL_ENCODED:a.body=e.postData.paramsObj?`new URLSearchParams(${t.var("formData")}).toString()`:`"${e.postData.text}"`,e.postData.paramsObj&&t.push(`const ${t.var("formData")} = ${p(l(e.postData.paramsObj,{indent:i.indent,inlineCharacterLimit:25}),{level:0,firstLine:!1})};`).blank();break;case r.JSON:e.postData.jsonObj&&(a.body=`JSON.stringify(${p(l(e.postData.jsonObj,{indent:i.indent,inlineCharacterLimit:25}),{level:1,firstLine:!1})})`);break;case r.MULTIPART:if(t.push(`const ${t.var("form")} = new FormData();`),delete a?.headers?.["Content-Type"],e.postData?.params?.length>0)e.postData.params.forEach(function(n){t.push(`${t.var("form")}.append(%s, %s);`,JSON.stringify(n.name),JSON.stringify(n.value||n.fileName||""))});else if(e.postData.text){const n=e.postData.text,s=n.match(/^--([^\r\n]+)/);if(s){const $=s[1];n.split(new RegExp(`--${$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(o=>o.trim().length>0).forEach(o=>{const d=o.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(d){const g=d[1],D=d[2],u=o.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),S=u?u[1].trim():"",x=D||S;t.push(`${t.var("form")}.append(%s, %s);`,JSON.stringify(g),JSON.stringify(x))}})}else t.push(`${t.var("form")}.append('data', %s);`,JSON.stringify(e.postData.text))}a.body=t.var("form"),t.blank();break;default:e.postData.text&&(a.body=`\`${p(e.postData.text,{level:2,indent:i.indent,firstLine:!1}).trim()}\``)}const c=a.headers&&a.headers.Accept&&f(a.headers.Accept)===r.JSON||f(e.postData?.mimeType)===r.JSON;if(e.basicAuth){const{username:n,password:s}=e.basicAuth;a.headers=a.headers||{},a.headers.Authorization=`'Basic ' + btoa('${n}:${s}')`,h=!0}T(e,t);const O=w(e,t);return t.push(`const ${t.var("resp")} = await fetch(`).push(1,"`"+O+(m?"?${"+t.var("query")+"}":"")+"`,").push(p(l(a,{indent:i.indent,inlineCharacterLimit:25,transform:C({body:!0,authorizationHeader:h})}),{level:1,indent:i.indent})).push(");").blank(),e.allResponseCodes?.includes("204")?(t.push("if (resp.status === 204) {").push(1,"console.log('success');").push("} else {"),t.push(1,`const ${t.var("data")} = await ${t.var("resp")}.${c?"json()":"text()"};`).push(1,`console.log(${t.var("data")});`).push("}")):t.push(`const ${t.var("data")} = await ${t.var("resp")}.${c?"json()":"text()"};`).push(`console.log(${t.var("data")});`),t.join()};function L(e){e.push("/**"),e.push(" * Requires ES8-compatible browser: https://caniuse.com/async-functions"),e.push(" */"),e.blank()}const F={key:"fetch",title:"fetch",link:"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",description:"Perform asynchronous HTTP requests with the Fetch API"};var H=k;export{H as default,F as info};
|