@redocly/openapi-docs 3.12.0 → 3.12.1

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.
Files changed (384) hide show
  1. package/dist/redocly-openapi-docs.min.js +753 -750
  2. package/lib/components/ApiInfo/ApiInfo.js +29 -1
  3. package/lib/components/ApiInfo/Metadata.js +29 -1
  4. package/lib/components/ApiInfo/index.js +2 -1
  5. package/lib/components/ApiInfo/styled.js +16 -8
  6. package/lib/components/CallbackSamples/CallbackSamples.js +25 -4
  7. package/lib/components/CallbackSamples/index.js +2 -1
  8. package/lib/components/Callbacks/CallbackDetails.js +17 -3
  9. package/lib/components/Callbacks/CallbackOperation.js +24 -3
  10. package/lib/components/Callbacks/CallbackSummary.js +19 -3
  11. package/lib/components/Callbacks/CallbacksList.js +16 -1
  12. package/lib/components/Callbacks/index.js +4 -1
  13. package/lib/components/Callbacks/styled.js +6 -3
  14. package/lib/components/Content/Content.js +10 -1
  15. package/lib/components/Content/index.js +2 -1
  16. package/lib/components/Content/useAutoScroll.js +50 -1
  17. package/lib/components/ContentItem/ContentItem.js +31 -1
  18. package/lib/components/ContentItem/index.js +2 -1
  19. package/lib/components/ContentItem/useIsExpanded.js +33 -1
  20. package/lib/components/ContentItems/ContentItems.js +19 -1
  21. package/lib/components/ContentItems/Items.js +13 -1
  22. package/lib/components/ContentItems/VirtualList.js +35 -1
  23. package/lib/components/ContentItems/helpers.js +49 -1
  24. package/lib/components/ContentItems/index.js +2 -1
  25. package/lib/components/ContentItems/useScrollOnRender.js +26 -1
  26. package/lib/components/Discriminator/Discriminator.js +27 -2
  27. package/lib/components/Discriminator/index.js +2 -1
  28. package/lib/components/Download/DownloadSpecification.js +46 -4
  29. package/lib/components/Download/index.js +2 -1
  30. package/lib/components/Download/types.js +2 -0
  31. package/lib/components/Download/useDownloadInfo.js +42 -1
  32. package/lib/components/ErrorBoundary/ErrorBoundary.js +22 -2
  33. package/lib/components/ErrorBoundary/index.js +2 -1
  34. package/lib/components/ExpandAllButton/ExpandAllButton.js +31 -2
  35. package/lib/components/ExpandAllButton/index.js +2 -1
  36. package/lib/components/ExternalDocumentation/ExternalDocumentation.js +18 -4
  37. package/lib/components/ExternalDocumentation/index.js +2 -1
  38. package/lib/components/Language/LanguageDropdown.js +21 -1
  39. package/lib/components/Language/LanguageItem.js +33 -1
  40. package/lib/components/Language/LanguageList.js +93 -1
  41. package/lib/components/Language/_tests_/LanguageDropdown.test.js +23 -1
  42. package/lib/components/Language/constants.js +3 -1
  43. package/lib/components/Language/index.js +4 -1
  44. package/lib/components/Language/styled.js +29 -15
  45. package/lib/components/Markdown/Markdown.js +64 -1
  46. package/lib/components/Markdown/index.js +3 -1
  47. package/lib/components/Markdown/types.js +2 -0
  48. package/lib/components/MediaTypeSwitch/MediaTypesSwitch.js +51 -1
  49. package/lib/components/MediaTypeSwitch/index.js +2 -1
  50. package/lib/components/OperationItem/Description.js +9 -1
  51. package/lib/components/OperationItem/OperationItem.js +70 -5
  52. package/lib/components/OperationItem/_tests_/OperationItem.test.js +70 -1
  53. package/lib/components/OperationItem/_tests_/__mocks__/mock-intersection-observer.js +40 -1
  54. package/lib/components/OperationItem/index.js +2 -1
  55. package/lib/components/OperationItem/types.js +2 -0
  56. package/lib/components/Overlay.js +48 -3
  57. package/lib/components/Overview/Overview.js +20 -1
  58. package/lib/components/Overview/index.js +2 -1
  59. package/lib/components/PageFooter/PageFooter.js +19 -1
  60. package/lib/components/PageFooter/index.js +2 -1
  61. package/lib/components/Panel/ResponsePanel.js +12 -6
  62. package/lib/components/Panel/Trigger.js +4 -2
  63. package/lib/components/Panel/index.js +3 -1
  64. package/lib/components/PanelItem/PanelItem.js +6 -1
  65. package/lib/components/PanelItem/index.js +3 -1
  66. package/lib/components/PanelItem/styled.js +20 -10
  67. package/lib/components/PayloadSamples/Example.js +6 -1
  68. package/lib/components/PayloadSamples/ExampleValue.js +30 -1
  69. package/lib/components/PayloadSamples/MediaTypeSamples.js +36 -2
  70. package/lib/components/PayloadSamples/PayloadSamples.js +26 -1
  71. package/lib/components/PayloadSamples/index.js +7 -1
  72. package/lib/components/PayloadSamples/styled.js +9 -4
  73. package/lib/components/PayloadSamples/types.js +2 -0
  74. package/lib/components/PropertyDetails/DescriptionEnums.js +19 -3
  75. package/lib/components/PropertyDetails/EnumValues.js +37 -1
  76. package/lib/components/PropertyDetails/Examples.js +26 -1
  77. package/lib/components/PropertyDetails/Extensions.js +17 -2
  78. package/lib/components/PropertyDetails/FieldDetail.js +15 -2
  79. package/lib/components/PropertyDetails/FieldDetails.js +51 -6
  80. package/lib/components/PropertyDetails/Pattern.js +21 -1
  81. package/lib/components/PropertyDetails/PlusCircleIcon.js +10 -4
  82. package/lib/components/PropertyDetails/PropertyDetails.js +22 -5
  83. package/lib/components/PropertyDetails/SchemaTypeInfo.js +10 -2
  84. package/lib/components/PropertyDetails/SimpleEnums.js +13 -2
  85. package/lib/components/PropertyDetails/cycleColorsByLevel.js +18 -1
  86. package/lib/components/PropertyDetails/index.js +4 -1
  87. package/lib/components/PropertyDetails/styled.js +15 -7
  88. package/lib/components/PropertyDetails/types.js +2 -0
  89. package/lib/components/RedoclyOpenAPIDocs/Providers.js +114 -1
  90. package/lib/components/RedoclyOpenAPIDocs/RedoclyOpenAPIDocs.js +57 -1
  91. package/lib/components/RedoclyOpenAPIDocs/RedoclyOpenAPIDocsStandalone.js +86 -1
  92. package/lib/components/RedoclyOpenAPIDocs/index.js +5 -1
  93. package/lib/components/RedoclyOpenAPIDocs/styled.js +4 -2
  94. package/lib/components/RedoclyOpenAPIDocs/types.js +2 -0
  95. package/lib/components/RedoclyOpenAPIDocs/utils.js +33 -1
  96. package/lib/components/RenderHook/RenderHook.js +17 -1
  97. package/lib/components/RenderHook/index.js +2 -1
  98. package/lib/components/Replay/EmbeddedReplay.js +41 -3
  99. package/lib/components/Replay/Replay.js +99 -1
  100. package/lib/components/Replay/index.js +3 -1
  101. package/lib/components/Replay/utils.js +208 -1
  102. package/lib/components/Request/RequestDetails.js +33 -2
  103. package/lib/components/Request/types.js +2 -0
  104. package/lib/components/RequestParameters/Body.js +8 -1
  105. package/lib/components/RequestParameters/ParametersGroup.js +19 -4
  106. package/lib/components/RequestParameters/RequestParameters.js +40 -1
  107. package/lib/components/RequestParameters/index.js +4 -1
  108. package/lib/components/RequestSamples/CodeSample.js +55 -2
  109. package/lib/components/RequestSamples/Example.js +37 -1
  110. package/lib/components/RequestSamples/RequestSamples.js +89 -5
  111. package/lib/components/RequestSamples/index.js +3 -1
  112. package/lib/components/RequestSamples/useCodeSamples.js +92 -1
  113. package/lib/components/ResponseSamples/ResponseSamples.js +47 -1
  114. package/lib/components/ResponseSamples/Summary.js +9 -1
  115. package/lib/components/ResponseSamples/index.js +2 -1
  116. package/lib/components/Responses/OperationResponseList.js +42 -2
  117. package/lib/components/Responses/ResponseDetails.js +18 -1
  118. package/lib/components/Responses/ResponseHeaders.js +15 -1
  119. package/lib/components/Responses/index.js +6 -1
  120. package/lib/components/Responses/styled.js +14 -6
  121. package/lib/components/Responses/types.js +2 -0
  122. package/lib/components/RightPanel/RightPanel.js +21 -1
  123. package/lib/components/RightPanel/index.js +2 -1
  124. package/lib/components/Samples/ExampleSwitch.js +33 -1
  125. package/lib/components/Samples/index.js +3 -1
  126. package/lib/components/Samples/use-example-key.js +12 -1
  127. package/lib/components/Schema/ArraySchema.js +45 -1
  128. package/lib/components/Schema/ObjectSchema.js +29 -1
  129. package/lib/components/Schema/OneOfSchema.js +47 -3
  130. package/lib/components/Schema/RecursiveSchema.js +10 -1
  131. package/lib/components/Schema/Schema.js +63 -2
  132. package/lib/components/Schema/SubSchema.js +20 -1
  133. package/lib/components/Schema/helpers.js +16 -1
  134. package/lib/components/Schema/index.js +5 -1
  135. package/lib/components/Schema/types.js +2 -0
  136. package/lib/components/Schema/useOneOfLocationIdx.js +11 -1
  137. package/lib/components/SchemaDefinition/SchemaDefinition.js +65 -2
  138. package/lib/components/SchemaDefinition/index.js +2 -1
  139. package/lib/components/SectionContent/SectionContent.js +49 -6
  140. package/lib/components/SectionContent/index.js +2 -1
  141. package/lib/components/SectionItem/SectionItem.js +14 -1
  142. package/lib/components/SectionItem/index.js +2 -1
  143. package/lib/components/Security/Divider.js +9 -2
  144. package/lib/components/Security/OAuthFlow.js +11 -1
  145. package/lib/components/Security/OAuthScopes.js +59 -9
  146. package/lib/components/Security/Security.js +15 -1
  147. package/lib/components/Security/SecurityButton.js +31 -7
  148. package/lib/components/Security/SecurityFlow.js +28 -4
  149. package/lib/components/Security/SecurityModal.js +34 -5
  150. package/lib/components/Security/SecuritySchemeItem.js +15 -4
  151. package/lib/components/Security/helper.js +16 -1
  152. package/lib/components/Security/index.js +11 -1
  153. package/lib/components/Security/styled.js +6 -3
  154. package/lib/components/SelectOrLabel/SelectOrLabel.js +12 -2
  155. package/lib/components/SelectOrLabel/index.js +2 -1
  156. package/lib/components/ServerList/ServerList.js +36 -10
  157. package/lib/components/ServerList/index.js +2 -1
  158. package/lib/components/ServerList/types.js +2 -0
  159. package/lib/components/ServerListDropdown/ServerListDropdown.js +54 -1
  160. package/lib/components/ServerListDropdown/index.js +2 -1
  161. package/lib/components/ServerListDropdown/styled.js +15 -6
  162. package/lib/components/SideMenu/SideMenu.js +13 -2
  163. package/lib/components/SideMenu/hooks/useMenuItems.js +110 -1
  164. package/lib/components/SideMenu/index.js +2 -1
  165. package/lib/components/SideMenu/types.js +2 -0
  166. package/lib/components/StickySidebar/SidebarActions.js +14 -2
  167. package/lib/components/StickySidebar/StickyResponsiveSidebar.js +37 -7
  168. package/lib/components/StickySidebar/index.js +2 -1
  169. package/lib/components/Tabs/Tabs.js +16 -5
  170. package/lib/components/Tabs/index.js +3 -1
  171. package/lib/components/Tabs/useTabsState.js +22 -1
  172. package/lib/components/TagItem/OperationNavigationItems.js +18 -4
  173. package/lib/components/TagItem/OperationsNavigation.js +46 -2
  174. package/lib/components/TagItem/TagItem.js +40 -7
  175. package/lib/components/TagItem/index.js +2 -1
  176. package/lib/components/TagItem/styled.js +5 -2
  177. package/lib/components/TagItem/types.js +2 -0
  178. package/lib/components/ViewNested/ViewNested.js +42 -9
  179. package/lib/components/ViewNested/index.js +2 -1
  180. package/lib/components/common/Badges.js +21 -5
  181. package/lib/components/common/BodyContent/BodyContent.js +31 -4
  182. package/lib/components/common/BodyContent/index.js +2 -1
  183. package/lib/components/common/ClearButton/ClearButton.js +5 -1
  184. package/lib/components/common/ClearButton/index.js +3 -1
  185. package/lib/components/common/ClearButton/styled.js +5 -2
  186. package/lib/components/common/ClearButton/types.js +2 -0
  187. package/lib/components/common/CodeBlockPanel.js +7 -3
  188. package/lib/components/common/ConstraintsView.js +14 -2
  189. package/lib/components/common/Dropdown/Dropdown.js +22 -4
  190. package/lib/components/common/Dropdown/index.js +2 -1
  191. package/lib/components/common/ExpandableExample/ExpandableExample.js +24 -3
  192. package/lib/components/common/ExpandableExample/index.js +2 -1
  193. package/lib/components/common/Extensions.js +17 -2
  194. package/lib/components/common/Fields/fields-layout.js +76 -51
  195. package/lib/components/common/Fields/fields.js +39 -17
  196. package/lib/components/common/Fields/index.js +3 -1
  197. package/lib/components/common/LinkToField.js +33 -6
  198. package/lib/components/common/OperationItemTitle.js +12 -6
  199. package/lib/components/common/SchemaSelection/SchemaSelection.js +51 -1
  200. package/lib/components/common/SchemaSelection/index.js +2 -1
  201. package/lib/components/common/Select/Select.js +21 -1
  202. package/lib/components/common/Select/index.js +3 -1
  203. package/lib/components/common/Select/styled.js +17 -9
  204. package/lib/components/common/Select/types.js +2 -0
  205. package/lib/components/common/Skeleton/LanguageListSkeleton.js +16 -6
  206. package/lib/components/common/Skeleton/Skeleton.js +15 -5
  207. package/lib/components/common/Skeleton/index.js +3 -1
  208. package/lib/components/common/headers.js +4 -2
  209. package/lib/components/common/index.js +14 -1
  210. package/lib/components/common/linkify.js +28 -4
  211. package/lib/components/common/mixins.js +4 -2
  212. package/lib/components/common/panels.js +52 -29
  213. package/lib/components/common/schema.js +16 -8
  214. package/lib/components/common/styled.js +15 -7
  215. package/lib/components/index.js +25 -1
  216. package/lib/components/pluggable/RedocExample.js +20 -1
  217. package/lib/components/pluggable/RedocSchema.js +22 -1
  218. package/lib/components/pluggable/index.js +3 -1
  219. package/lib/components/pluggable/styled.components.js +9 -4
  220. package/lib/constants.js +30 -1
  221. package/lib/empty.js +7 -1
  222. package/lib/events/codeSampleCopy.js +19 -1
  223. package/lib/events/creator.js +5 -1
  224. package/lib/events/index.js +8 -1
  225. package/lib/events/languageSwitch.js +18 -1
  226. package/lib/events/panelToggle.js +16 -1
  227. package/lib/events/serverSwitch.js +13 -1
  228. package/lib/events/tryItOpen.js +12 -1
  229. package/lib/events/tryItSent.js +12 -1
  230. package/lib/events/types.js +11 -1
  231. package/lib/hoc/types.js +2 -0
  232. package/lib/hoc/utils.js +4 -1
  233. package/lib/hoc/withRouter.js +17 -1
  234. package/lib/hoc/withStore.js +28 -1
  235. package/lib/hooks/index.js +9 -1
  236. package/lib/hooks/useActivateExample.js +35 -1
  237. package/lib/hooks/useActiveWithFallback.js +12 -1
  238. package/lib/hooks/useContentItems.js +10 -1
  239. package/lib/hooks/useLicense.js +17 -1
  240. package/lib/hooks/usePerformanceMetrics.js +26 -1
  241. package/lib/hooks/useRouter.js +17 -1
  242. package/lib/hooks/useTelemetry.js +5 -1
  243. package/lib/hooks/useTranslate.js +6 -1
  244. package/lib/hooks/useUppercase2LowercaseRedirect.js +12 -1
  245. package/lib/icons/CSharpIcon/CSharpIcon.js +7 -1
  246. package/lib/icons/CSharpIcon/index.js +2 -1
  247. package/lib/icons/CurlIcon/CurlIcon.js +8 -2
  248. package/lib/icons/CurlIcon/index.js +2 -1
  249. package/lib/icons/GOIcon/GOIcon.js +7 -1
  250. package/lib/icons/GOIcon/index.js +2 -1
  251. package/lib/icons/JavaIcon/JavaIcon.js +7 -1
  252. package/lib/icons/JavaIcon/index.js +2 -1
  253. package/lib/icons/JavaScriptIcon/JavaScriptIcon.js +7 -1
  254. package/lib/icons/JavaScriptIcon/index.js +2 -1
  255. package/lib/icons/NodeJSIcon/NodeJSIcon.js +7 -1
  256. package/lib/icons/NodeJSIcon/index.js +2 -1
  257. package/lib/icons/PHPIcon/PHPIcon.js +7 -1
  258. package/lib/icons/PHPIcon/index.js +2 -1
  259. package/lib/icons/PayloadIcon/PayloadIcon.js +7 -1
  260. package/lib/icons/PayloadIcon/index.js +2 -1
  261. package/lib/icons/PythonIcon/PythonIcon.js +7 -1
  262. package/lib/icons/PythonIcon/index.js +2 -1
  263. package/lib/icons/RIcon/RIcon.js +7 -1
  264. package/lib/icons/RIcon/index.js +2 -1
  265. package/lib/icons/RubyIcon/RubyIcon.js +7 -1
  266. package/lib/icons/RubyIcon/index.js +2 -1
  267. package/lib/index.js +49 -1
  268. package/lib/jotai/app.js +113 -1
  269. package/lib/jotai/operation.js +28 -1
  270. package/lib/jotai/replay.js +5 -1
  271. package/lib/jotai/store.js +8 -1
  272. package/lib/jotai/use-write-atom.js +9 -1
  273. package/lib/models/callback.js +28 -1
  274. package/lib/models/code-sample-options.js +2 -0
  275. package/lib/models/example.js +17 -1
  276. package/lib/models/field.js +109 -1
  277. package/lib/models/group.js +38 -1
  278. package/lib/models/index.js +14 -1
  279. package/lib/models/mediaContent.js +26 -1
  280. package/lib/models/mediaType.js +153 -1
  281. package/lib/models/operation.js +166 -1
  282. package/lib/models/request.js +25 -1
  283. package/lib/models/response.js +46 -1
  284. package/lib/models/schema.js +474 -2
  285. package/lib/models/security.js +84 -1
  286. package/lib/models/tab.js +2 -0
  287. package/lib/models/types.js +2 -0
  288. package/lib/services/OpenAPIParser.js +321 -1
  289. package/lib/services/check.js +104 -1
  290. package/lib/services/code-samples/constants.js +16 -1
  291. package/lib/services/code-samples/generator.js +540 -1
  292. package/lib/services/code-samples/httpsnippet/helpers/code-builder.js +252 -3
  293. package/lib/services/code-samples/httpsnippet/helpers/code-helpers.js +90 -2
  294. package/lib/services/code-samples/httpsnippet/helpers/constants.js +28 -1
  295. package/lib/services/code-samples/httpsnippet/helpers/lodash-int.js +173 -1
  296. package/lib/services/code-samples/httpsnippet/helpers/mocks/code-helpers-mock.js +76 -37
  297. package/lib/services/code-samples/httpsnippet/helpers/reducer.js +16 -1
  298. package/lib/services/code-samples/httpsnippet/helpers/shell.js +20 -1
  299. package/lib/services/code-samples/httpsnippet/helpers/string-utility.js +19 -1
  300. package/lib/services/code-samples/httpsnippet/index.js +166 -1
  301. package/lib/services/code-samples/httpsnippet/targets/__mocks__/mock.js +2340 -146
  302. package/lib/services/code-samples/httpsnippet/targets/csharp/httpclient.js +227 -2
  303. package/lib/services/code-samples/httpsnippet/targets/csharp/index.js +11 -1
  304. package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/httpclient.js +185 -2
  305. package/lib/services/code-samples/httpsnippet/targets/csharpNewtonsoft/index.js +11 -1
  306. package/lib/services/code-samples/httpsnippet/targets/go/index.js +11 -1
  307. package/lib/services/code-samples/httpsnippet/targets/go/native.js +222 -3
  308. package/lib/services/code-samples/httpsnippet/targets/index.js +28 -1
  309. package/lib/services/code-samples/httpsnippet/targets/java/httpclient.js +184 -3
  310. package/lib/services/code-samples/httpsnippet/targets/java/index.js +11 -1
  311. package/lib/services/code-samples/httpsnippet/targets/java8/apachehttp.js +223 -2
  312. package/lib/services/code-samples/httpsnippet/targets/java8/index.js +11 -1
  313. package/lib/services/code-samples/httpsnippet/targets/javascript/fetch.js +147 -1
  314. package/lib/services/code-samples/httpsnippet/targets/javascript/index.js +11 -1
  315. package/lib/services/code-samples/httpsnippet/targets/node/fetch.js +199 -1
  316. package/lib/services/code-samples/httpsnippet/targets/node/index.js +11 -1
  317. package/lib/services/code-samples/httpsnippet/targets/php/curl.js +203 -5
  318. package/lib/services/code-samples/httpsnippet/targets/php/index.js +11 -1
  319. package/lib/services/code-samples/httpsnippet/targets/php/types.js +2 -0
  320. package/lib/services/code-samples/httpsnippet/targets/php/utils.js +106 -5
  321. package/lib/services/code-samples/httpsnippet/targets/python/index.js +11 -1
  322. package/lib/services/code-samples/httpsnippet/targets/python/requests.js +185 -6
  323. package/lib/services/code-samples/httpsnippet/targets/r/httr.js +111 -1
  324. package/lib/services/code-samples/httpsnippet/targets/r/index.js +11 -1
  325. package/lib/services/code-samples/httpsnippet/targets/r/utils.js +18 -6
  326. package/lib/services/code-samples/httpsnippet/targets/ruby/index.js +11 -1
  327. package/lib/services/code-samples/httpsnippet/targets/ruby/native.js +169 -1
  328. package/lib/services/code-samples/httpsnippet/targets/shell/curl.js +94 -6
  329. package/lib/services/code-samples/httpsnippet/targets/shell/index.js +11 -1
  330. package/lib/services/code-samples/index.js +3 -1
  331. package/lib/services/code-samples/types.js +2 -0
  332. package/lib/services/config-options/helpers.js +49 -1
  333. package/lib/services/config-options/index.js +3 -1
  334. package/lib/services/config-options/normalizeOptions.js +83 -1
  335. package/lib/services/config-options/types.js +2 -0
  336. package/lib/services/history/helpers.js +63 -1
  337. package/lib/services/history/index.js +2 -1
  338. package/lib/services/index.js +9 -1
  339. package/lib/services/menu/builder.js +47 -1
  340. package/lib/services/menu/index.js +2 -1
  341. package/lib/services/menu/markdown.js +93 -1
  342. package/lib/services/menu/operation.js +50 -1
  343. package/lib/services/menu/tags.js +166 -1
  344. package/lib/services/types.js +2 -0
  345. package/lib/services/utils.js +83 -1
  346. package/lib/standalone.js +68 -1
  347. package/lib/styled-components.js +6 -1
  348. package/lib/types/app.js +2 -0
  349. package/lib/types/index.js +4 -1
  350. package/lib/types/open-api.js +2 -0
  351. package/lib/types/security.js +2 -0
  352. package/lib/utils/JsonPointer.js +84 -1
  353. package/lib/utils/areArraysEqual.js +4 -1
  354. package/lib/utils/argValuesHelpers.js +35 -1
  355. package/lib/utils/compose.js +2 -1
  356. package/lib/utils/configure-helpers.js +223 -1
  357. package/lib/utils/convertSwagger2OpenAPI.js +14 -1
  358. package/lib/utils/cookies.js +73 -1
  359. package/lib/utils/debounce.js +22 -1
  360. package/lib/utils/debug.js +11 -1
  361. package/lib/utils/dom.js +65 -1
  362. package/lib/utils/environments.js +13 -1
  363. package/lib/utils/helpers.js +222 -12
  364. package/lib/utils/index.js +25 -1
  365. package/lib/utils/isMobile.js +13 -1
  366. package/lib/utils/loadAndBundleSpec.js +32 -1
  367. package/lib/utils/local-storage.js +12 -1
  368. package/lib/utils/object.js +31 -1
  369. package/lib/utils/openapi.js +592 -1
  370. package/lib/utils/parameters.js +13 -1
  371. package/lib/utils/path.js +22 -1
  372. package/lib/utils/queryString.js +60 -1
  373. package/lib/utils/replaceVariables.js +14 -1
  374. package/lib/utils/saveTextBeforeHeading.js +35 -1
  375. package/lib/utils/security-details.js +49 -1
  376. package/lib/utils/session-storage.js +12 -1
  377. package/lib/utils/simplifyAstStructure.js +22 -1
  378. package/lib/utils/sort.js +21 -1
  379. package/lib/utils/string.js +65 -1
  380. package/lib/utils/telemetry.js +7 -1
  381. package/lib/utils/test-utils.js +26 -1
  382. package/lib/utils/theme-helpers.js +24 -3
  383. package/lib/utils/url.js +38 -1
  384. package/package.json +3 -3
@@ -1 +1,540 @@
1
- import*as oe from"openapi-sampler";import L from"deepmerge";import{isObject as ce}from"@redocly/theme/core/openapi";import{areArraysEqual as ie,serializeParameterValue as P,getSecurityDetails as ue,getParameterValue as M,queryString as j,isArrayOfObjects as le,deleteEmptyArrayItem as pe}from"../../utils/index.js";import{normalizeMimeType as me,arrayMergeStrategy as z}from"../utils.js";import{MediaTypes as m}from"../../constants.js";import{HTTPSnippet as fe}from"./httpsnippet/index.js";import{getActiveMediaType as de}from"../../models/mediaContent.js";import J from"./httpsnippet/helpers/string-utility.js";function v(t,a,s){try{return oe.sample(t,a,s)}catch(c){return console.error(`Error sampling schema: ${c.message}`),null}}function ye(t,a){return t.find(s=>{const c=s.schemes.map(i=>i.id);return ie(c,a||[])})}function he(t,{exampleName:a="",skipOptionalParameters:s=!1,withOAuth2Call:c=!1,spec:i,generatedPayloadSamplesMaxDepth:r=8,pathParams:o={},properties:u={},activeMimeName:n=""},{environment:d,requestValues:k,activeSecuritySchemeIds:T}){const l=d.server,b=t.servers.find(e=>e.url===l)||t.servers[0],w=ye(t.security,T),{securityHeaders:A,securityCookies:F,securityQueries:X,securityOAuth2ExtraCalls:K,basicAuth:Q}=Se(w||t.security?.[0],c,d),p=t?.requestBody?.content&&de(t.requestBody.content,n),O={skipNonRequired:s,skipReadOnly:!0,maxSampleDepth:r,quiet:!0},h=k;let q=!1;const H=t.parameters.filter(e=>e.in==="header").filter(e=>!(s&&!e.required)).map(e=>({name:e.name,value:h.header?.[e.name]||M("header",e.name)||e.serverValues?.[l]?.example||e.example||P(e,v(e.schema.rawSchema,O,i))})).map(e=>(p?.name&&e.name.toLowerCase()==="content-type"&&(q=!0,e.value=p.name),e)).concat(A);!q&&p?.name&&H.unshift({name:"Content-Type",value:p?.name});const G=t.parameters.filter(e=>e.in==="cookie").filter(e=>!(s&&!e.required)).map(e=>j.parse(P(e,e.serverValues?.[l]?.example||e.example||v(e.schema.rawSchema,O,i)))).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=>!(s&&!e.required)).map(e=>j.parse(P(e,e.serverValues?.[l]?.example||e.example||v(e.schema.rawSchema,O,i)))).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=b?.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||o[S]||M(y,S),e},{}),E=p?.name.toLowerCase(),I=E===m.MULTIPART||E===m.URL_ENCODED,R=I?p?.formExamples?.[a]:p?.examples?.[a],ae=I?p?.formExamples||{}:p?.examples||{},[U]=Object.values(ae),N=R?.serverValues?.[l]?.value||U?.serverValues?.[l]?.value,D=e=>!e||typeof e!="object"||!p?.schema?.rawSchema?null:v(ge(p.schema.rawSchema,e),{...O,format:"xml"},i),C=(()=>{if(h?.body)return h.body;if(E===m.XML){const e=D(N)||D(R?.value)||D(U?.value);if(e)return e;if(p?.schema)return v(p.schema.rawSchema,{...O,format:"xml"},i)}else{const e=p?.schema&&v(p.schema.rawSchema,{...O,format:"json"},i);return N||R?.value||U?.value||e}return""})();let g="",$=[];switch(me(E)){case m.JSON:g=JSON.stringify(V(C,u));break;case m.XML:g=C;break;case m.URL_ENCODED:case m.MULTIPART:g=j.stringify(V(C,u)),$=Y(V(C,u));break;default:g=String(C||"")}const se=g?{mimeType:p?.name||m.OCTET_STREAM,text:g,params:$}: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:d,allResponseCodes:ne}}const f={withImports:!0,withComments:!1},x={curl:{code:"shell",defaultTarget:"curl",defaultOptions:{...f,short:!0}},JavaScript:{code:"javascript",defaultTarget:"fetch",defaultOptions:{...f,withImports:!1}},"Node.js":{code:"node",defaultTarget:"fetch",defaultOptions:{...f}},Python:{code:"python",defaultTarget:"requests",defaultOptions:{...f}},"Java8+Apache":{code:"java8",defaultTarget:"apachehttp",defaultOptions:{...f}},Java:{code:"java",defaultTarget:"httpclient",defaultOptions:{...f}},"C#":{code:"csharp",defaultTarget:"httpclient",defaultOptions:{...f}},"C#+Newtonsoft":{code:"csharpNewtonsoft",defaultTarget:"httpclient",defaultOptions:{...f}},Go:{code:"go",defaultTarget:"http.DefaultClient",defaultOptions:{...f}},PHP:{code:"php",defaultTarget:"curl",defaultOptions:{...f}},Ruby:{code:"ruby",defaultTarget:"net::http",defaultOptions:{...f}},R:{code:"r",defaultTarget:"httr",defaultOptions:{...f}}};function Ue({lang:t,operation:a,exampleName:s,pathParams:c,properties:i,options:r={},environment:o,translate:u}){try{const{skipOptionalParameters:n,withOAuth2Call:d,spec:k,generatedPayloadSamplesMaxDepth:T,store:l,activeMimeName:b}=r,w=he(a,{exampleName:s,pathParams:c,properties:i,skipOptionalParameters:n,withOAuth2Call:d,spec:k,generatedPayloadSamplesMaxDepth:T,activeMimeName:b},{environment:o,requestValues:l.requestValues,activeSecuritySchemeIds:l.activeSecuritySchemeIds}),A=new fe(w);return x[t]?A.convert(x[t].code,x[t].defaultTarget,{...x[t].defaultOptions,...r}):u("openapi.unsupportedLanguage","Language is not supported.")}catch(n){return console.error(n),u("openapi.failedToGenerateCodeSample","Failed to generate code sample.")}}function Se(t,a,s){const c={securityHeaders:[],securityCookies:[],securityQueries:[],securityOAuth2ExtraCalls:[],basicAuth:void 0},i=s?.server;for(const r of t?.schemes||[]){const o=ue(r.id,s),u=i&&r.serverValues&&r.serverValues[i],n={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"]},d=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":c.securityHeaders?.push({name:"Authorization",value:n.access_token?`${n.token_type||"Bearer"} ${n.access_token}`:o.token?`${n.token_type||o.token.token_type||"Bearer"} ${o.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>"});break;case"oauth2":{const l=n.access_token?`${n.token_type||"Bearer"} ${n.access_token}`:o.token?`${o.token.token_type||"Bearer"} ${o.token.access_token}`:"Bearer <YOUR_TOKEN_HERE>";r.flows.clientCredentials&&a?c.securityOAuth2ExtraCalls.push(Te(r.flows.clientCredentials,T,{...o,client_id:n.client_id||o.client_id,client_secret:n.client_secret||o.client_secret})):r.flows.password&&a&&c.securityOAuth2ExtraCalls.push(_e(r.flows.password,T,{...o,client_id:n.client_id||o.client_id,client_secret:n.client_secret||o.client_secret})),c.securityHeaders?.push({name:"Authorization",value:l});break}case"apiKey":{const l=n.access_token||o.raw||"YOUR_API_KEY_HERE";r.in==="header"&&c.securityHeaders?.push({name:r.name,value:l}),r.in==="cookie"&&c.securityCookies.push({name:r.name,value:l}),r.in==="query"&&c.securityQueries.push({name:r.name,value:l});break}case"http":if(r.scheme==="basic")c.basicAuth={username:d||o.username||`<${J.toSnakeCase("Username")}>`,password:k||o.password||`<${J.toSnakeCase("Password")}>`};else{const l=n?.access_token||o.token?.access_token||`<YOUR_${r.bearerFormat||"TOKEN"}_HERE>`;c.securityHeaders?.push({name:"Authorization",value:`${Oe(r.scheme||"bearer")} ${l}`})}break}}return c}function _e(t,a,s){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.client_id||"YOUR_CLIENT_ID"},{name:"client_secret",value:s.client_secret||"YOUR_CLIENT_SECRET"},{name:"username",value:s.username||"<username>"},{name:"password",value:s.password||"<password>"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(B)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[]}}function Te(t,a,s){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.client_id||"YOUR_CLIENT_ID"},{name:"client_secret",value:s.client_secret||"YOUR_CLIENT_SECRET"},a.length?{name:"scope",value:a.join(" ")}:void 0].filter(B)},cookies:[],headersSize:-1,bodySize:-1,securityOAuth2ExtraCalls:[]}}function V(t,a){if(t){if(ce(t))return Object.keys(t).length>0&&Object.keys(a).length===0?t:L(t,a,{arrayMerge:z});try{return L(JSON.parse(t),a,{arrayMerge:z})}catch{return!1}}return!1}function Y(t,a=""){const s=[];for(const[c,i]of Object.entries(t)){const r=a?`${a}[${c}]`:c;if(typeof i=="object"&&i!==null)s.push(...Y(i,r));else{const o=Array.isArray(t)&&typeof i=="string"&&a?a:r;s.push({name:o,value:String(i)})}}return s}function B(t){return t!==void 0}function Oe(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 s=JSON.parse(JSON.stringify(t));function c(i,r){if(!(!i||!r||typeof i!="object"||typeof r!="object")&&i.properties){for(const o in i.properties)if(r[o]!==void 0){const u=i.properties[o],n=r[o];if(u.type==="object"&&typeof n=="object"&&!Array.isArray(n))c(u,n);else if(u.type==="array"&&Array.isArray(n)&&n.length>0){const d=n[0];u.items&&u.items.properties&&c(u.items,d)}else u.example=n}}}return c(s,a),s}export{Oe as capitalizeFirst,Ue as getCodeSample,V as getDataRequest,B as isDefined,v as safeSample};
1
+ import * as Sampler from 'openapi-sampler';
2
+ import merge from 'deepmerge';
3
+ import { isObject } from '@redocly/theme/core/openapi';
4
+ import { areArraysEqual, serializeParameterValue, getSecurityDetails, getParameterValue, queryString, isArrayOfObjects, deleteEmptyArrayItem, } from '../../utils/index.js';
5
+ import { normalizeMimeType, arrayMergeStrategy } from '../utils.js';
6
+ import { MediaTypes } from '../../constants.js';
7
+ import { HTTPSnippet } from './httpsnippet/index.js';
8
+ import { getActiveMediaType } from '../../models/mediaContent.js';
9
+ import StringUtility from './httpsnippet/helpers/string-utility.js';
10
+ export function safeSample(schema, options, document) {
11
+ try {
12
+ return Sampler.sample(schema, options, document);
13
+ }
14
+ catch (e) {
15
+ console.error(`Error sampling schema: ${e.message}`);
16
+ return null;
17
+ }
18
+ }
19
+ function getSelectedSecurityScheme(operationSecurity, activeSecuritySchemeIds) {
20
+ return operationSecurity.find((sec) => {
21
+ const secSchemesIds = sec.schemes.map((scheme) => scheme.id);
22
+ return areArraysEqual(secSchemesIds, activeSecuritySchemeIds || []);
23
+ });
24
+ }
25
+ function mapOperationToHAR(operation, { exampleName = '', skipOptionalParameters = false, withOAuth2Call = false, spec, generatedPayloadSamplesMaxDepth = 8, pathParams = {}, properties = {}, activeMimeName = '', }, { environment, requestValues, activeSecuritySchemeIds, }) {
26
+ const envServer = environment.server;
27
+ const activeServer = operation.servers.find((server) => server.url === envServer) || operation.servers[0];
28
+ const selectedSecurityScheme = getSelectedSecurityScheme(operation.security, activeSecuritySchemeIds);
29
+ const { securityHeaders, securityCookies, securityQueries, securityOAuth2ExtraCalls, basicAuth } = getSecurityData(selectedSecurityScheme || operation.security?.[0], withOAuth2Call, environment); // TODO: add dropdown for security type select
30
+ const activeMimeType = operation?.requestBody?.content &&
31
+ getActiveMediaType(operation.requestBody.content, activeMimeName);
32
+ const samplerOptions = {
33
+ skipNonRequired: skipOptionalParameters,
34
+ skipReadOnly: true,
35
+ maxSampleDepth: generatedPayloadSamplesMaxDepth,
36
+ quiet: true,
37
+ };
38
+ const tryItRequestValues = requestValues;
39
+ let hasContentTypeHeader = false;
40
+ const headers = operation.parameters
41
+ .filter((param) => param.in === 'header')
42
+ .filter((param) => !(skipOptionalParameters && !param.required))
43
+ .map((header) => ({
44
+ name: header.name,
45
+ value: tryItRequestValues['header']?.[header.name] ||
46
+ getParameterValue('header', header.name) ||
47
+ header.serverValues?.[envServer]?.example ||
48
+ header.example ||
49
+ serializeParameterValue(header, safeSample(header.schema.rawSchema, samplerOptions, spec)),
50
+ }))
51
+ .map((header) => {
52
+ if (
53
+ // Overwrite content-type header from selected value in dropdown
54
+ activeMimeType?.name &&
55
+ header.name.toLowerCase() === 'content-type') {
56
+ hasContentTypeHeader = true;
57
+ header.value = activeMimeType.name;
58
+ }
59
+ return header;
60
+ })
61
+ .concat(securityHeaders);
62
+ if (!hasContentTypeHeader && activeMimeType?.name) {
63
+ headers.unshift({
64
+ name: 'Content-Type',
65
+ value: activeMimeType?.name,
66
+ });
67
+ }
68
+ const cookies = operation.parameters
69
+ .filter((param) => param.in === 'cookie')
70
+ .filter((param) => !(skipOptionalParameters && !param.required))
71
+ .map((cookie) => queryString.parse(serializeParameterValue(cookie, cookie.serverValues?.[envServer]?.example ||
72
+ cookie.example ||
73
+ safeSample(cookie.schema.rawSchema, samplerOptions, spec))))
74
+ .reduce((acc, current) => {
75
+ for (const [key, value] of Object.entries(current)) {
76
+ acc.push({
77
+ name: key,
78
+ value: String(tryItRequestValues['cookie']?.[key] || value),
79
+ });
80
+ }
81
+ return acc;
82
+ }, [])
83
+ .concat(securityCookies);
84
+ const queryParams = operation.parameters
85
+ .filter((param) => param.in === 'query')
86
+ .filter((param) => !(skipOptionalParameters && !param.required))
87
+ .map((query) => {
88
+ return queryString.parse(serializeParameterValue(query, query.serverValues?.[envServer]?.example ||
89
+ query.example ||
90
+ safeSample(query.schema.rawSchema, samplerOptions, spec)));
91
+ })
92
+ .reduce((acc, current) => {
93
+ for (const [key, value] of Object.entries(current)) {
94
+ acc.push({
95
+ name: key,
96
+ value: (isArrayOfObjects(tryItRequestValues['query']?.[key]) &&
97
+ JSON.stringify(deleteEmptyArrayItem(tryItRequestValues['query']?.[key]))) ||
98
+ String(tryItRequestValues['query']?.[key] || value),
99
+ });
100
+ }
101
+ return acc;
102
+ }, [])
103
+ .concat(securityQueries);
104
+ const server = activeServer?.url.replace(/\/$/, ''); // remove trailing slash
105
+ const path = operation.path.replace(/^\//, '');
106
+ const url = `${server}/${path}`;
107
+ // should we use examples instead of name?
108
+ const pathParameters = operation.parameters
109
+ .filter((param) => param.in === 'path')
110
+ .reduce((acc, value) => {
111
+ const { in: _in, name } = value;
112
+ acc[name] =
113
+ tryItRequestValues['path']?.[name] ||
114
+ value.serverValues?.[envServer]?.example ||
115
+ value.example ||
116
+ pathParams[name] ||
117
+ getParameterValue(_in, name);
118
+ return acc;
119
+ }, {});
120
+ const contentType = activeMimeType?.name.toLowerCase();
121
+ const useFormValues = contentType === MediaTypes.MULTIPART || contentType === MediaTypes.URL_ENCODED;
122
+ const activeExample = useFormValues
123
+ ? activeMimeType?.formExamples?.[exampleName]
124
+ : activeMimeType?.examples?.[exampleName];
125
+ // Getting example by name or just first example in name is not provided
126
+ const examples = useFormValues
127
+ ? activeMimeType?.formExamples || {}
128
+ : activeMimeType?.examples || {};
129
+ const [firstExample] = Object.values(examples);
130
+ const serverSpecificValue = activeExample?.serverValues?.[envServer]?.value ||
131
+ firstExample?.serverValues?.[envServer]?.value;
132
+ const processXmlSchema = (values) => {
133
+ if (!values || typeof values !== 'object' || !activeMimeType?.schema?.rawSchema) {
134
+ return null;
135
+ }
136
+ return safeSample(populateXmlSchemaFields(activeMimeType.schema.rawSchema, values), { ...samplerOptions, format: 'xml' }, spec);
137
+ };
138
+ const getExampleValue = () => {
139
+ if (tryItRequestValues?.['body']) {
140
+ return tryItRequestValues['body'];
141
+ }
142
+ if (contentType === MediaTypes.XML) {
143
+ const xmlProcessed = processXmlSchema(serverSpecificValue) ||
144
+ processXmlSchema(activeExample?.value) ||
145
+ processXmlSchema(firstExample?.value);
146
+ if (xmlProcessed) {
147
+ return xmlProcessed;
148
+ }
149
+ if (activeMimeType?.schema) {
150
+ return safeSample(activeMimeType.schema.rawSchema, { ...samplerOptions, format: 'xml' }, spec);
151
+ }
152
+ }
153
+ else {
154
+ const sampledValue = activeMimeType?.schema &&
155
+ safeSample(activeMimeType.schema.rawSchema, { ...samplerOptions, format: 'json' }, spec);
156
+ return serverSpecificValue || activeExample?.value || firstExample?.value || sampledValue;
157
+ }
158
+ return '';
159
+ };
160
+ const exampleValue = getExampleValue();
161
+ let textPostData = '';
162
+ let postDataParams = [];
163
+ switch (normalizeMimeType(contentType)) {
164
+ case MediaTypes.JSON:
165
+ textPostData = JSON.stringify(getDataRequest(exampleValue, properties));
166
+ break;
167
+ case MediaTypes.XML:
168
+ textPostData = exampleValue;
169
+ break;
170
+ case MediaTypes.URL_ENCODED:
171
+ case MediaTypes.MULTIPART:
172
+ textPostData = queryString.stringify(getDataRequest(exampleValue, properties));
173
+ postDataParams = objectToHarParams(getDataRequest(exampleValue, properties));
174
+ break;
175
+ default:
176
+ textPostData = String(exampleValue || '');
177
+ }
178
+ const postData = textPostData
179
+ ? {
180
+ mimeType: activeMimeType?.name || MediaTypes.OCTET_STREAM,
181
+ text: textPostData,
182
+ params: postDataParams,
183
+ }
184
+ : undefined;
185
+ const allResponseCodes = operation.responses.map((response) => response.code);
186
+ return {
187
+ method: operation.httpVerb,
188
+ url,
189
+ httpVersion: 'HTTP/1.1',
190
+ cookies: cookies,
191
+ headers: headers,
192
+ queryString: queryParams,
193
+ postData,
194
+ headersSize: -1,
195
+ bodySize: -1,
196
+ securityOAuth2ExtraCalls,
197
+ basicAuth,
198
+ pathParameters,
199
+ serverVariables: environment,
200
+ allResponseCodes,
201
+ };
202
+ }
203
+ const defaultOptions = { withImports: true, withComments: false };
204
+ // Map language to 'httpsnippet' library target code
205
+ const langToSnippetConfig = {
206
+ curl: {
207
+ code: 'shell',
208
+ defaultTarget: 'curl',
209
+ defaultOptions: { ...defaultOptions, short: true },
210
+ },
211
+ JavaScript: {
212
+ code: 'javascript',
213
+ defaultTarget: 'fetch',
214
+ defaultOptions: {
215
+ ...defaultOptions,
216
+ withImports: false,
217
+ },
218
+ },
219
+ 'Node.js': {
220
+ code: 'node',
221
+ defaultTarget: 'fetch',
222
+ defaultOptions: { ...defaultOptions },
223
+ },
224
+ Python: {
225
+ code: 'python',
226
+ defaultTarget: 'requests',
227
+ defaultOptions: { ...defaultOptions },
228
+ },
229
+ 'Java8+Apache': {
230
+ code: 'java8',
231
+ defaultTarget: 'apachehttp',
232
+ defaultOptions: { ...defaultOptions },
233
+ },
234
+ Java: {
235
+ code: 'java',
236
+ defaultTarget: 'httpclient',
237
+ defaultOptions: { ...defaultOptions },
238
+ },
239
+ 'C#': {
240
+ code: 'csharp',
241
+ defaultTarget: 'httpclient',
242
+ defaultOptions: { ...defaultOptions },
243
+ },
244
+ 'C#+Newtonsoft': {
245
+ code: 'csharpNewtonsoft',
246
+ defaultTarget: 'httpclient',
247
+ defaultOptions: { ...defaultOptions },
248
+ },
249
+ Go: {
250
+ code: 'go',
251
+ defaultTarget: 'http.DefaultClient',
252
+ defaultOptions: { ...defaultOptions },
253
+ },
254
+ PHP: {
255
+ code: 'php',
256
+ defaultTarget: 'curl',
257
+ defaultOptions: { ...defaultOptions },
258
+ },
259
+ Ruby: {
260
+ code: 'ruby',
261
+ defaultTarget: 'net::http',
262
+ defaultOptions: { ...defaultOptions },
263
+ },
264
+ R: {
265
+ code: 'r',
266
+ defaultTarget: 'httr',
267
+ defaultOptions: { ...defaultOptions },
268
+ },
269
+ };
270
+ export function getCodeSample({ lang, operation, exampleName, pathParams, properties, options = {}, environment, translate, }) {
271
+ try {
272
+ const { skipOptionalParameters, withOAuth2Call, spec, generatedPayloadSamplesMaxDepth, store: operationStore, activeMimeName, } = options;
273
+ const har = mapOperationToHAR(operation, {
274
+ exampleName,
275
+ pathParams,
276
+ properties,
277
+ skipOptionalParameters,
278
+ withOAuth2Call,
279
+ spec,
280
+ generatedPayloadSamplesMaxDepth,
281
+ activeMimeName,
282
+ }, {
283
+ environment,
284
+ requestValues: operationStore.requestValues,
285
+ activeSecuritySchemeIds: operationStore.activeSecuritySchemeIds,
286
+ });
287
+ const snippet = new HTTPSnippet(har);
288
+ if (!langToSnippetConfig[lang]) {
289
+ return translate('openapi.unsupportedLanguage', 'Language is not supported.');
290
+ }
291
+ return snippet.convert(langToSnippetConfig[lang].code, langToSnippetConfig[lang].defaultTarget, {
292
+ ...langToSnippetConfig[lang].defaultOptions,
293
+ ...options,
294
+ });
295
+ }
296
+ catch (e) {
297
+ console.error(e);
298
+ return translate('openapi.failedToGenerateCodeSample', 'Failed to generate code sample.');
299
+ }
300
+ }
301
+ function getSecurityData(requirement, withOAuth2Call, environment) {
302
+ const securityData = {
303
+ securityHeaders: [],
304
+ securityCookies: [],
305
+ securityQueries: [],
306
+ securityOAuth2ExtraCalls: [],
307
+ basicAuth: undefined,
308
+ };
309
+ const serverUrl = environment?.server;
310
+ for (const scheme of requirement?.schemes || []) {
311
+ const authDetails = getSecurityDetails(scheme.id, environment);
312
+ const serverCredentials = serverUrl && scheme.serverValues && scheme.serverValues[serverUrl];
313
+ const operationSecurityValue = {
314
+ access_token: serverCredentials?.['x-defaultAccessToken'] || scheme['x-defaultAccessToken'],
315
+ token_type: serverCredentials?.['x-defaultTokenType'] || scheme['x-defaultTokenType'],
316
+ client_id: serverCredentials?.['x-defaultClientId'] || scheme['x-defaultClientId'],
317
+ client_secret: serverCredentials?.['x-defaultClientSecret'] || scheme['x-defaultClientSecret'],
318
+ };
319
+ const operationUsername = serverCredentials?.['x-defaultUsername'] || scheme['x-defaultUsername'];
320
+ const operationPassword = serverCredentials?.['x-defaultPassword'] || scheme['x-defaultPassword'];
321
+ const operationScopes = serverCredentials && 'scopes' in serverCredentials
322
+ ? serverCredentials.scopes || []
323
+ : scheme.scopes || [];
324
+ switch (scheme.type) {
325
+ case 'openIdConnect':
326
+ securityData.securityHeaders?.push({
327
+ name: 'Authorization',
328
+ value: operationSecurityValue.access_token
329
+ ? `${operationSecurityValue.token_type || 'Bearer'} ${operationSecurityValue.access_token}`
330
+ : authDetails.token
331
+ ? `${operationSecurityValue.token_type || authDetails.token.token_type || 'Bearer'} ${authDetails.token.access_token}`
332
+ : 'Bearer <YOUR_TOKEN_HERE>',
333
+ });
334
+ break;
335
+ case 'oauth2': {
336
+ const authTokenValue = operationSecurityValue.access_token
337
+ ? `${operationSecurityValue.token_type || 'Bearer'} ${operationSecurityValue.access_token}`
338
+ : authDetails.token
339
+ ? `${authDetails.token.token_type || 'Bearer'} ${authDetails.token.access_token}`
340
+ : 'Bearer <YOUR_TOKEN_HERE>';
341
+ if (scheme.flows.clientCredentials && withOAuth2Call) {
342
+ securityData.securityOAuth2ExtraCalls.push(getOAuth2ClientCredsCallHar(scheme.flows.clientCredentials, operationScopes, {
343
+ ...authDetails,
344
+ client_id: operationSecurityValue.client_id || authDetails.client_id,
345
+ client_secret: operationSecurityValue.client_secret || authDetails.client_secret,
346
+ }));
347
+ }
348
+ else if (scheme.flows.password && withOAuth2Call) {
349
+ securityData.securityOAuth2ExtraCalls.push(getOAuth2PasswordCallHar(scheme.flows.password, operationScopes, {
350
+ ...authDetails,
351
+ client_id: operationSecurityValue.client_id || authDetails.client_id,
352
+ client_secret: operationSecurityValue.client_secret || authDetails.client_secret,
353
+ }));
354
+ }
355
+ securityData.securityHeaders?.push({ name: 'Authorization', value: authTokenValue });
356
+ break;
357
+ }
358
+ case 'apiKey': {
359
+ const value = operationSecurityValue.access_token || authDetails.raw || 'YOUR_API_KEY_HERE';
360
+ if (scheme.in === 'header') {
361
+ securityData.securityHeaders?.push({
362
+ name: scheme.name,
363
+ value,
364
+ });
365
+ }
366
+ if (scheme.in === 'cookie') {
367
+ securityData.securityCookies.push({
368
+ name: scheme.name,
369
+ value,
370
+ });
371
+ }
372
+ if (scheme.in === 'query') {
373
+ securityData.securityQueries.push({
374
+ name: scheme.name,
375
+ value,
376
+ });
377
+ }
378
+ break;
379
+ }
380
+ case 'http':
381
+ if (scheme.scheme === 'basic') {
382
+ securityData.basicAuth = {
383
+ username: operationUsername ||
384
+ authDetails.username ||
385
+ `<${StringUtility.toSnakeCase('Username')}>`,
386
+ password: operationPassword ||
387
+ authDetails.password ||
388
+ `<${StringUtility.toSnakeCase('Password')}>`,
389
+ };
390
+ }
391
+ else {
392
+ const token = operationSecurityValue?.access_token ||
393
+ authDetails.token?.access_token ||
394
+ `<YOUR_${scheme.bearerFormat || 'TOKEN'}_HERE>`;
395
+ securityData.securityHeaders?.push({
396
+ name: 'Authorization',
397
+ value: `${capitalizeFirst(scheme.scheme || 'bearer')} ${token}`,
398
+ });
399
+ }
400
+ break;
401
+ }
402
+ }
403
+ return securityData;
404
+ }
405
+ function getOAuth2PasswordCallHar(flow, scopes, authDetails) {
406
+ return {
407
+ method: 'POST',
408
+ url: flow.tokenUrl,
409
+ httpVersion: 'HTTP/1.1',
410
+ headers: [
411
+ { name: 'Content-Type', value: MediaTypes.URL_ENCODED },
412
+ { name: 'Accept', value: MediaTypes.JSON },
413
+ ],
414
+ queryString: [],
415
+ postData: {
416
+ mimeType: MediaTypes.URL_ENCODED,
417
+ text: '',
418
+ params: [
419
+ { name: 'grant_type', value: 'password' },
420
+ { name: 'client_id', value: authDetails.client_id || 'YOUR_CLIENT_ID' },
421
+ { name: 'client_secret', value: authDetails.client_secret || 'YOUR_CLIENT_SECRET' },
422
+ { name: 'username', value: authDetails.username || '<username>' },
423
+ { name: 'password', value: authDetails.password || '<password>' },
424
+ scopes.length ? { name: 'scope', value: scopes.join(' ') } : undefined,
425
+ ].filter(isDefined),
426
+ },
427
+ cookies: [],
428
+ headersSize: -1,
429
+ bodySize: -1,
430
+ securityOAuth2ExtraCalls: [],
431
+ };
432
+ }
433
+ function getOAuth2ClientCredsCallHar(flow, scopes, authDetails) {
434
+ return {
435
+ method: 'POST',
436
+ url: flow.tokenUrl,
437
+ httpVersion: 'HTTP/1.1',
438
+ headers: [
439
+ { name: 'Content-Type', value: MediaTypes.URL_ENCODED },
440
+ { name: 'Accept', value: MediaTypes.JSON },
441
+ ],
442
+ queryString: [],
443
+ postData: {
444
+ mimeType: MediaTypes.URL_ENCODED,
445
+ text: '',
446
+ params: [
447
+ { name: 'grant_type', value: 'client_credentials' },
448
+ { name: 'client_id', value: authDetails.client_id || 'YOUR_CLIENT_ID' },
449
+ { name: 'client_secret', value: authDetails.client_secret || 'YOUR_CLIENT_SECRET' },
450
+ scopes.length ? { name: 'scope', value: scopes.join(' ') } : undefined,
451
+ ].filter(isDefined),
452
+ },
453
+ cookies: [],
454
+ headersSize: -1,
455
+ bodySize: -1,
456
+ securityOAuth2ExtraCalls: [],
457
+ };
458
+ }
459
+ export function getDataRequest(exampleValue, properties) {
460
+ if (exampleValue) {
461
+ if (isObject(exampleValue)) {
462
+ if (Object.keys(exampleValue).length > 0 && Object.keys(properties).length === 0) {
463
+ return exampleValue;
464
+ }
465
+ else {
466
+ return merge(exampleValue, properties, { arrayMerge: arrayMergeStrategy });
467
+ }
468
+ }
469
+ try {
470
+ return merge(JSON.parse(exampleValue), properties, { arrayMerge: arrayMergeStrategy });
471
+ }
472
+ catch {
473
+ return false;
474
+ }
475
+ }
476
+ return false;
477
+ }
478
+ function objectToHarParams(obj, parentKey = '') {
479
+ const res = [];
480
+ for (const [key, value] of Object.entries(obj)) {
481
+ const currentKey = parentKey ? `${parentKey}[${key}]` : key;
482
+ if (typeof value === 'object' && value !== null) {
483
+ res.push(...objectToHarParams(value, currentKey));
484
+ }
485
+ else {
486
+ const name = Array.isArray(obj) && typeof value === 'string' && parentKey ? parentKey : currentKey;
487
+ res.push({ name, value: String(value) });
488
+ }
489
+ }
490
+ return res;
491
+ }
492
+ export function isDefined(arg) {
493
+ return arg !== undefined;
494
+ }
495
+ export function capitalizeFirst(str) {
496
+ return str.charAt(0).toUpperCase() + str.slice(1);
497
+ }
498
+ function populateXmlSchemaFields(schema, values) {
499
+ if (!schema || typeof schema !== 'object' || !values || typeof values !== 'object') {
500
+ return schema;
501
+ }
502
+ const updatedSchema = JSON.parse(JSON.stringify(schema));
503
+ function populateValues(schemaNode, valueNode) {
504
+ if (!schemaNode ||
505
+ !valueNode ||
506
+ typeof schemaNode !== 'object' ||
507
+ typeof valueNode !== 'object') {
508
+ return;
509
+ }
510
+ if (schemaNode.properties) {
511
+ for (const propName in schemaNode.properties) {
512
+ if (valueNode[propName] !== undefined) {
513
+ const propSchema = schemaNode.properties[propName];
514
+ const propValue = valueNode[propName];
515
+ if (propSchema.type === 'object' &&
516
+ typeof propValue === 'object' &&
517
+ !Array.isArray(propValue)) {
518
+ populateValues(propSchema, propValue);
519
+ }
520
+ else if (propSchema.type === 'array' &&
521
+ Array.isArray(propValue) &&
522
+ propValue.length > 0) {
523
+ // For arrays, use the first item from values array to update item examples
524
+ const firstItem = propValue[0];
525
+ if (propSchema.items && propSchema.items.properties) {
526
+ populateValues(propSchema.items, firstItem);
527
+ }
528
+ }
529
+ else {
530
+ propSchema.example = propValue;
531
+ }
532
+ }
533
+ // If value doesn't exist for this property, just skip it (keep original example)
534
+ }
535
+ }
536
+ }
537
+ populateValues(updatedSchema, values);
538
+ return updatedSchema;
539
+ }
540
+ //# sourceMappingURL=generator.js.map