@readme/httpsnippet 6.2.1 → 7.0.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 (494) hide show
  1. package/dist/chunk-XPUGYZ4Y.mjs +3485 -0
  2. package/dist/chunk-XPUGYZ4Y.mjs.map +1 -0
  3. package/dist/index-acc66e3d.d.ts +167 -0
  4. package/dist/index.d.mts +4 -0
  5. package/dist/index.d.ts +4 -95
  6. package/dist/index.js +3777 -261
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.mjs +299 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/targets/targets.d.mts +4 -0
  11. package/dist/targets/targets.d.ts +4 -53
  12. package/dist/targets/targets.js +3476 -113
  13. package/dist/targets/targets.js.map +1 -0
  14. package/dist/targets/targets.mjs +3 -0
  15. package/dist/targets/targets.mjs.map +1 -0
  16. package/package.json +40 -14
  17. package/dist/helpers/code-builder.d.ts +0 -49
  18. package/dist/helpers/code-builder.js +0 -91
  19. package/dist/helpers/escape.d.ts +0 -46
  20. package/dist/helpers/escape.js +0 -101
  21. package/dist/helpers/form-data.d.ts +0 -30
  22. package/dist/helpers/form-data.js +0 -157
  23. package/dist/helpers/headers.d.ts +0 -18
  24. package/dist/helpers/headers.js +0 -33
  25. package/dist/helpers/reducer.d.ts +0 -5
  26. package/dist/helpers/reducer.js +0 -19
  27. package/dist/helpers/shell.d.ts +0 -6
  28. package/dist/helpers/shell.js +0 -20
  29. package/dist/helpers/utils.d.ts +0 -6
  30. package/dist/helpers/utils.js +0 -21
  31. package/dist/targets/c/libcurl/client.d.ts +0 -2
  32. package/dist/targets/c/libcurl/client.js +0 -45
  33. package/dist/targets/c/target.d.ts +0 -2
  34. package/dist/targets/c/target.js +0 -16
  35. package/dist/targets/clojure/clj_http/client.d.ts +0 -11
  36. package/dist/targets/clojure/clj_http/client.js +0 -178
  37. package/dist/targets/clojure/target.d.ts +0 -2
  38. package/dist/targets/clojure/target.js +0 -15
  39. package/dist/targets/csharp/httpclient/client.d.ts +0 -2
  40. package/dist/targets/csharp/httpclient/client.js +0 -163
  41. package/dist/targets/csharp/restsharp/client.d.ts +0 -2
  42. package/dist/targets/csharp/restsharp/client.js +0 -92
  43. package/dist/targets/csharp/target.d.ts +0 -2
  44. package/dist/targets/csharp/target.js +0 -18
  45. package/dist/targets/go/native/client.d.ts +0 -17
  46. package/dist/targets/go/native/client.js +0 -103
  47. package/dist/targets/go/target.d.ts +0 -2
  48. package/dist/targets/go/target.js +0 -16
  49. package/dist/targets/http/http1.1/client.d.ts +0 -23
  50. package/dist/targets/http/http1.1/client.js +0 -69
  51. package/dist/targets/http/target.d.ts +0 -2
  52. package/dist/targets/http/target.js +0 -15
  53. package/dist/targets/java/asynchttp/client.d.ts +0 -11
  54. package/dist/targets/java/asynchttp/client.js +0 -45
  55. package/dist/targets/java/nethttp/client.d.ts +0 -14
  56. package/dist/targets/java/nethttp/client.js +0 -44
  57. package/dist/targets/java/okhttp/client.d.ts +0 -11
  58. package/dist/targets/java/okhttp/client.js +0 -71
  59. package/dist/targets/java/target.d.ts +0 -2
  60. package/dist/targets/java/target.js +0 -21
  61. package/dist/targets/java/unirest/client.d.ts +0 -11
  62. package/dist/targets/java/unirest/client.js +0 -45
  63. package/dist/targets/javascript/axios/client.d.ts +0 -11
  64. package/dist/targets/javascript/axios/client.js +0 -92
  65. package/dist/targets/javascript/axios/fixtures/application-form-encoded.d.ts +0 -1
  66. package/dist/targets/javascript/axios/fixtures/application-form-encoded.js +0 -23
  67. package/dist/targets/javascript/axios/fixtures/application-json.d.ts +0 -1
  68. package/dist/targets/javascript/axios/fixtures/application-json.js +0 -27
  69. package/dist/targets/javascript/axios/fixtures/cookies.d.ts +0 -1
  70. package/dist/targets/javascript/axios/fixtures/cookies.js +0 -19
  71. package/dist/targets/javascript/axios/fixtures/custom-method.d.ts +0 -1
  72. package/dist/targets/javascript/axios/fixtures/custom-method.js +0 -15
  73. package/dist/targets/javascript/axios/fixtures/full.d.ts +0 -1
  74. package/dist/targets/javascript/axios/fixtures/full.js +0 -27
  75. package/dist/targets/javascript/axios/fixtures/headers.d.ts +0 -1
  76. package/dist/targets/javascript/axios/fixtures/headers.js +0 -24
  77. package/dist/targets/javascript/axios/fixtures/http-insecure.d.ts +0 -1
  78. package/dist/targets/javascript/axios/fixtures/http-insecure.js +0 -15
  79. package/dist/targets/javascript/axios/fixtures/jsonObj-multiline.d.ts +0 -1
  80. package/dist/targets/javascript/axios/fixtures/jsonObj-multiline.js +0 -20
  81. package/dist/targets/javascript/axios/fixtures/jsonObj-null-value.d.ts +0 -1
  82. package/dist/targets/javascript/axios/fixtures/jsonObj-null-value.js +0 -20
  83. package/dist/targets/javascript/axios/fixtures/multipart-data.d.ts +0 -1
  84. package/dist/targets/javascript/axios/fixtures/multipart-data.js +0 -23
  85. package/dist/targets/javascript/axios/fixtures/multipart-file.d.ts +0 -1
  86. package/dist/targets/javascript/axios/fixtures/multipart-file.js +0 -22
  87. package/dist/targets/javascript/axios/fixtures/multipart-form-data-no-params.d.ts +0 -1
  88. package/dist/targets/javascript/axios/fixtures/multipart-form-data-no-params.js +0 -19
  89. package/dist/targets/javascript/axios/fixtures/multipart-form-data.d.ts +0 -1
  90. package/dist/targets/javascript/axios/fixtures/multipart-form-data.js +0 -22
  91. package/dist/targets/javascript/axios/fixtures/nested.d.ts +0 -1
  92. package/dist/targets/javascript/axios/fixtures/nested.js +0 -19
  93. package/dist/targets/javascript/axios/fixtures/postdata-malformed.d.ts +0 -1
  94. package/dist/targets/javascript/axios/fixtures/postdata-malformed.js +0 -19
  95. package/dist/targets/javascript/axios/fixtures/query-encoded.d.ts +0 -1
  96. package/dist/targets/javascript/axios/fixtures/query-encoded.js +0 -22
  97. package/dist/targets/javascript/axios/fixtures/query.d.ts +0 -1
  98. package/dist/targets/javascript/axios/fixtures/query.js +0 -19
  99. package/dist/targets/javascript/axios/fixtures/short.d.ts +0 -1
  100. package/dist/targets/javascript/axios/fixtures/short.js +0 -15
  101. package/dist/targets/javascript/axios/fixtures/text-plain.d.ts +0 -1
  102. package/dist/targets/javascript/axios/fixtures/text-plain.js +0 -20
  103. package/dist/targets/javascript/fetch/client.d.ts +0 -15
  104. package/dist/targets/javascript/fetch/client.js +0 -106
  105. package/dist/targets/javascript/fetch/fixtures/application-form-encoded.d.ts +0 -8
  106. package/dist/targets/javascript/fetch/fixtures/application-form-encoded.js +0 -10
  107. package/dist/targets/javascript/fetch/fixtures/application-json.d.ts +0 -7
  108. package/dist/targets/javascript/fetch/fixtures/application-json.js +0 -17
  109. package/dist/targets/javascript/fetch/fixtures/cookies.d.ts +0 -6
  110. package/dist/targets/javascript/fetch/fixtures/cookies.js +0 -6
  111. package/dist/targets/javascript/fetch/fixtures/custom-method.d.ts +0 -3
  112. package/dist/targets/javascript/fetch/fixtures/custom-method.js +0 -6
  113. package/dist/targets/javascript/fetch/fixtures/full.d.ts +0 -10
  114. package/dist/targets/javascript/fetch/fixtures/full.js +0 -14
  115. package/dist/targets/javascript/fetch/fixtures/headers.d.ts +0 -9
  116. package/dist/targets/javascript/fetch/fixtures/headers.js +0 -14
  117. package/dist/targets/javascript/fetch/fixtures/http-insecure.d.ts +0 -3
  118. package/dist/targets/javascript/fetch/fixtures/http-insecure.js +0 -6
  119. package/dist/targets/javascript/fetch/fixtures/jsonObj-multiline.d.ts +0 -7
  120. package/dist/targets/javascript/fetch/fixtures/jsonObj-multiline.js +0 -10
  121. package/dist/targets/javascript/fetch/fixtures/jsonObj-null-value.d.ts +0 -7
  122. package/dist/targets/javascript/fetch/fixtures/jsonObj-null-value.js +0 -10
  123. package/dist/targets/javascript/fetch/fixtures/multipart-data.d.ts +0 -4
  124. package/dist/targets/javascript/fetch/fixtures/multipart-data.js +0 -10
  125. package/dist/targets/javascript/fetch/fixtures/multipart-file.d.ts +0 -4
  126. package/dist/targets/javascript/fetch/fixtures/multipart-file.js +0 -9
  127. package/dist/targets/javascript/fetch/fixtures/multipart-form-data-no-params.d.ts +0 -6
  128. package/dist/targets/javascript/fetch/fixtures/multipart-form-data-no-params.js +0 -6
  129. package/dist/targets/javascript/fetch/fixtures/multipart-form-data.d.ts +0 -4
  130. package/dist/targets/javascript/fetch/fixtures/multipart-form-data.js +0 -9
  131. package/dist/targets/javascript/fetch/fixtures/nested.d.ts +0 -3
  132. package/dist/targets/javascript/fetch/fixtures/nested.js +0 -6
  133. package/dist/targets/javascript/fetch/fixtures/postdata-malformed.d.ts +0 -6
  134. package/dist/targets/javascript/fetch/fixtures/postdata-malformed.js +0 -6
  135. package/dist/targets/javascript/fetch/fixtures/query-encoded.d.ts +0 -3
  136. package/dist/targets/javascript/fetch/fixtures/query-encoded.js +0 -6
  137. package/dist/targets/javascript/fetch/fixtures/query.d.ts +0 -3
  138. package/dist/targets/javascript/fetch/fixtures/query.js +0 -6
  139. package/dist/targets/javascript/fetch/fixtures/short.d.ts +0 -3
  140. package/dist/targets/javascript/fetch/fixtures/short.js +0 -6
  141. package/dist/targets/javascript/fetch/fixtures/text-plain.d.ts +0 -7
  142. package/dist/targets/javascript/fetch/fixtures/text-plain.js +0 -6
  143. package/dist/targets/javascript/jquery/client.d.ts +0 -11
  144. package/dist/targets/javascript/jquery/client.js +0 -84
  145. package/dist/targets/javascript/jquery/fixtures/application-form-encoded.d.ts +0 -13
  146. package/dist/targets/javascript/jquery/fixtures/application-form-encoded.js +0 -17
  147. package/dist/targets/javascript/jquery/fixtures/application-json.d.ts +0 -11
  148. package/dist/targets/javascript/jquery/fixtures/application-json.js +0 -15
  149. package/dist/targets/javascript/jquery/fixtures/cookies.d.ts +0 -9
  150. package/dist/targets/javascript/jquery/fixtures/cookies.js +0 -13
  151. package/dist/targets/javascript/jquery/fixtures/custom-method.d.ts +0 -7
  152. package/dist/targets/javascript/jquery/fixtures/custom-method.js +0 -11
  153. package/dist/targets/javascript/jquery/fixtures/full.d.ts +0 -14
  154. package/dist/targets/javascript/jquery/fixtures/full.js +0 -18
  155. package/dist/targets/javascript/jquery/fixtures/headers.d.ts +0 -12
  156. package/dist/targets/javascript/jquery/fixtures/headers.js +0 -16
  157. package/dist/targets/javascript/jquery/fixtures/http-insecure.d.ts +0 -7
  158. package/dist/targets/javascript/jquery/fixtures/http-insecure.js +0 -11
  159. package/dist/targets/javascript/jquery/fixtures/jsonObj-multiline.d.ts +0 -11
  160. package/dist/targets/javascript/jquery/fixtures/jsonObj-multiline.js +0 -15
  161. package/dist/targets/javascript/jquery/fixtures/jsonObj-null-value.d.ts +0 -11
  162. package/dist/targets/javascript/jquery/fixtures/jsonObj-null-value.js +0 -15
  163. package/dist/targets/javascript/jquery/fixtures/multipart-data.d.ts +0 -12
  164. package/dist/targets/javascript/jquery/fixtures/multipart-data.js +0 -18
  165. package/dist/targets/javascript/jquery/fixtures/multipart-file.d.ts +0 -12
  166. package/dist/targets/javascript/jquery/fixtures/multipart-file.js +0 -17
  167. package/dist/targets/javascript/jquery/fixtures/multipart-form-data-no-params.d.ts +0 -9
  168. package/dist/targets/javascript/jquery/fixtures/multipart-form-data-no-params.js +0 -13
  169. package/dist/targets/javascript/jquery/fixtures/multipart-form-data.d.ts +0 -12
  170. package/dist/targets/javascript/jquery/fixtures/multipart-form-data.js +0 -17
  171. package/dist/targets/javascript/jquery/fixtures/nested.d.ts +0 -7
  172. package/dist/targets/javascript/jquery/fixtures/nested.js +0 -11
  173. package/dist/targets/javascript/jquery/fixtures/postdata-malformed.d.ts +0 -9
  174. package/dist/targets/javascript/jquery/fixtures/postdata-malformed.js +0 -13
  175. package/dist/targets/javascript/jquery/fixtures/query-encoded.d.ts +0 -7
  176. package/dist/targets/javascript/jquery/fixtures/query-encoded.js +0 -11
  177. package/dist/targets/javascript/jquery/fixtures/query.d.ts +0 -7
  178. package/dist/targets/javascript/jquery/fixtures/query.js +0 -11
  179. package/dist/targets/javascript/jquery/fixtures/short.d.ts +0 -7
  180. package/dist/targets/javascript/jquery/fixtures/short.js +0 -11
  181. package/dist/targets/javascript/jquery/fixtures/text-plain.d.ts +0 -10
  182. package/dist/targets/javascript/jquery/fixtures/text-plain.js +0 -14
  183. package/dist/targets/javascript/target.d.ts +0 -2
  184. package/dist/targets/javascript/target.js +0 -21
  185. package/dist/targets/javascript/xhr/client.d.ts +0 -14
  186. package/dist/targets/javascript/xhr/client.js +0 -83
  187. package/dist/targets/javascript/xhr/fixtures/application-form-encoded.d.ts +0 -2
  188. package/dist/targets/javascript/xhr/fixtures/application-form-encoded.js +0 -12
  189. package/dist/targets/javascript/xhr/fixtures/application-json.d.ts +0 -2
  190. package/dist/targets/javascript/xhr/fixtures/application-json.js +0 -31
  191. package/dist/targets/javascript/xhr/fixtures/cookies.d.ts +0 -2
  192. package/dist/targets/javascript/xhr/fixtures/cookies.js +0 -12
  193. package/dist/targets/javascript/xhr/fixtures/cors.d.ts +0 -2
  194. package/dist/targets/javascript/xhr/fixtures/cors.js +0 -10
  195. package/dist/targets/javascript/xhr/fixtures/custom-method.d.ts +0 -2
  196. package/dist/targets/javascript/xhr/fixtures/custom-method.js +0 -11
  197. package/dist/targets/javascript/xhr/fixtures/full.d.ts +0 -2
  198. package/dist/targets/javascript/xhr/fixtures/full.js +0 -14
  199. package/dist/targets/javascript/xhr/fixtures/headers.d.ts +0 -2
  200. package/dist/targets/javascript/xhr/fixtures/headers.js +0 -15
  201. package/dist/targets/javascript/xhr/fixtures/http-insecure.d.ts +0 -2
  202. package/dist/targets/javascript/xhr/fixtures/http-insecure.js +0 -11
  203. package/dist/targets/javascript/xhr/fixtures/jsonObj-multiline.d.ts +0 -2
  204. package/dist/targets/javascript/xhr/fixtures/jsonObj-multiline.js +0 -14
  205. package/dist/targets/javascript/xhr/fixtures/jsonObj-null-value.d.ts +0 -2
  206. package/dist/targets/javascript/xhr/fixtures/jsonObj-null-value.js +0 -14
  207. package/dist/targets/javascript/xhr/fixtures/multipart-data.d.ts +0 -2
  208. package/dist/targets/javascript/xhr/fixtures/multipart-data.js +0 -13
  209. package/dist/targets/javascript/xhr/fixtures/multipart-file.d.ts +0 -2
  210. package/dist/targets/javascript/xhr/fixtures/multipart-file.js +0 -12
  211. package/dist/targets/javascript/xhr/fixtures/multipart-form-data-no-params.d.ts +0 -1
  212. package/dist/targets/javascript/xhr/fixtures/multipart-form-data-no-params.js +0 -11
  213. package/dist/targets/javascript/xhr/fixtures/multipart-form-data.d.ts +0 -2
  214. package/dist/targets/javascript/xhr/fixtures/multipart-form-data.js +0 -12
  215. package/dist/targets/javascript/xhr/fixtures/nested.d.ts +0 -2
  216. package/dist/targets/javascript/xhr/fixtures/nested.js +0 -11
  217. package/dist/targets/javascript/xhr/fixtures/postdata-malformed.d.ts +0 -2
  218. package/dist/targets/javascript/xhr/fixtures/postdata-malformed.js +0 -12
  219. package/dist/targets/javascript/xhr/fixtures/query-encoded.d.ts +0 -2
  220. package/dist/targets/javascript/xhr/fixtures/query-encoded.js +0 -11
  221. package/dist/targets/javascript/xhr/fixtures/query.d.ts +0 -2
  222. package/dist/targets/javascript/xhr/fixtures/query.js +0 -11
  223. package/dist/targets/javascript/xhr/fixtures/short.d.ts +0 -2
  224. package/dist/targets/javascript/xhr/fixtures/short.js +0 -11
  225. package/dist/targets/javascript/xhr/fixtures/text-plain.d.ts +0 -2
  226. package/dist/targets/javascript/xhr/fixtures/text-plain.js +0 -12
  227. package/dist/targets/json/native/client.d.ts +0 -2
  228. package/dist/targets/json/native/client.js +0 -56
  229. package/dist/targets/json/target.d.ts +0 -2
  230. package/dist/targets/json/target.js +0 -15
  231. package/dist/targets/kotlin/okhttp/client.d.ts +0 -11
  232. package/dist/targets/kotlin/okhttp/client.js +0 -71
  233. package/dist/targets/kotlin/target.d.ts +0 -2
  234. package/dist/targets/kotlin/target.js +0 -15
  235. package/dist/targets/node/axios/client.d.ts +0 -11
  236. package/dist/targets/node/axios/client.js +0 -78
  237. package/dist/targets/node/axios/fixtures/application-form-encoded.d.ts +0 -1
  238. package/dist/targets/node/axios/fixtures/application-form-encoded.js +0 -20
  239. package/dist/targets/node/axios/fixtures/application-json.d.ts +0 -1
  240. package/dist/targets/node/axios/fixtures/application-json.js +0 -23
  241. package/dist/targets/node/axios/fixtures/cookies.d.ts +0 -1
  242. package/dist/targets/node/axios/fixtures/cookies.js +0 -15
  243. package/dist/targets/node/axios/fixtures/custom-method.d.ts +0 -1
  244. package/dist/targets/node/axios/fixtures/custom-method.js +0 -11
  245. package/dist/targets/node/axios/fixtures/full.d.ts +0 -1
  246. package/dist/targets/node/axios/fixtures/full.js +0 -23
  247. package/dist/targets/node/axios/fixtures/headers.d.ts +0 -1
  248. package/dist/targets/node/axios/fixtures/headers.js +0 -20
  249. package/dist/targets/node/axios/fixtures/http-insecure.d.ts +0 -1
  250. package/dist/targets/node/axios/fixtures/http-insecure.js +0 -11
  251. package/dist/targets/node/axios/fixtures/jsonObj-multiline.d.ts +0 -1
  252. package/dist/targets/node/axios/fixtures/jsonObj-multiline.js +0 -16
  253. package/dist/targets/node/axios/fixtures/jsonObj-null-value.d.ts +0 -1
  254. package/dist/targets/node/axios/fixtures/jsonObj-null-value.js +0 -16
  255. package/dist/targets/node/axios/fixtures/multipart-data.d.ts +0 -1
  256. package/dist/targets/node/axios/fixtures/multipart-data.js +0 -16
  257. package/dist/targets/node/axios/fixtures/multipart-file.d.ts +0 -1
  258. package/dist/targets/node/axios/fixtures/multipart-file.js +0 -16
  259. package/dist/targets/node/axios/fixtures/multipart-form-data-no-params.d.ts +0 -1
  260. package/dist/targets/node/axios/fixtures/multipart-form-data-no-params.js +0 -15
  261. package/dist/targets/node/axios/fixtures/multipart-form-data.d.ts +0 -1
  262. package/dist/targets/node/axios/fixtures/multipart-form-data.js +0 -16
  263. package/dist/targets/node/axios/fixtures/nested.d.ts +0 -1
  264. package/dist/targets/node/axios/fixtures/nested.js +0 -14
  265. package/dist/targets/node/axios/fixtures/postdata-malformed.d.ts +0 -1
  266. package/dist/targets/node/axios/fixtures/postdata-malformed.js +0 -15
  267. package/dist/targets/node/axios/fixtures/query-encoded.d.ts +0 -1
  268. package/dist/targets/node/axios/fixtures/query-encoded.js +0 -14
  269. package/dist/targets/node/axios/fixtures/query.d.ts +0 -1
  270. package/dist/targets/node/axios/fixtures/query.js +0 -14
  271. package/dist/targets/node/axios/fixtures/short.d.ts +0 -1
  272. package/dist/targets/node/axios/fixtures/short.js +0 -11
  273. package/dist/targets/node/axios/fixtures/text-plain.d.ts +0 -1
  274. package/dist/targets/node/axios/fixtures/text-plain.js +0 -16
  275. package/dist/targets/node/fetch/client.d.ts +0 -11
  276. package/dist/targets/node/fetch/client.js +0 -140
  277. package/dist/targets/node/fetch/fixtures/application-form-encoded.d.ts +0 -1
  278. package/dist/targets/node/fetch/fixtures/application-form-encoded.js +0 -16
  279. package/dist/targets/node/fetch/fixtures/application-json.d.ts +0 -1
  280. package/dist/targets/node/fetch/fixtures/application-json.js +0 -19
  281. package/dist/targets/node/fetch/fixtures/cookies.d.ts +0 -1
  282. package/dist/targets/node/fetch/fixtures/cookies.js +0 -8
  283. package/dist/targets/node/fetch/fixtures/custom-method.d.ts +0 -1
  284. package/dist/targets/node/fetch/fixtures/custom-method.js +0 -8
  285. package/dist/targets/node/fetch/fixtures/full.d.ts +0 -1
  286. package/dist/targets/node/fetch/fixtures/full.js +0 -19
  287. package/dist/targets/node/fetch/fixtures/headers.d.ts +0 -1
  288. package/dist/targets/node/fetch/fixtures/headers.js +0 -16
  289. package/dist/targets/node/fetch/fixtures/http-insecure.d.ts +0 -1
  290. package/dist/targets/node/fetch/fixtures/http-insecure.js +0 -8
  291. package/dist/targets/node/fetch/fixtures/jsonObj-multiline.d.ts +0 -1
  292. package/dist/targets/node/fetch/fixtures/jsonObj-multiline.js +0 -12
  293. package/dist/targets/node/fetch/fixtures/jsonObj-null-value.d.ts +0 -1
  294. package/dist/targets/node/fetch/fixtures/jsonObj-null-value.js +0 -12
  295. package/dist/targets/node/fetch/fixtures/multipart-data.d.ts +0 -1
  296. package/dist/targets/node/fetch/fixtures/multipart-data.js +0 -14
  297. package/dist/targets/node/fetch/fixtures/multipart-file.d.ts +0 -1
  298. package/dist/targets/node/fetch/fixtures/multipart-file.js +0 -13
  299. package/dist/targets/node/fetch/fixtures/multipart-form-data-no-params.d.ts +0 -1
  300. package/dist/targets/node/fetch/fixtures/multipart-form-data-no-params.js +0 -8
  301. package/dist/targets/node/fetch/fixtures/multipart-form-data.d.ts +0 -1
  302. package/dist/targets/node/fetch/fixtures/multipart-form-data.js +0 -12
  303. package/dist/targets/node/fetch/fixtures/nested.d.ts +0 -1
  304. package/dist/targets/node/fetch/fixtures/nested.js +0 -8
  305. package/dist/targets/node/fetch/fixtures/postdata-malformed.d.ts +0 -1
  306. package/dist/targets/node/fetch/fixtures/postdata-malformed.js +0 -8
  307. package/dist/targets/node/fetch/fixtures/query-encoded.d.ts +0 -1
  308. package/dist/targets/node/fetch/fixtures/query-encoded.js +0 -8
  309. package/dist/targets/node/fetch/fixtures/query.d.ts +0 -1
  310. package/dist/targets/node/fetch/fixtures/query.js +0 -8
  311. package/dist/targets/node/fetch/fixtures/short.d.ts +0 -1
  312. package/dist/targets/node/fetch/fixtures/short.js +0 -8
  313. package/dist/targets/node/fetch/fixtures/text-plain.d.ts +0 -1
  314. package/dist/targets/node/fetch/fixtures/text-plain.js +0 -8
  315. package/dist/targets/node/native/client.d.ts +0 -11
  316. package/dist/targets/node/native/client.js +0 -72
  317. package/dist/targets/node/native/fixtures/application-form-encoded.d.ts +0 -1
  318. package/dist/targets/node/native/fixtures/application-form-encoded.js +0 -24
  319. package/dist/targets/node/native/fixtures/application-json.d.ts +0 -1
  320. package/dist/targets/node/native/fixtures/application-json.js +0 -30
  321. package/dist/targets/node/native/fixtures/cookies.d.ts +0 -1
  322. package/dist/targets/node/native/fixtures/cookies.js +0 -22
  323. package/dist/targets/node/native/fixtures/custom-method.d.ts +0 -1
  324. package/dist/targets/node/native/fixtures/custom-method.js +0 -20
  325. package/dist/targets/node/native/fixtures/full.d.ts +0 -1
  326. package/dist/targets/node/native/fixtures/full.js +0 -26
  327. package/dist/targets/node/native/fixtures/headers.d.ts +0 -1
  328. package/dist/targets/node/native/fixtures/headers.js +0 -25
  329. package/dist/targets/node/native/fixtures/http-insecure.d.ts +0 -1
  330. package/dist/targets/node/native/fixtures/http-insecure.js +0 -20
  331. package/dist/targets/node/native/fixtures/jsonObj-multiline.d.ts +0 -1
  332. package/dist/targets/node/native/fixtures/jsonObj-multiline.js +0 -23
  333. package/dist/targets/node/native/fixtures/jsonObj-null-value.d.ts +0 -1
  334. package/dist/targets/node/native/fixtures/jsonObj-null-value.js +0 -23
  335. package/dist/targets/node/native/fixtures/multipart-data.d.ts +0 -1
  336. package/dist/targets/node/native/fixtures/multipart-data.js +0 -23
  337. package/dist/targets/node/native/fixtures/multipart-file.d.ts +0 -1
  338. package/dist/targets/node/native/fixtures/multipart-file.js +0 -23
  339. package/dist/targets/node/native/fixtures/multipart-form-data-no-params.d.ts +0 -1
  340. package/dist/targets/node/native/fixtures/multipart-form-data-no-params.js +0 -22
  341. package/dist/targets/node/native/fixtures/multipart-form-data.d.ts +0 -1
  342. package/dist/targets/node/native/fixtures/multipart-form-data.js +0 -23
  343. package/dist/targets/node/native/fixtures/nested.d.ts +0 -1
  344. package/dist/targets/node/native/fixtures/nested.js +0 -20
  345. package/dist/targets/node/native/fixtures/postdata-malformed.d.ts +0 -1
  346. package/dist/targets/node/native/fixtures/postdata-malformed.js +0 -22
  347. package/dist/targets/node/native/fixtures/query-encoded.d.ts +0 -1
  348. package/dist/targets/node/native/fixtures/query-encoded.js +0 -20
  349. package/dist/targets/node/native/fixtures/query.d.ts +0 -1
  350. package/dist/targets/node/native/fixtures/query.js +0 -20
  351. package/dist/targets/node/native/fixtures/short.d.ts +0 -1
  352. package/dist/targets/node/native/fixtures/short.js +0 -20
  353. package/dist/targets/node/native/fixtures/text-plain.d.ts +0 -1
  354. package/dist/targets/node/native/fixtures/text-plain.js +0 -23
  355. package/dist/targets/node/request/client.d.ts +0 -11
  356. package/dist/targets/node/request/client.js +0 -107
  357. package/dist/targets/node/request/fixtures/application-form-encoded.d.ts +0 -1
  358. package/dist/targets/node/request/fixtures/application-form-encoded.js +0 -13
  359. package/dist/targets/node/request/fixtures/application-json.d.ts +0 -1
  360. package/dist/targets/node/request/fixtures/application-json.js +0 -21
  361. package/dist/targets/node/request/fixtures/cookies.d.ts +0 -1
  362. package/dist/targets/node/request/fixtures/cookies.js +0 -11
  363. package/dist/targets/node/request/fixtures/custom-method.d.ts +0 -1
  364. package/dist/targets/node/request/fixtures/custom-method.js +0 -8
  365. package/dist/targets/node/request/fixtures/full.d.ts +0 -1
  366. package/dist/targets/node/request/fixtures/full.js +0 -20
  367. package/dist/targets/node/request/fixtures/headers.d.ts +0 -1
  368. package/dist/targets/node/request/fixtures/headers.js +0 -17
  369. package/dist/targets/node/request/fixtures/http-insecure.d.ts +0 -1
  370. package/dist/targets/node/request/fixtures/http-insecure.js +0 -8
  371. package/dist/targets/node/request/fixtures/jsonObj-multiline.d.ts +0 -1
  372. package/dist/targets/node/request/fixtures/jsonObj-multiline.js +0 -14
  373. package/dist/targets/node/request/fixtures/jsonObj-null-value.d.ts +0 -1
  374. package/dist/targets/node/request/fixtures/jsonObj-null-value.js +0 -14
  375. package/dist/targets/node/request/fixtures/multipart-data.d.ts +0 -1
  376. package/dist/targets/node/request/fixtures/multipart-data.js +0 -20
  377. package/dist/targets/node/request/fixtures/multipart-file.d.ts +0 -1
  378. package/dist/targets/node/request/fixtures/multipart-file.js +0 -19
  379. package/dist/targets/node/request/fixtures/multipart-form-data-no-params.d.ts +0 -1
  380. package/dist/targets/node/request/fixtures/multipart-form-data-no-params.js +0 -12
  381. package/dist/targets/node/request/fixtures/multipart-form-data.d.ts +0 -1
  382. package/dist/targets/node/request/fixtures/multipart-form-data.js +0 -13
  383. package/dist/targets/node/request/fixtures/nested.d.ts +0 -1
  384. package/dist/targets/node/request/fixtures/nested.js +0 -11
  385. package/dist/targets/node/request/fixtures/postdata-malformed.d.ts +0 -1
  386. package/dist/targets/node/request/fixtures/postdata-malformed.js +0 -12
  387. package/dist/targets/node/request/fixtures/query-encoded.d.ts +0 -1
  388. package/dist/targets/node/request/fixtures/query-encoded.js +0 -11
  389. package/dist/targets/node/request/fixtures/query.d.ts +0 -1
  390. package/dist/targets/node/request/fixtures/query.js +0 -11
  391. package/dist/targets/node/request/fixtures/short.d.ts +0 -1
  392. package/dist/targets/node/request/fixtures/short.js +0 -8
  393. package/dist/targets/node/request/fixtures/text-plain.d.ts +0 -1
  394. package/dist/targets/node/request/fixtures/text-plain.js +0 -13
  395. package/dist/targets/node/target.d.ts +0 -2
  396. package/dist/targets/node/target.js +0 -24
  397. package/dist/targets/node/unirest/client.d.ts +0 -11
  398. package/dist/targets/node/unirest/client.js +0 -110
  399. package/dist/targets/node/unirest/fixtures/application-form-encoded.d.ts +0 -1
  400. package/dist/targets/node/unirest/fixtures/application-form-encoded.js +0 -15
  401. package/dist/targets/node/unirest/fixtures/application-json.d.ts +0 -1
  402. package/dist/targets/node/unirest/fixtures/application-json.js +0 -32
  403. package/dist/targets/node/unirest/fixtures/cookies.d.ts +0 -1
  404. package/dist/targets/node/unirest/fixtures/cookies.js +0 -12
  405. package/dist/targets/node/unirest/fixtures/custom-method.d.ts +0 -1
  406. package/dist/targets/node/unirest/fixtures/custom-method.js +0 -8
  407. package/dist/targets/node/unirest/fixtures/full.d.ts +0 -1
  408. package/dist/targets/node/unirest/fixtures/full.js +0 -27
  409. package/dist/targets/node/unirest/fixtures/headers.d.ts +0 -1
  410. package/dist/targets/node/unirest/fixtures/headers.js +0 -14
  411. package/dist/targets/node/unirest/fixtures/http-insecure.d.ts +0 -1
  412. package/dist/targets/node/unirest/fixtures/http-insecure.js +0 -8
  413. package/dist/targets/node/unirest/fixtures/jsonObj-multiline.d.ts +0 -1
  414. package/dist/targets/node/unirest/fixtures/jsonObj-multiline.js +0 -15
  415. package/dist/targets/node/unirest/fixtures/jsonObj-null-value.d.ts +0 -1
  416. package/dist/targets/node/unirest/fixtures/jsonObj-null-value.js +0 -15
  417. package/dist/targets/node/unirest/fixtures/multipart-data.d.ts +0 -1
  418. package/dist/targets/node/unirest/fixtures/multipart-data.js +0 -20
  419. package/dist/targets/node/unirest/fixtures/multipart-file.d.ts +0 -1
  420. package/dist/targets/node/unirest/fixtures/multipart-file.js +0 -18
  421. package/dist/targets/node/unirest/fixtures/multipart-form-data-no-params.d.ts +0 -1
  422. package/dist/targets/node/unirest/fixtures/multipart-form-data-no-params.js +0 -11
  423. package/dist/targets/node/unirest/fixtures/multipart-form-data.d.ts +0 -1
  424. package/dist/targets/node/unirest/fixtures/multipart-form-data.js +0 -16
  425. package/dist/targets/node/unirest/fixtures/nested.d.ts +0 -1
  426. package/dist/targets/node/unirest/fixtures/nested.js +0 -13
  427. package/dist/targets/node/unirest/fixtures/postdata-malformed.d.ts +0 -1
  428. package/dist/targets/node/unirest/fixtures/postdata-malformed.js +0 -11
  429. package/dist/targets/node/unirest/fixtures/query-encoded.d.ts +0 -1
  430. package/dist/targets/node/unirest/fixtures/query-encoded.js +0 -12
  431. package/dist/targets/node/unirest/fixtures/query.d.ts +0 -1
  432. package/dist/targets/node/unirest/fixtures/query.js +0 -16
  433. package/dist/targets/node/unirest/fixtures/short.d.ts +0 -1
  434. package/dist/targets/node/unirest/fixtures/short.js +0 -8
  435. package/dist/targets/node/unirest/fixtures/text-plain.d.ts +0 -1
  436. package/dist/targets/node/unirest/fixtures/text-plain.js +0 -12
  437. package/dist/targets/objc/helpers.d.ts +0 -26
  438. package/dist/targets/objc/helpers.js +0 -59
  439. package/dist/targets/objc/nsurlsession/client.d.ts +0 -15
  440. package/dist/targets/objc/nsurlsession/client.js +0 -143
  441. package/dist/targets/objc/target.d.ts +0 -2
  442. package/dist/targets/objc/target.js +0 -15
  443. package/dist/targets/ocaml/cohttp/client.d.ts +0 -11
  444. package/dist/targets/ocaml/cohttp/client.js +0 -64
  445. package/dist/targets/ocaml/target.d.ts +0 -2
  446. package/dist/targets/ocaml/target.js +0 -15
  447. package/dist/targets/php/curl/client.d.ts +0 -19
  448. package/dist/targets/php/curl/client.js +0 -122
  449. package/dist/targets/php/guzzle/client.d.ts +0 -17
  450. package/dist/targets/php/guzzle/client.js +0 -119
  451. package/dist/targets/php/helpers.d.ts +0 -2
  452. package/dist/targets/php/helpers.js +0 -66
  453. package/dist/targets/php/http1/client.d.ts +0 -16
  454. package/dist/targets/php/http1/client.js +0 -76
  455. package/dist/targets/php/http2/client.d.ts +0 -16
  456. package/dist/targets/php/http2/client.js +0 -115
  457. package/dist/targets/php/target.d.ts +0 -2
  458. package/dist/targets/php/target.js +0 -22
  459. package/dist/targets/powershell/common.d.ts +0 -3
  460. package/dist/targets/powershell/common.js +0 -50
  461. package/dist/targets/powershell/restmethod/client.d.ts +0 -2
  462. package/dist/targets/powershell/restmethod/client.js +0 -13
  463. package/dist/targets/powershell/target.d.ts +0 -2
  464. package/dist/targets/powershell/target.js +0 -17
  465. package/dist/targets/powershell/webrequest/client.d.ts +0 -2
  466. package/dist/targets/powershell/webrequest/client.js +0 -13
  467. package/dist/targets/python/helpers.d.ts +0 -8
  468. package/dist/targets/python/helpers.js +0 -64
  469. package/dist/targets/python/requests/client.d.ts +0 -14
  470. package/dist/targets/python/requests/client.js +0 -162
  471. package/dist/targets/python/target.d.ts +0 -2
  472. package/dist/targets/python/target.js +0 -16
  473. package/dist/targets/r/httr/client.d.ts +0 -11
  474. package/dist/targets/r/httr/client.js +0 -130
  475. package/dist/targets/r/target.d.ts +0 -2
  476. package/dist/targets/r/target.js +0 -15
  477. package/dist/targets/ruby/native/client.d.ts +0 -2
  478. package/dist/targets/ruby/native/client.js +0 -67
  479. package/dist/targets/ruby/target.d.ts +0 -2
  480. package/dist/targets/ruby/target.js +0 -15
  481. package/dist/targets/shell/curl/client.d.ts +0 -19
  482. package/dist/targets/shell/curl/client.js +0 -166
  483. package/dist/targets/shell/httpie/client.d.ts +0 -24
  484. package/dist/targets/shell/httpie/client.js +0 -102
  485. package/dist/targets/shell/target.d.ts +0 -2
  486. package/dist/targets/shell/target.js +0 -20
  487. package/dist/targets/shell/wget/client.d.ts +0 -16
  488. package/dist/targets/shell/wget/client.js +0 -46
  489. package/dist/targets/swift/helpers.d.ts +0 -16
  490. package/dist/targets/swift/helpers.js +0 -80
  491. package/dist/targets/swift/nsurlsession/client.d.ts +0 -15
  492. package/dist/targets/swift/nsurlsession/client.js +0 -148
  493. package/dist/targets/swift/target.d.ts +0 -2
  494. package/dist/targets/swift/target.js +0 -15
package/dist/index.js CHANGED
@@ -1,275 +1,3791 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __values = (this && this.__values) || function(o) {
14
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
15
- if (m) return m.call(o);
16
- if (o && typeof o.length === "number") return {
17
- next: function () {
18
- if (o && i >= o.length) o = void 0;
19
- return { value: o && o[i++], done: !o };
20
- }
21
- };
22
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
23
- };
24
- var __importDefault = (this && this.__importDefault) || function (mod) {
25
- return (mod && mod.__esModule) ? mod : { "default": mod };
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.HTTPSnippet = exports.addTargetClient = exports.addTarget = exports.extname = exports.availableTargets = void 0;
29
- // eslint-disable-next-line node/no-deprecated-api
30
- var url_1 = require("url");
31
- var event_stream_1 = require("event-stream");
32
- var form_data_1 = __importDefault(require("form-data"));
33
- var qs_1 = require("qs");
34
- var form_data_2 = require("./helpers/form-data");
35
- var headers_1 = require("./helpers/headers");
36
- var reducer_1 = require("./helpers/reducer");
37
- var targets_1 = require("./targets/targets");
38
- var utils_1 = require("./helpers/utils");
39
- Object.defineProperty(exports, "availableTargets", { enumerable: true, get: function () { return utils_1.availableTargets; } });
40
- Object.defineProperty(exports, "extname", { enumerable: true, get: function () { return utils_1.extname; } });
41
- var targets_2 = require("./targets/targets");
42
- Object.defineProperty(exports, "addTarget", { enumerable: true, get: function () { return targets_2.addTarget; } });
43
- Object.defineProperty(exports, "addTargetClient", { enumerable: true, get: function () { return targets_2.addTargetClient; } });
44
- var DEBUG_MODE = false;
45
- var debug = {
46
- // eslint-disable-next-line @typescript-eslint/no-empty-function, no-console
47
- info: DEBUG_MODE ? console.info : function () { },
48
- };
49
- var isHarEntry = function (value) {
50
- return typeof value === 'object' &&
51
- 'log' in value &&
52
- typeof value.log === 'object' &&
53
- 'entries' in value.log &&
54
- Array.isArray(value.log.entries);
55
- };
56
- var HTTPSnippet = /** @class */ (function () {
57
- function HTTPSnippet(input, opts) {
58
- if (opts === void 0) { opts = {}; }
59
- var _this = this;
60
- this.requests = [];
61
- this.prepare = function (harRequest, options) {
62
- var e_1, _a;
63
- var _b, _c, _d;
64
- var request = __assign(__assign({}, harRequest), { fullUrl: '', uriObj: {}, queryObj: {}, headersObj: {}, cookiesObj: {}, allHeaders: {} });
65
- // construct query objects
66
- if (request.queryString && request.queryString.length) {
67
- debug.info('queryString found, constructing queryString pair map');
68
- request.queryObj = request.queryString.reduce(reducer_1.reducer, {});
1
+ 'use strict';
2
+
3
+ var url = require('url');
4
+ var eventStream = require('event-stream');
5
+ var FormData = require('form-data');
6
+ var qs = require('qs');
7
+ var stringifyObject9 = require('stringify-object');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var FormData__default = /*#__PURE__*/_interopDefault(FormData);
12
+ var stringifyObject9__default = /*#__PURE__*/_interopDefault(stringifyObject9);
13
+
14
+ // src/index.ts
15
+
16
+ // src/helpers/form-data.ts
17
+ var carriage = "\r\n";
18
+ var dashes = "-".repeat(2);
19
+ var NAME = Symbol.toStringTag;
20
+ var isBlob = (object) => typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
21
+ var getFooter = (boundary) => `${dashes}${boundary}${dashes}${carriage.repeat(2)}`;
22
+ var getHeader = (boundary, name, field) => {
23
+ let header = "";
24
+ header += `${dashes}${boundary}${carriage}`;
25
+ header += `Content-Disposition: form-data; name="${name}"`;
26
+ if (isBlob(field)) {
27
+ header += `; filename="${field.name}"${carriage}`;
28
+ header += `Content-Type: ${field.type || "application/octet-stream"}`;
29
+ }
30
+ return `${header}${carriage.repeat(2)}`;
31
+ };
32
+ var formDataIterator = function* (form, boundary) {
33
+ for (const [name, value] of form) {
34
+ yield getHeader(boundary, name, value);
35
+ if (isBlob(value)) {
36
+ yield* value.stream();
37
+ } else {
38
+ yield value;
39
+ }
40
+ yield carriage;
41
+ }
42
+ yield getFooter(boundary);
43
+ };
44
+
45
+ // src/helpers/headers.ts
46
+ var getHeaderName = (headers, name) => Object.keys(headers).find((header) => header.toLowerCase() === name.toLowerCase());
47
+ var getHeader2 = (headers, name) => {
48
+ const headerName = getHeaderName(headers, name);
49
+ if (!headerName) {
50
+ return void 0;
51
+ }
52
+ return headers[headerName];
53
+ };
54
+ var hasHeader = (headers, name) => Boolean(getHeaderName(headers, name));
55
+ var isMimeTypeJSON = (mimeType) => ["application/json", "application/x-json", "text/json", "text/x-json", "+json"].some(
56
+ (type) => mimeType.indexOf(type) > -1
57
+ );
58
+
59
+ // src/helpers/reducer.ts
60
+ var reducer = (accumulator, pair) => {
61
+ const currentValue = accumulator[pair.name];
62
+ if (currentValue === void 0) {
63
+ accumulator[pair.name] = pair.value;
64
+ return accumulator;
65
+ }
66
+ if (Array.isArray(currentValue)) {
67
+ currentValue.push(pair.value);
68
+ return accumulator;
69
+ }
70
+ accumulator[pair.name] = [currentValue, pair.value];
71
+ return accumulator;
72
+ };
73
+
74
+ // src/helpers/code-builder.ts
75
+ var DEFAULT_INDENTATION_CHARACTER = "";
76
+ var DEFAULT_LINE_JOIN = "\n";
77
+ var CodeBuilder = class {
78
+ /**
79
+ * Helper object to format and aggragate lines of code.
80
+ * Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet.
81
+ */
82
+ constructor({ indent, join } = {}) {
83
+ this.postProcessors = [];
84
+ this.code = [];
85
+ this.indentationCharacter = DEFAULT_INDENTATION_CHARACTER;
86
+ this.lineJoin = DEFAULT_LINE_JOIN;
87
+ /**
88
+ * Add given indentation level to given line of code
89
+ */
90
+ this.indentLine = (line, indentationLevel = 0) => {
91
+ const indent = this.indentationCharacter.repeat(indentationLevel);
92
+ return `${indent}${line}`;
93
+ };
94
+ /**
95
+ * Add the line at the beginning of the current lines
96
+ */
97
+ this.unshift = (line, indentationLevel) => {
98
+ const newLine = this.indentLine(line, indentationLevel);
99
+ this.code.unshift(newLine);
100
+ };
101
+ /**
102
+ * Add the line at the end of the current lines
103
+ */
104
+ this.push = (line, indentationLevel) => {
105
+ const newLine = this.indentLine(line, indentationLevel);
106
+ this.code.push(newLine);
107
+ };
108
+ /**
109
+ * Add an empty line at the end of current lines
110
+ */
111
+ this.blank = () => {
112
+ this.code.push("");
113
+ };
114
+ /**
115
+ * Concatenate all current lines using the given lineJoin, then apply any replacers that may have been added
116
+ */
117
+ this.join = () => {
118
+ const unreplacedCode = this.code.join(this.lineJoin);
119
+ const replacedOutput = this.postProcessors.reduce((accumulator, replacer) => replacer(accumulator), unreplacedCode);
120
+ return replacedOutput;
121
+ };
122
+ /**
123
+ * Often when writing modules you may wish to add a literal tag or bit of metadata that you wish to transform after other processing as a final step.
124
+ * To do so, you can provide a PostProcessor function and it will be run automatically for you when you call `join()` later on.
125
+ */
126
+ this.addPostProcessor = (postProcessor) => {
127
+ this.postProcessors = [...this.postProcessors, postProcessor];
128
+ };
129
+ this.indentationCharacter = indent || DEFAULT_INDENTATION_CHARACTER;
130
+ this.lineJoin = join ?? DEFAULT_LINE_JOIN;
131
+ }
132
+ };
133
+
134
+ // src/helpers/escape.ts
135
+ function escapeString(rawValue, options = {}) {
136
+ const { delimiter = '"', escapeChar = "\\", escapeNewlines = true } = options;
137
+ const stringValue = rawValue.toString();
138
+ return [...stringValue].map((c2) => {
139
+ if (c2 === "\b") {
140
+ return `${escapeChar}b`;
141
+ } else if (c2 === " ") {
142
+ return `${escapeChar}t`;
143
+ } else if (c2 === "\n") {
144
+ if (escapeNewlines) {
145
+ return `${escapeChar}n`;
146
+ }
147
+ return c2;
148
+ } else if (c2 === "\f") {
149
+ return `${escapeChar}f`;
150
+ } else if (c2 === "\r") {
151
+ if (escapeNewlines) {
152
+ return `${escapeChar}r`;
153
+ }
154
+ return c2;
155
+ } else if (c2 === escapeChar) {
156
+ return escapeChar + escapeChar;
157
+ } else if (c2 === delimiter) {
158
+ return escapeChar + delimiter;
159
+ } else if (c2 < " " || c2 > "~") {
160
+ return JSON.stringify(c2).slice(1, -1);
161
+ }
162
+ return c2;
163
+ }).join("");
164
+ }
165
+ var escapeForSingleQuotes = (value) => escapeString(value, { delimiter: "'" });
166
+ var escapeForDoubleQuotes = (value) => escapeString(value, { delimiter: '"' });
167
+
168
+ // src/targets/c/libcurl/client.ts
169
+ var libcurl = {
170
+ info: {
171
+ key: "libcurl",
172
+ title: "Libcurl",
173
+ link: "http://curl.haxx.se/libcurl",
174
+ description: "Simple REST and HTTP API Client for C"
175
+ },
176
+ convert: ({ method, fullUrl, headersObj, allHeaders, postData }) => {
177
+ const { push, blank, join } = new CodeBuilder();
178
+ push("CURL *hnd = curl_easy_init();");
179
+ blank();
180
+ push(`curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method.toUpperCase()}");`);
181
+ push("curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout);");
182
+ push(`curl_easy_setopt(hnd, CURLOPT_URL, "${fullUrl}");`);
183
+ const headers = Object.keys(headersObj);
184
+ if (headers.length) {
185
+ blank();
186
+ push("struct curl_slist *headers = NULL;");
187
+ headers.forEach((header) => {
188
+ push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`);
189
+ });
190
+ push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);");
191
+ }
192
+ if (allHeaders.cookie) {
193
+ blank();
194
+ push(`curl_easy_setopt(hnd, CURLOPT_COOKIE, "${allHeaders.cookie}");`);
195
+ }
196
+ if (postData.text) {
197
+ blank();
198
+ push(`curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${JSON.stringify(postData.text)});`);
199
+ }
200
+ blank();
201
+ push("CURLcode ret = curl_easy_perform(hnd);");
202
+ return join();
203
+ }
204
+ };
205
+
206
+ // src/targets/c/target.ts
207
+ var c = {
208
+ info: {
209
+ key: "c",
210
+ title: "C",
211
+ extname: ".c",
212
+ default: "libcurl",
213
+ cli: "c"
214
+ },
215
+ clientsById: {
216
+ libcurl
217
+ }
218
+ };
219
+
220
+ // src/targets/clojure/clj_http/client.ts
221
+ var Keyword = class {
222
+ constructor(name) {
223
+ this.name = "";
224
+ this.toString = () => `:${this.name}`;
225
+ this.name = name;
226
+ }
227
+ };
228
+ var File = class {
229
+ constructor(path) {
230
+ this.path = "";
231
+ this.toString = () => `(clojure.java.io/file "${this.path}")`;
232
+ this.path = path;
233
+ }
234
+ };
235
+ var jsType = (input) => {
236
+ if (input === void 0) {
237
+ return null;
238
+ }
239
+ if (input === null) {
240
+ return "null";
241
+ }
242
+ return input.constructor.name.toLowerCase();
243
+ };
244
+ var objEmpty = (input) => {
245
+ if (input === void 0) {
246
+ return true;
247
+ } else if (jsType(input) === "object") {
248
+ return Object.keys(input).length === 0;
249
+ }
250
+ return false;
251
+ };
252
+ var filterEmpty = (input) => {
253
+ Object.keys(input).filter((x) => objEmpty(input[x])).forEach((x) => {
254
+ delete input[x];
255
+ });
256
+ return input;
257
+ };
258
+ var padBlock = (padSize, input) => {
259
+ const padding = " ".repeat(padSize);
260
+ return input.replace(/\n/g, `
261
+ ${padding}`);
262
+ };
263
+ var jsToEdn = (js) => {
264
+ switch (jsType(js)) {
265
+ case "string":
266
+ return `"${js.replace(/"/g, '\\"')}"`;
267
+ case "file":
268
+ return js.toString();
269
+ case "keyword":
270
+ return js.toString();
271
+ case "null":
272
+ return "nil";
273
+ case "regexp":
274
+ return `#"${js.source}"`;
275
+ case "object": {
276
+ const obj = Object.keys(js).reduce((accumulator, key) => {
277
+ const val = padBlock(key.length + 2, jsToEdn(js[key]));
278
+ return `${accumulator}:${key} ${val}
279
+ `;
280
+ }, "").trim();
281
+ return `{${padBlock(1, obj)}}`;
282
+ }
283
+ case "array": {
284
+ const arr = js.reduce((accumulator, value) => `${accumulator} ${jsToEdn(value)}`, "").trim();
285
+ return `[${padBlock(1, arr)}]`;
286
+ }
287
+ default:
288
+ return js.toString();
289
+ }
290
+ };
291
+ var clj_http = {
292
+ info: {
293
+ key: "clj_http",
294
+ title: "clj-http",
295
+ link: "https://github.com/dakrone/clj-http",
296
+ description: "An idiomatic clojure http client wrapping the apache client."
297
+ },
298
+ convert: ({ queryObj, method, postData, url, allHeaders }, options) => {
299
+ const { push, join } = new CodeBuilder({ indent: options?.indent });
300
+ const methods = ["get", "post", "put", "delete", "patch", "head", "options"];
301
+ method = method.toLowerCase();
302
+ if (!methods.includes(method)) {
303
+ push("Method not supported");
304
+ return join();
305
+ }
306
+ const params2 = {
307
+ headers: allHeaders,
308
+ "query-params": queryObj
309
+ };
310
+ switch (postData.mimeType) {
311
+ case "application/json":
312
+ {
313
+ params2["content-type"] = new Keyword("json");
314
+ params2["form-params"] = postData.jsonObj;
315
+ const header = getHeaderName(params2.headers, "content-type");
316
+ if (header) {
317
+ delete params2.headers[header];
318
+ }
319
+ }
320
+ break;
321
+ case "application/x-www-form-urlencoded":
322
+ {
323
+ params2["form-params"] = postData.paramsObj;
324
+ const header = getHeaderName(params2.headers, "content-type");
325
+ if (header) {
326
+ delete params2.headers[header];
327
+ }
328
+ }
329
+ break;
330
+ case "text/plain":
331
+ {
332
+ params2.body = postData.text;
333
+ const header = getHeaderName(params2.headers, "content-type");
334
+ if (header) {
335
+ delete params2.headers[header];
336
+ }
337
+ }
338
+ break;
339
+ case "multipart/form-data": {
340
+ if (postData.params) {
341
+ params2.multipart = postData.params.map((param) => {
342
+ if (param.fileName && !param.value) {
343
+ return {
344
+ name: param.name,
345
+ content: new File(param.fileName)
346
+ };
69
347
  }
70
- // construct headers objects
71
- if (request.headers && request.headers.length) {
72
- var http2VersionRegex_1 = /^HTTP\/2/;
73
- request.headersObj = request.headers.reduce(function (accumulator, _a) {
74
- var _b;
75
- var name = _a.name, value = _a.value;
76
- var headerName = http2VersionRegex_1.exec(request.httpVersion) ? name.toLocaleLowerCase() : name;
77
- return __assign(__assign({}, accumulator), (_b = {}, _b[headerName] = value, _b));
78
- }, {});
348
+ return {
349
+ name: param.name,
350
+ content: param.value
351
+ };
352
+ });
353
+ const header = getHeaderName(params2.headers, "content-type");
354
+ if (header) {
355
+ delete params2.headers[header];
356
+ }
357
+ }
358
+ break;
359
+ }
360
+ }
361
+ switch (getHeader2(params2.headers, "accept")) {
362
+ case "application/json":
363
+ {
364
+ params2.accept = new Keyword("json");
365
+ const header = getHeaderName(params2.headers, "accept");
366
+ if (header) {
367
+ delete params2.headers[header];
368
+ }
369
+ }
370
+ break;
371
+ }
372
+ push("(require '[clj-http.client :as client])\n");
373
+ if (objEmpty(filterEmpty(params2))) {
374
+ push(`(client/${method} "${url}")`);
375
+ } else {
376
+ const padding = 11 + method.length + url.length;
377
+ const formattedParams = padBlock(padding, jsToEdn(filterEmpty(params2)));
378
+ push(`(client/${method} "${url}" ${formattedParams})`);
379
+ }
380
+ return join();
381
+ }
382
+ };
383
+
384
+ // src/targets/clojure/target.ts
385
+ var clojure = {
386
+ info: {
387
+ key: "clojure",
388
+ title: "Clojure",
389
+ extname: ".clj",
390
+ default: "clj_http"
391
+ },
392
+ clientsById: {
393
+ clj_http
394
+ }
395
+ };
396
+
397
+ // src/targets/csharp/httpclient/client.ts
398
+ var getDecompressionMethods = (allHeaders) => {
399
+ let acceptEncodings = getHeader2(allHeaders, "accept-encoding");
400
+ if (!acceptEncodings) {
401
+ return [];
402
+ }
403
+ const supportedMethods2 = {
404
+ gzip: "DecompressionMethods.GZip",
405
+ deflate: "DecompressionMethods.Deflate"
406
+ };
407
+ const methods = [];
408
+ if (typeof acceptEncodings === "string") {
409
+ acceptEncodings = [acceptEncodings];
410
+ }
411
+ acceptEncodings.forEach((acceptEncoding) => {
412
+ acceptEncoding.split(",").forEach((encoding) => {
413
+ const match = /\s*([^;\s]+)/.exec(encoding);
414
+ if (match) {
415
+ const method = supportedMethods2[match[1]];
416
+ if (method) {
417
+ methods.push(method);
418
+ }
419
+ }
420
+ });
421
+ });
422
+ return methods;
423
+ };
424
+ var httpclient = {
425
+ info: {
426
+ key: "httpclient",
427
+ title: "HttpClient",
428
+ link: "https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",
429
+ description: ".NET Standard HTTP Client"
430
+ },
431
+ convert: ({ allHeaders, postData, method, fullUrl }, options) => {
432
+ const opts = {
433
+ indent: " ",
434
+ ...options
435
+ };
436
+ const { push, join } = new CodeBuilder({ indent: opts.indent });
437
+ push("using System.Net.Http.Headers;");
438
+ let clienthandler = "";
439
+ const cookies = Boolean(allHeaders.cookie);
440
+ const decompressionMethods = getDecompressionMethods(allHeaders);
441
+ if (cookies || decompressionMethods.length) {
442
+ clienthandler = "clientHandler";
443
+ push("var clientHandler = new HttpClientHandler");
444
+ push("{");
445
+ if (cookies) {
446
+ push("UseCookies = false,", 1);
447
+ }
448
+ if (decompressionMethods.length) {
449
+ push(`AutomaticDecompression = ${decompressionMethods.join(" | ")},`, 1);
450
+ }
451
+ push("};");
452
+ }
453
+ push(`var client = new HttpClient(${clienthandler});`);
454
+ push("var request = new HttpRequestMessage");
455
+ push("{");
456
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE"];
457
+ method = method.toUpperCase();
458
+ if (method && methods.includes(method)) {
459
+ method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`;
460
+ } else {
461
+ method = `new HttpMethod("${method}")`;
462
+ }
463
+ push(`Method = ${method},`, 1);
464
+ push(`RequestUri = new Uri("${fullUrl}"),`, 1);
465
+ const headers = Object.keys(allHeaders).filter((header) => {
466
+ switch (header.toLowerCase()) {
467
+ case "content-type":
468
+ case "content-length":
469
+ case "accept-encoding":
470
+ return false;
471
+ default:
472
+ return true;
473
+ }
474
+ });
475
+ if (headers.length) {
476
+ push("Headers =", 1);
477
+ push("{", 1);
478
+ headers.forEach((key) => {
479
+ push(`{ "${key}", "${escapeForDoubleQuotes(allHeaders[key])}" },`, 2);
480
+ });
481
+ push("},", 1);
482
+ }
483
+ if (postData.text) {
484
+ const contentType = postData.mimeType;
485
+ switch (contentType) {
486
+ case "application/x-www-form-urlencoded":
487
+ push("Content = new FormUrlEncodedContent(new Dictionary<string, string>", 1);
488
+ push("{", 1);
489
+ postData.params?.forEach((param) => {
490
+ push(`{ "${param.name}", "${param.value}" },`, 2);
491
+ });
492
+ push("}),", 1);
493
+ break;
494
+ case "multipart/form-data":
495
+ push("Content = new MultipartFormDataContent", 1);
496
+ push("{", 1);
497
+ postData.params?.forEach((param) => {
498
+ push(`new StringContent(${JSON.stringify(param.value || "")})`, 2);
499
+ push("{", 2);
500
+ push("Headers =", 3);
501
+ push("{", 3);
502
+ if (param.contentType) {
503
+ push(`ContentType = new MediaTypeHeaderValue("${param.contentType}"),`, 4);
79
504
  }
80
- // construct headers objects
81
- if (request.cookies && request.cookies.length) {
82
- request.cookiesObj = request.cookies.reduceRight(function (accumulator, _a) {
83
- var _b;
84
- var name = _a.name, value = _a.value;
85
- return (__assign(__assign({}, accumulator), (_b = {}, _b[name] = value, _b)));
86
- }, {});
505
+ push('ContentDisposition = new ContentDispositionHeaderValue("form-data")', 4);
506
+ push("{", 4);
507
+ push(`Name = "${param.name}",`, 5);
508
+ if (param.fileName) {
509
+ push(`FileName = "${param.fileName}",`, 5);
87
510
  }
88
- // construct Cookie header
89
- var cookies = (_b = request.cookies) === null || _b === void 0 ? void 0 : _b.map(function (_a) {
90
- var name = _a.name, value = _a.value;
91
- if (options.harIsAlreadyEncoded) {
92
- return "".concat(name, "=").concat(value);
93
- }
94
- return "".concat(encodeURIComponent(name), "=").concat(encodeURIComponent(value));
511
+ push("}", 4);
512
+ push("}", 3);
513
+ push("},", 2);
514
+ });
515
+ push("},", 1);
516
+ break;
517
+ default:
518
+ push(`Content = new StringContent(${JSON.stringify(postData.text || "")})`, 1);
519
+ push("{", 1);
520
+ push("Headers =", 2);
521
+ push("{", 2);
522
+ push(`ContentType = new MediaTypeHeaderValue("${contentType}")`, 3);
523
+ push("}", 2);
524
+ push("}", 1);
525
+ break;
526
+ }
527
+ }
528
+ push("};");
529
+ push("using (var response = await client.SendAsync(request))");
530
+ push("{");
531
+ push("response.EnsureSuccessStatusCode();", 1);
532
+ push("var body = await response.Content.ReadAsStringAsync();", 1);
533
+ push("Console.WriteLine(body);", 1);
534
+ push("}");
535
+ return join();
536
+ }
537
+ };
538
+
539
+ // src/targets/csharp/restsharp/client.ts
540
+ function title(s) {
541
+ return s[0].toUpperCase() + s.slice(1).toLowerCase();
542
+ }
543
+ var restsharp = {
544
+ info: {
545
+ key: "restsharp",
546
+ title: "RestSharp",
547
+ link: "http://restsharp.org/",
548
+ description: "Simple REST and HTTP API Client for .NET"
549
+ },
550
+ convert: ({ method, fullUrl, headersObj, cookies, postData, uriObj }) => {
551
+ const { push, join } = new CodeBuilder();
552
+ const isSupportedMethod = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"].includes(
553
+ method.toUpperCase()
554
+ );
555
+ if (!isSupportedMethod) {
556
+ return "Method not supported";
557
+ }
558
+ push("using RestSharp;\n\n");
559
+ push(`var options = new RestClientOptions("${fullUrl}");`);
560
+ push("var client = new RestClient(options);");
561
+ push('var request = new RestRequest("");');
562
+ const isMultipart = postData.mimeType && postData.mimeType === "multipart/form-data";
563
+ if (isMultipart) {
564
+ push("request.AlwaysMultipartFormData = true;");
565
+ }
566
+ Object.keys(headersObj).forEach((key) => {
567
+ if (postData.mimeType && key.toLowerCase() === "content-type" && postData.text) {
568
+ if (isMultipart && postData.boundary) {
569
+ push(`request.FormBoundary = "${postData.boundary}";`);
570
+ }
571
+ return;
572
+ }
573
+ push(`request.AddHeader("${key}", "${escapeForDoubleQuotes(headersObj[key])}");`);
574
+ });
575
+ cookies.forEach(({ name, value }) => {
576
+ push(`request.AddCookie("${name}", "${escapeForDoubleQuotes(value)}", "${uriObj.pathname}", "${uriObj.host}");`);
577
+ });
578
+ switch (postData.mimeType) {
579
+ case "multipart/form-data":
580
+ if (!postData.params)
581
+ break;
582
+ postData.params.forEach((param) => {
583
+ if (param.fileName) {
584
+ push(`request.AddFile("${param.name}", "${param.fileName}");`);
585
+ } else {
586
+ push(`request.AddParameter("${param.name}", "${param.value}");`);
587
+ }
588
+ });
589
+ break;
590
+ case "application/x-www-form-urlencoded":
591
+ if (!postData.params)
592
+ break;
593
+ postData.params.forEach((param) => {
594
+ push(`request.AddParameter("${param.name}", "${param.value}");`);
595
+ });
596
+ break;
597
+ case "application/json": {
598
+ if (!postData.text)
599
+ break;
600
+ const text = JSON.stringify(postData.text);
601
+ push(`request.AddJsonBody(${text}, false);`);
602
+ break;
603
+ }
604
+ default:
605
+ if (!postData.text)
606
+ break;
607
+ push(`request.AddStringBody("${postData.text}", "${postData.mimeType}");`);
608
+ }
609
+ push(`var response = await client.${title(method)}Async(request);
610
+ `);
611
+ push('Console.WriteLine("{0}", response.Content);\n');
612
+ return join();
613
+ }
614
+ };
615
+
616
+ // src/targets/csharp/target.ts
617
+ var csharp = {
618
+ info: {
619
+ key: "csharp",
620
+ title: "C#",
621
+ extname: ".cs",
622
+ default: "restsharp",
623
+ cli: "dotnet"
624
+ },
625
+ clientsById: {
626
+ httpclient,
627
+ restsharp
628
+ }
629
+ };
630
+
631
+ // src/targets/go/native/client.ts
632
+ var native = {
633
+ info: {
634
+ key: "native",
635
+ title: "NewRequest",
636
+ link: "http://golang.org/pkg/net/http/#NewRequest",
637
+ description: "Golang HTTP client request"
638
+ },
639
+ convert: ({ postData, method, allHeaders, fullUrl }, options = {}) => {
640
+ const { blank, push, join } = new CodeBuilder({ indent: " " });
641
+ const { showBoilerplate = true, checkErrors = false, printBody = true, timeout = -1 } = options;
642
+ const errorPlaceholder = checkErrors ? "err" : "_";
643
+ const indent = showBoilerplate ? 1 : 0;
644
+ const errorCheck = () => {
645
+ if (checkErrors) {
646
+ push("if err != nil {", indent);
647
+ push("panic(err)", indent + 1);
648
+ push("}", indent);
649
+ }
650
+ };
651
+ if (showBoilerplate) {
652
+ push("package main");
653
+ blank();
654
+ push("import (");
655
+ push('"fmt"', indent);
656
+ if (timeout > 0) {
657
+ push('"time"', indent);
658
+ }
659
+ if (postData.text) {
660
+ push('"strings"', indent);
661
+ }
662
+ push('"net/http"', indent);
663
+ if (printBody) {
664
+ push('"io"', indent);
665
+ }
666
+ push(")");
667
+ blank();
668
+ push("func main() {");
669
+ blank();
670
+ }
671
+ const hasTimeout = timeout > 0;
672
+ const hasClient = hasTimeout;
673
+ const client = hasClient ? "client" : "http.DefaultClient";
674
+ if (hasClient) {
675
+ push("client := http.Client{", indent);
676
+ if (hasTimeout) {
677
+ push(`Timeout: time.Duration(${timeout} * time.Second),`, indent + 1);
678
+ }
679
+ push("}", indent);
680
+ blank();
681
+ }
682
+ push(`url := "${fullUrl}"`, indent);
683
+ blank();
684
+ if (postData.text) {
685
+ push(`payload := strings.NewReader(${JSON.stringify(postData.text)})`, indent);
686
+ blank();
687
+ push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, payload)`, indent);
688
+ blank();
689
+ } else {
690
+ push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, nil)`, indent);
691
+ blank();
692
+ }
693
+ errorCheck();
694
+ if (Object.keys(allHeaders).length) {
695
+ Object.keys(allHeaders).forEach((key) => {
696
+ push(`req.Header.Add("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, indent);
697
+ });
698
+ blank();
699
+ }
700
+ push(`res, ${errorPlaceholder} := ${client}.Do(req)`, indent);
701
+ errorCheck();
702
+ if (printBody) {
703
+ blank();
704
+ push("defer res.Body.Close()", indent);
705
+ push(`body, ${errorPlaceholder} := io.ReadAll(res.Body)`, indent);
706
+ errorCheck();
707
+ }
708
+ blank();
709
+ if (printBody) {
710
+ push("fmt.Println(string(body))", indent);
711
+ }
712
+ if (showBoilerplate) {
713
+ blank();
714
+ push("}");
715
+ }
716
+ return join();
717
+ }
718
+ };
719
+
720
+ // src/targets/go/target.ts
721
+ var go = {
722
+ info: {
723
+ key: "go",
724
+ title: "Go",
725
+ extname: ".go",
726
+ default: "native",
727
+ cli: "go"
728
+ },
729
+ clientsById: {
730
+ native
731
+ }
732
+ };
733
+
734
+ // src/targets/http/http1.1/client.ts
735
+ var CRLF = "\r\n";
736
+ var http11 = {
737
+ info: {
738
+ key: "http1.1",
739
+ title: "HTTP/1.1",
740
+ link: "https://tools.ietf.org/html/rfc7230",
741
+ description: "HTTP/1.1 request string in accordance with RFC 7230"
742
+ },
743
+ convert: ({ method, fullUrl, uriObj, httpVersion, allHeaders, postData }, options) => {
744
+ const opts = {
745
+ absoluteURI: false,
746
+ autoContentLength: true,
747
+ autoHost: true,
748
+ ...options
749
+ };
750
+ const { blank, push, join } = new CodeBuilder({ indent: "", join: CRLF });
751
+ const requestUrl = opts.absoluteURI ? fullUrl : uriObj.path;
752
+ push(`${method} ${requestUrl} ${httpVersion}`);
753
+ const headerKeys = Object.keys(allHeaders);
754
+ headerKeys.forEach((key) => {
755
+ const keyCapitalized = key.toLowerCase().replace(/(^|-)(\w)/g, (input) => input.toUpperCase());
756
+ push(`${keyCapitalized}: ${allHeaders[key]}`);
757
+ });
758
+ if (opts.autoHost && !headerKeys.includes("host")) {
759
+ push(`Host: ${uriObj.host}`);
760
+ }
761
+ if (opts.autoContentLength && postData.text && !headerKeys.includes("content-length")) {
762
+ const length = Buffer.byteLength(postData.text, "ascii").toString();
763
+ push(`Content-Length: ${length}`);
764
+ }
765
+ blank();
766
+ const headerSection = join();
767
+ const messageBody = postData.text || "";
768
+ return `${headerSection}${CRLF}${messageBody}`;
769
+ }
770
+ };
771
+
772
+ // src/targets/http/target.ts
773
+ var http = {
774
+ info: {
775
+ key: "http",
776
+ title: "HTTP",
777
+ extname: null,
778
+ default: "1.1"
779
+ },
780
+ clientsById: {
781
+ "http1.1": http11
782
+ }
783
+ };
784
+
785
+ // src/targets/java/asynchttp/client.ts
786
+ var asynchttp = {
787
+ info: {
788
+ key: "asynchttp",
789
+ title: "AsyncHttp",
790
+ link: "https://github.com/AsyncHttpClient/async-http-client",
791
+ description: "Asynchronous Http and WebSocket Client library for Java"
792
+ },
793
+ convert: ({ method, allHeaders, postData, fullUrl }, options) => {
794
+ const opts = {
795
+ indent: " ",
796
+ ...options
797
+ };
798
+ const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
799
+ push("AsyncHttpClient client = new DefaultAsyncHttpClient();");
800
+ push(`client.prepare("${method.toUpperCase()}", "${fullUrl}")`);
801
+ Object.keys(allHeaders).forEach((key) => {
802
+ push(`.setHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
803
+ });
804
+ if (postData.text) {
805
+ push(`.setBody(${JSON.stringify(postData.text)})`, 1);
806
+ }
807
+ push(".execute()", 1);
808
+ push(".toCompletableFuture()", 1);
809
+ push(".thenAccept(System.out::println)", 1);
810
+ push(".join();", 1);
811
+ blank();
812
+ push("client.close();");
813
+ return join();
814
+ }
815
+ };
816
+
817
+ // src/targets/java/nethttp/client.ts
818
+ var nethttp = {
819
+ info: {
820
+ key: "nethttp",
821
+ title: "java.net.http",
822
+ link: "https://openjdk.java.net/groups/net/httpclient/intro.html",
823
+ description: "Java Standardized HTTP Client API"
824
+ },
825
+ convert: ({ allHeaders, fullUrl, method, postData }, options) => {
826
+ const opts = {
827
+ indent: " ",
828
+ ...options
829
+ };
830
+ const { push, join } = new CodeBuilder({ indent: opts.indent });
831
+ push("HttpRequest request = HttpRequest.newBuilder()");
832
+ push(`.uri(URI.create("${fullUrl}"))`, 2);
833
+ Object.keys(allHeaders).forEach((key) => {
834
+ push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 2);
835
+ });
836
+ if (postData.text) {
837
+ push(
838
+ `.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.ofString(${JSON.stringify(postData.text)}))`,
839
+ 2
840
+ );
841
+ } else {
842
+ push(`.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.noBody())`, 2);
843
+ }
844
+ push(".build();", 2);
845
+ push(
846
+ "HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());"
847
+ );
848
+ push("System.out.println(response.body());");
849
+ return join();
850
+ }
851
+ };
852
+
853
+ // src/targets/java/okhttp/client.ts
854
+ var okhttp = {
855
+ info: {
856
+ key: "okhttp",
857
+ title: "OkHttp",
858
+ link: "http://square.github.io/okhttp/",
859
+ description: "An HTTP Request Client Library"
860
+ },
861
+ convert: ({ postData, method, fullUrl, allHeaders }, options) => {
862
+ const opts = {
863
+ indent: " ",
864
+ ...options
865
+ };
866
+ const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
867
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
868
+ const methodsWithBody = ["POST", "PUT", "DELETE", "PATCH"];
869
+ push("OkHttpClient client = new OkHttpClient();");
870
+ blank();
871
+ if (postData.text) {
872
+ if (postData.boundary) {
873
+ push(`MediaType mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}");`);
874
+ } else {
875
+ push(`MediaType mediaType = MediaType.parse("${postData.mimeType}");`);
876
+ }
877
+ push(`RequestBody body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)});`);
878
+ }
879
+ push("Request request = new Request.Builder()");
880
+ push(`.url("${fullUrl}")`, 1);
881
+ if (!methods.includes(method.toUpperCase())) {
882
+ if (postData.text) {
883
+ push(`.method("${method.toUpperCase()}", body)`, 1);
884
+ } else {
885
+ push(`.method("${method.toUpperCase()}", null)`, 1);
886
+ }
887
+ } else if (methodsWithBody.includes(method.toUpperCase())) {
888
+ if (postData.text) {
889
+ push(`.${method.toLowerCase()}(body)`, 1);
890
+ } else {
891
+ push(`.${method.toLowerCase()}(null)`, 1);
892
+ }
893
+ } else {
894
+ push(`.${method.toLowerCase()}()`, 1);
895
+ }
896
+ Object.keys(allHeaders).forEach((key) => {
897
+ push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
898
+ });
899
+ push(".build();", 1);
900
+ blank();
901
+ push("Response response = client.newCall(request).execute();");
902
+ return join();
903
+ }
904
+ };
905
+
906
+ // src/targets/java/unirest/client.ts
907
+ var unirest = {
908
+ info: {
909
+ key: "unirest",
910
+ title: "Unirest",
911
+ link: "http://unirest.io/java.html",
912
+ description: "Lightweight HTTP Request Client Library"
913
+ },
914
+ convert: ({ method, allHeaders, postData, fullUrl }, options) => {
915
+ const opts = {
916
+ indent: " ",
917
+ ...options
918
+ };
919
+ const { join, push } = new CodeBuilder({ indent: opts.indent });
920
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
921
+ if (!methods.includes(method.toUpperCase())) {
922
+ push(`HttpResponse<String> response = Unirest.customMethod("${method.toUpperCase()}","${fullUrl}")`);
923
+ } else {
924
+ push(`HttpResponse<String> response = Unirest.${method.toLowerCase()}("${fullUrl}")`);
925
+ }
926
+ Object.keys(allHeaders).forEach((key) => {
927
+ push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
928
+ });
929
+ if (postData.text) {
930
+ push(`.body(${JSON.stringify(postData.text)})`, 1);
931
+ }
932
+ push(".asString();", 1);
933
+ return join();
934
+ }
935
+ };
936
+
937
+ // src/targets/java/target.ts
938
+ var java = {
939
+ info: {
940
+ key: "java",
941
+ title: "Java",
942
+ extname: ".java",
943
+ default: "unirest"
944
+ },
945
+ clientsById: {
946
+ asynchttp,
947
+ nethttp,
948
+ okhttp,
949
+ unirest
950
+ }
951
+ };
952
+ var axios = {
953
+ info: {
954
+ key: "axios",
955
+ title: "Axios",
956
+ link: "https://github.com/axios/axios",
957
+ description: "Promise based HTTP client for the browser and node.js"
958
+ },
959
+ convert: ({ allHeaders, method, url, queryObj, postData }, options) => {
960
+ const opts = {
961
+ indent: " ",
962
+ ...options
963
+ };
964
+ const { blank, push, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
965
+ push("import axios from 'axios';");
966
+ blank();
967
+ const requestOptions = {
968
+ method,
969
+ url
970
+ };
971
+ if (Object.keys(queryObj).length) {
972
+ requestOptions.params = queryObj;
973
+ }
974
+ if (Object.keys(allHeaders).length) {
975
+ requestOptions.headers = allHeaders;
976
+ }
977
+ switch (postData.mimeType) {
978
+ case "application/x-www-form-urlencoded":
979
+ if (postData.params) {
980
+ push("const encodedParams = new URLSearchParams();");
981
+ postData.params.forEach((param) => {
982
+ push(`encodedParams.set('${param.name}', '${param.value}');`);
983
+ });
984
+ blank();
985
+ requestOptions.data = "encodedParams,";
986
+ addPostProcessor((code) => code.replace(/'encodedParams,'/, "encodedParams,"));
987
+ }
988
+ break;
989
+ case "application/json":
990
+ if (postData.jsonObj) {
991
+ requestOptions.data = postData.jsonObj;
992
+ }
993
+ break;
994
+ case "multipart/form-data":
995
+ if (!postData.params) {
996
+ break;
997
+ }
998
+ push("const form = new FormData();");
999
+ postData.params.forEach((param) => {
1000
+ push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1001
+ });
1002
+ blank();
1003
+ requestOptions.data = "[form]";
1004
+ break;
1005
+ default:
1006
+ if (postData.text) {
1007
+ requestOptions.data = postData.text;
1008
+ }
1009
+ }
1010
+ const optionString = stringifyObject9__default.default(requestOptions, {
1011
+ indent: " ",
1012
+ inlineCharacterLimit: 80
1013
+ }).replace('"[form]"', "form");
1014
+ push(`const options = ${optionString};`);
1015
+ blank();
1016
+ push("axios");
1017
+ push(".request(options)", 1);
1018
+ push(".then(function (response) {", 1);
1019
+ push("console.log(response.data);", 2);
1020
+ push("})", 1);
1021
+ push(".catch(function (error) {", 1);
1022
+ push("console.error(error);", 2);
1023
+ push("});", 1);
1024
+ return join();
1025
+ }
1026
+ };
1027
+ var fetch = {
1028
+ info: {
1029
+ key: "fetch",
1030
+ title: "fetch",
1031
+ link: "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
1032
+ description: "Perform asynchronous HTTP requests with the Fetch API"
1033
+ },
1034
+ convert: ({ method, allHeaders, postData, fullUrl }, inputOpts) => {
1035
+ const opts = {
1036
+ indent: " ",
1037
+ credentials: null,
1038
+ ...inputOpts
1039
+ };
1040
+ const { blank, join, push } = new CodeBuilder({ indent: opts.indent });
1041
+ const options = {
1042
+ method
1043
+ };
1044
+ if (Object.keys(allHeaders).length) {
1045
+ options.headers = allHeaders;
1046
+ }
1047
+ if (opts.credentials !== null) {
1048
+ options.credentials = opts.credentials;
1049
+ }
1050
+ switch (postData.mimeType) {
1051
+ case "application/x-www-form-urlencoded":
1052
+ options.body = postData.paramsObj ? postData.paramsObj : postData.text;
1053
+ break;
1054
+ case "application/json":
1055
+ if (postData.jsonObj) {
1056
+ options.body = postData.jsonObj;
1057
+ }
1058
+ break;
1059
+ case "multipart/form-data":
1060
+ if (!postData.params) {
1061
+ break;
1062
+ }
1063
+ const contentTypeHeader = getHeaderName(allHeaders, "content-type");
1064
+ if (contentTypeHeader) {
1065
+ delete allHeaders[contentTypeHeader];
1066
+ }
1067
+ push("const form = new FormData();");
1068
+ postData.params.forEach((param) => {
1069
+ push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1070
+ });
1071
+ blank();
1072
+ break;
1073
+ default:
1074
+ if (postData.text) {
1075
+ options.body = postData.text;
1076
+ }
1077
+ }
1078
+ if (options.headers && !Object.keys(options.headers).length) {
1079
+ delete options.headers;
1080
+ }
1081
+ push(
1082
+ `const options = ${stringifyObject9__default.default(options, {
1083
+ indent: opts.indent,
1084
+ inlineCharacterLimit: 80,
1085
+ // The Fetch API body only accepts string parameters, but stringified JSON can be difficult
1086
+ // to read, so we keep the object as a literal and use this transform function to wrap the
1087
+ // literal in a `JSON.stringify` call.
1088
+ transform: (object, property, originalResult) => {
1089
+ if (property === "body") {
1090
+ if (postData.mimeType === "application/x-www-form-urlencoded") {
1091
+ return `new URLSearchParams(${originalResult})`;
1092
+ } else if (postData.mimeType === "application/json") {
1093
+ return `JSON.stringify(${originalResult})`;
1094
+ }
1095
+ }
1096
+ return originalResult;
1097
+ }
1098
+ })};`
1099
+ );
1100
+ blank();
1101
+ if (postData.params && postData.mimeType === "multipart/form-data") {
1102
+ push("options.body = form;");
1103
+ blank();
1104
+ }
1105
+ push(`fetch('${fullUrl}', options)`);
1106
+ push(".then(response => response.json())", 1);
1107
+ push(".then(response => console.log(response))", 1);
1108
+ push(".catch(err => console.error(err));", 1);
1109
+ return join();
1110
+ }
1111
+ };
1112
+ var jquery = {
1113
+ info: {
1114
+ key: "jquery",
1115
+ title: "jQuery",
1116
+ link: "http://api.jquery.com/jquery.ajax/",
1117
+ description: "Perform an asynchronous HTTP (Ajax) requests with jQuery"
1118
+ },
1119
+ convert: ({ fullUrl, method, allHeaders, postData }, options) => {
1120
+ const opts = {
1121
+ indent: " ",
1122
+ ...options
1123
+ };
1124
+ const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
1125
+ const settings = {
1126
+ async: true,
1127
+ crossDomain: true,
1128
+ url: fullUrl,
1129
+ method,
1130
+ headers: allHeaders
1131
+ };
1132
+ switch (postData.mimeType) {
1133
+ case "application/x-www-form-urlencoded":
1134
+ settings.data = postData.paramsObj ? postData.paramsObj : postData.text;
1135
+ break;
1136
+ case "application/json":
1137
+ settings.processData = false;
1138
+ settings.data = postData.text;
1139
+ break;
1140
+ case "multipart/form-data":
1141
+ if (!postData.params) {
1142
+ break;
1143
+ }
1144
+ push("const form = new FormData();");
1145
+ postData.params.forEach((param) => {
1146
+ push(`form.append('${param.name}', '${param.value || param.fileName || ""}');`);
1147
+ });
1148
+ settings.processData = false;
1149
+ settings.contentType = false;
1150
+ settings.mimeType = "multipart/form-data";
1151
+ settings.data = "[form]";
1152
+ if (hasHeader(allHeaders, "content-type")) {
1153
+ if (getHeader2(allHeaders, "content-type")?.includes("boundary")) {
1154
+ const headerName = getHeaderName(allHeaders, "content-type");
1155
+ if (headerName) {
1156
+ delete settings.headers[headerName];
1157
+ }
1158
+ }
1159
+ }
1160
+ blank();
1161
+ break;
1162
+ default:
1163
+ if (postData.text) {
1164
+ settings.data = postData.text;
1165
+ }
1166
+ }
1167
+ const stringifiedSettings = stringifyObject9__default.default(settings, { indent: opts.indent }).replace("'[form]'", "form");
1168
+ push(`const settings = ${stringifiedSettings};`);
1169
+ blank();
1170
+ push("$.ajax(settings).done(function (response) {");
1171
+ push("console.log(response);", 1);
1172
+ push("});");
1173
+ return join();
1174
+ }
1175
+ };
1176
+ var xhr = {
1177
+ info: {
1178
+ key: "xhr",
1179
+ title: "XMLHttpRequest",
1180
+ link: "https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest",
1181
+ description: "W3C Standard API that provides scripted client functionality"
1182
+ },
1183
+ convert: ({ postData, allHeaders, method, fullUrl }, options) => {
1184
+ const opts = {
1185
+ indent: " ",
1186
+ cors: true,
1187
+ ...options
1188
+ };
1189
+ const { blank, push, join } = new CodeBuilder({ indent: opts.indent });
1190
+ switch (postData.mimeType) {
1191
+ case "application/json":
1192
+ push(
1193
+ `const data = JSON.stringify(${stringifyObject9__default.default(postData.jsonObj, {
1194
+ indent: opts.indent
1195
+ })});`
1196
+ );
1197
+ blank();
1198
+ break;
1199
+ case "multipart/form-data":
1200
+ if (!postData.params) {
1201
+ break;
1202
+ }
1203
+ push("const data = new FormData();");
1204
+ postData.params.forEach((param) => {
1205
+ push(`data.append('${param.name}', '${param.value || param.fileName || ""}');`);
1206
+ });
1207
+ if (hasHeader(allHeaders, "content-type")) {
1208
+ if (getHeader2(allHeaders, "content-type")?.includes("boundary")) {
1209
+ const headerName = getHeaderName(allHeaders, "content-type");
1210
+ if (headerName) {
1211
+ delete allHeaders[headerName];
1212
+ }
1213
+ }
1214
+ }
1215
+ blank();
1216
+ break;
1217
+ default:
1218
+ push(`const data = ${postData.text ? `'${postData.text}'` : "null"};`);
1219
+ blank();
1220
+ }
1221
+ push("const xhr = new XMLHttpRequest();");
1222
+ if (opts.cors) {
1223
+ push("xhr.withCredentials = true;");
1224
+ }
1225
+ blank();
1226
+ push("xhr.addEventListener('readystatechange', function () {");
1227
+ push("if (this.readyState === this.DONE) {", 1);
1228
+ push("console.log(this.responseText);", 2);
1229
+ push("}", 1);
1230
+ push("});");
1231
+ blank();
1232
+ push(`xhr.open('${method}', '${fullUrl}');`);
1233
+ Object.keys(allHeaders).forEach((key) => {
1234
+ push(`xhr.setRequestHeader('${key}', '${escapeForSingleQuotes(allHeaders[key])}');`);
1235
+ });
1236
+ blank();
1237
+ push("xhr.send(data);");
1238
+ return join();
1239
+ }
1240
+ };
1241
+
1242
+ // src/targets/javascript/target.ts
1243
+ var javascript = {
1244
+ info: {
1245
+ key: "javascript",
1246
+ title: "JavaScript",
1247
+ extname: ".js",
1248
+ default: "xhr"
1249
+ },
1250
+ clientsById: {
1251
+ xhr,
1252
+ axios,
1253
+ fetch,
1254
+ jquery
1255
+ }
1256
+ };
1257
+
1258
+ // src/targets/json/native/client.ts
1259
+ var native2 = {
1260
+ info: {
1261
+ key: "native",
1262
+ title: "Native JSON",
1263
+ link: "https://www.json.org/json-en.html",
1264
+ description: "A JSON represetation of any HAR payload."
1265
+ },
1266
+ convert: ({ postData }, inputOpts) => {
1267
+ const opts = {
1268
+ indent: " ",
1269
+ ...inputOpts
1270
+ };
1271
+ let payload = "";
1272
+ switch (postData.mimeType) {
1273
+ case "application/x-www-form-urlencoded":
1274
+ payload = postData.paramsObj ? postData.paramsObj : postData.text;
1275
+ break;
1276
+ case "application/json":
1277
+ if (postData.jsonObj) {
1278
+ payload = postData.jsonObj;
1279
+ }
1280
+ break;
1281
+ case "multipart/form-data":
1282
+ if (!postData.params) {
1283
+ break;
1284
+ }
1285
+ const multipartPayload = {};
1286
+ postData.params.forEach((param) => {
1287
+ multipartPayload[param.name] = param.value;
1288
+ });
1289
+ payload = multipartPayload;
1290
+ break;
1291
+ default:
1292
+ if (postData.text) {
1293
+ payload = postData.text;
1294
+ }
1295
+ }
1296
+ if (typeof payload === "undefined" || payload === "") {
1297
+ return "No JSON body";
1298
+ }
1299
+ return JSON.stringify(payload, null, opts.indent);
1300
+ }
1301
+ };
1302
+
1303
+ // src/targets/json/target.ts
1304
+ var json = {
1305
+ info: {
1306
+ key: "json",
1307
+ title: "JSON",
1308
+ extname: ".json",
1309
+ default: "native"
1310
+ },
1311
+ clientsById: {
1312
+ native: native2
1313
+ }
1314
+ };
1315
+
1316
+ // src/targets/kotlin/okhttp/client.ts
1317
+ var okhttp2 = {
1318
+ info: {
1319
+ key: "okhttp",
1320
+ title: "OkHttp",
1321
+ link: "http://square.github.io/okhttp/",
1322
+ description: "An HTTP Request Client Library"
1323
+ },
1324
+ convert: ({ postData, fullUrl, method, allHeaders }, options) => {
1325
+ const opts = {
1326
+ indent: " ",
1327
+ ...options
1328
+ };
1329
+ const { blank, join, push } = new CodeBuilder({ indent: opts.indent });
1330
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
1331
+ const methodsWithBody = ["POST", "PUT", "DELETE", "PATCH"];
1332
+ push("val client = OkHttpClient()");
1333
+ blank();
1334
+ if (postData.text) {
1335
+ if (postData.boundary) {
1336
+ push(`val mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}")`);
1337
+ } else {
1338
+ push(`val mediaType = MediaType.parse("${postData.mimeType}")`);
1339
+ }
1340
+ push(`val body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)})`);
1341
+ }
1342
+ push("val request = Request.Builder()");
1343
+ push(`.url("${fullUrl}")`, 1);
1344
+ if (!methods.includes(method.toUpperCase())) {
1345
+ if (postData.text) {
1346
+ push(`.method("${method.toUpperCase()}", body)`, 1);
1347
+ } else {
1348
+ push(`.method("${method.toUpperCase()}", null)`, 1);
1349
+ }
1350
+ } else if (methodsWithBody.includes(method.toUpperCase())) {
1351
+ if (postData.text) {
1352
+ push(`.${method.toLowerCase()}(body)`, 1);
1353
+ } else {
1354
+ push(`.${method.toLowerCase()}(null)`, 1);
1355
+ }
1356
+ } else {
1357
+ push(`.${method.toLowerCase()}()`, 1);
1358
+ }
1359
+ Object.keys(allHeaders).forEach((key) => {
1360
+ push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1);
1361
+ });
1362
+ push(".build()", 1);
1363
+ blank();
1364
+ push("val response = client.newCall(request).execute()");
1365
+ return join();
1366
+ }
1367
+ };
1368
+
1369
+ // src/targets/kotlin/target.ts
1370
+ var kotlin = {
1371
+ info: {
1372
+ key: "kotlin",
1373
+ title: "Kotlin",
1374
+ extname: ".kt",
1375
+ default: "okhttp"
1376
+ },
1377
+ clientsById: {
1378
+ okhttp: okhttp2
1379
+ }
1380
+ };
1381
+ var axios2 = {
1382
+ info: {
1383
+ key: "axios",
1384
+ title: "Axios",
1385
+ link: "https://github.com/axios/axios",
1386
+ description: "Promise based HTTP client for the browser and node.js"
1387
+ },
1388
+ convert: ({ method, fullUrl, allHeaders, postData }, options) => {
1389
+ const opts = {
1390
+ indent: " ",
1391
+ ...options
1392
+ };
1393
+ const { blank, join, push, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
1394
+ push("const axios = require('axios');");
1395
+ const reqOpts = {
1396
+ method,
1397
+ url: fullUrl
1398
+ };
1399
+ if (Object.keys(allHeaders).length) {
1400
+ reqOpts.headers = allHeaders;
1401
+ }
1402
+ switch (postData.mimeType) {
1403
+ case "application/x-www-form-urlencoded":
1404
+ if (postData.params) {
1405
+ push("const { URLSearchParams } = require('url');");
1406
+ blank();
1407
+ push("const encodedParams = new URLSearchParams();");
1408
+ postData.params.forEach((param) => {
1409
+ push(`encodedParams.set('${param.name}', '${param.value}');`);
1410
+ });
1411
+ blank();
1412
+ reqOpts.data = "encodedParams,";
1413
+ addPostProcessor((code) => code.replace(/'encodedParams,'/, "encodedParams,"));
1414
+ }
1415
+ break;
1416
+ case "application/json":
1417
+ blank();
1418
+ if (postData.jsonObj) {
1419
+ reqOpts.data = postData.jsonObj;
1420
+ }
1421
+ break;
1422
+ default:
1423
+ blank();
1424
+ if (postData.text) {
1425
+ reqOpts.data = postData.text;
1426
+ }
1427
+ }
1428
+ const stringifiedOptions = stringifyObject9__default.default(reqOpts, { indent: " ", inlineCharacterLimit: 80 });
1429
+ push(`const options = ${stringifiedOptions};`);
1430
+ blank();
1431
+ push("axios");
1432
+ push(".request(options)", 1);
1433
+ push(".then(function (response) {", 1);
1434
+ push("console.log(response.data);", 2);
1435
+ push("})", 1);
1436
+ push(".catch(function (error) {", 1);
1437
+ push("console.error(error);", 2);
1438
+ push("});", 1);
1439
+ return join();
1440
+ }
1441
+ };
1442
+ var fetch2 = {
1443
+ info: {
1444
+ key: "fetch",
1445
+ title: "Fetch",
1446
+ link: "https://github.com/bitinn/node-fetch",
1447
+ description: "Simplified HTTP node-fetch client"
1448
+ },
1449
+ convert: ({ method, fullUrl, postData, headersObj, cookies }, options) => {
1450
+ const opts = {
1451
+ indent: " ",
1452
+ ...options
1453
+ };
1454
+ let includeFS = false;
1455
+ const { blank, push, join, unshift } = new CodeBuilder({ indent: opts.indent });
1456
+ push("const fetch = require('node-fetch');");
1457
+ const url = fullUrl;
1458
+ const reqOpts = {
1459
+ method
1460
+ };
1461
+ if (Object.keys(headersObj).length) {
1462
+ reqOpts.headers = headersObj;
1463
+ }
1464
+ switch (postData.mimeType) {
1465
+ case "application/x-www-form-urlencoded":
1466
+ unshift("const { URLSearchParams } = require('url');");
1467
+ push("const encodedParams = new URLSearchParams();");
1468
+ blank();
1469
+ postData.params?.forEach((param) => {
1470
+ push(`encodedParams.set('${param.name}', '${param.value}');`);
1471
+ });
1472
+ reqOpts.body = "encodedParams";
1473
+ break;
1474
+ case "application/json":
1475
+ if (postData.jsonObj) {
1476
+ reqOpts.body = postData.jsonObj;
1477
+ }
1478
+ break;
1479
+ case "multipart/form-data":
1480
+ if (!postData.params) {
1481
+ break;
1482
+ }
1483
+ const contentTypeHeader = getHeaderName(headersObj, "content-type");
1484
+ if (contentTypeHeader) {
1485
+ delete headersObj[contentTypeHeader];
1486
+ }
1487
+ unshift("const FormData = require('form-data');");
1488
+ push("const formData = new FormData();");
1489
+ blank();
1490
+ postData.params.forEach((param) => {
1491
+ if (!param.fileName && !param.fileName && !param.contentType) {
1492
+ push(`formData.append('${param.name}', '${param.value}');`);
1493
+ return;
1494
+ }
1495
+ if (param.fileName) {
1496
+ includeFS = true;
1497
+ push(`formData.append('${param.name}', fs.createReadStream('${param.fileName}'));`);
1498
+ }
1499
+ });
1500
+ break;
1501
+ default:
1502
+ if (postData.text) {
1503
+ reqOpts.body = postData.text;
1504
+ }
1505
+ }
1506
+ if (cookies.length) {
1507
+ const cookiesString = cookies.map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("; ");
1508
+ if (reqOpts.headers) {
1509
+ reqOpts.headers.cookie = cookiesString;
1510
+ } else {
1511
+ reqOpts.headers = {};
1512
+ reqOpts.headers.cookie = cookiesString;
1513
+ }
1514
+ }
1515
+ blank();
1516
+ push(`const url = '${url}';`);
1517
+ if (reqOpts.headers && !Object.keys(reqOpts.headers).length) {
1518
+ delete reqOpts.headers;
1519
+ }
1520
+ const stringifiedOptions = stringifyObject9__default.default(reqOpts, {
1521
+ indent: " ",
1522
+ inlineCharacterLimit: 80,
1523
+ // The Fetch API body only accepts string parameters, but stringified JSON can be difficult to
1524
+ // read, so we keep the object as a literal and use this transform function to wrap the literal
1525
+ // in a `JSON.stringify` call.
1526
+ transform: (object, property, originalResult) => {
1527
+ if (property === "body" && postData.mimeType === "application/json") {
1528
+ return `JSON.stringify(${originalResult})`;
1529
+ }
1530
+ return originalResult;
1531
+ }
1532
+ });
1533
+ push(`const options = ${stringifiedOptions};`);
1534
+ blank();
1535
+ if (includeFS) {
1536
+ unshift("const fs = require('fs');");
1537
+ }
1538
+ if (postData.params && postData.mimeType === "multipart/form-data") {
1539
+ push("options.body = formData;");
1540
+ blank();
1541
+ }
1542
+ push("fetch(url, options)");
1543
+ push(".then(res => res.json())", 1);
1544
+ push(".then(json => console.log(json))", 1);
1545
+ push(".catch(err => console.error('error:' + err));", 1);
1546
+ return join().replace(/'encodedParams'/, "encodedParams").replace(/"fs\.createReadStream\(\\"(.+)\\"\)"/, 'fs.createReadStream("$1")');
1547
+ }
1548
+ };
1549
+ var native3 = {
1550
+ info: {
1551
+ key: "native",
1552
+ title: "HTTP",
1553
+ link: "http://nodejs.org/api/http.html#http_http_request_options_callback",
1554
+ description: "Node.js native HTTP interface"
1555
+ },
1556
+ convert: ({ uriObj, method, allHeaders, postData }, options = {}) => {
1557
+ const { indent = " " } = options;
1558
+ const { blank, join, push, unshift } = new CodeBuilder({ indent });
1559
+ const reqOpts = {
1560
+ method,
1561
+ hostname: uriObj.hostname,
1562
+ port: uriObj.port,
1563
+ path: uriObj.path,
1564
+ headers: allHeaders
1565
+ };
1566
+ push(`const http = require('${uriObj.protocol?.replace(":", "")}');`);
1567
+ blank();
1568
+ push(`const options = ${stringifyObject9__default.default(reqOpts, { indent })};`);
1569
+ blank();
1570
+ push("const req = http.request(options, function (res) {");
1571
+ push("const chunks = [];", 1);
1572
+ blank();
1573
+ push("res.on('data', function (chunk) {", 1);
1574
+ push("chunks.push(chunk);", 2);
1575
+ push("});", 1);
1576
+ blank();
1577
+ push("res.on('end', function () {", 1);
1578
+ push("const body = Buffer.concat(chunks);", 2);
1579
+ push("console.log(body.toString());", 2);
1580
+ push("});", 1);
1581
+ push("});");
1582
+ blank();
1583
+ switch (postData.mimeType) {
1584
+ case "application/x-www-form-urlencoded":
1585
+ if (postData.paramsObj) {
1586
+ unshift("const qs = require('querystring');");
1587
+ push(
1588
+ `req.write(qs.stringify(${stringifyObject9__default.default(postData.paramsObj, {
1589
+ indent: " ",
1590
+ inlineCharacterLimit: 80
1591
+ })}));`
1592
+ );
1593
+ }
1594
+ break;
1595
+ case "application/json":
1596
+ if (postData.jsonObj) {
1597
+ push(
1598
+ `req.write(JSON.stringify(${stringifyObject9__default.default(postData.jsonObj, {
1599
+ indent: " ",
1600
+ inlineCharacterLimit: 80
1601
+ })}));`
1602
+ );
1603
+ }
1604
+ break;
1605
+ default:
1606
+ if (postData.text) {
1607
+ push(`req.write(${stringifyObject9__default.default(postData.text, { indent })});`);
1608
+ }
1609
+ }
1610
+ push("req.end();");
1611
+ return join();
1612
+ }
1613
+ };
1614
+ var request = {
1615
+ info: {
1616
+ key: "request",
1617
+ title: "Request",
1618
+ link: "https://github.com/request/request",
1619
+ description: "Simplified HTTP request client"
1620
+ },
1621
+ convert: ({ method, url, fullUrl, postData, headersObj, cookies }, options) => {
1622
+ const opts = {
1623
+ indent: " ",
1624
+ ...options
1625
+ };
1626
+ let includeFS = false;
1627
+ const { push, blank, join, unshift, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
1628
+ push("const request = require('request');");
1629
+ blank();
1630
+ const reqOpts = {
1631
+ method,
1632
+ url: fullUrl
1633
+ };
1634
+ if (Object.keys(headersObj).length) {
1635
+ reqOpts.headers = headersObj;
1636
+ }
1637
+ switch (postData.mimeType) {
1638
+ case "application/x-www-form-urlencoded":
1639
+ reqOpts.form = postData.paramsObj;
1640
+ break;
1641
+ case "application/json":
1642
+ if (postData.jsonObj) {
1643
+ reqOpts.body = postData.jsonObj;
1644
+ reqOpts.json = true;
1645
+ }
1646
+ break;
1647
+ case "multipart/form-data":
1648
+ if (!postData.params) {
1649
+ break;
1650
+ }
1651
+ reqOpts.formData = {};
1652
+ postData.params.forEach((param) => {
1653
+ if (!param.fileName && !param.fileName && !param.contentType) {
1654
+ reqOpts.formData[param.name] = param.value;
1655
+ return;
1656
+ }
1657
+ let attachment = {};
1658
+ if (param.fileName) {
1659
+ includeFS = true;
1660
+ attachment = {
1661
+ value: `fs.createReadStream(${param.fileName})`,
1662
+ options: {
1663
+ filename: param.fileName,
1664
+ contentType: param.contentType ? param.contentType : null
1665
+ }
1666
+ };
1667
+ } else if (param.value) {
1668
+ attachment.value = param.value;
1669
+ }
1670
+ reqOpts.formData[param.name] = attachment;
1671
+ });
1672
+ addPostProcessor((code) => code.replace(/'fs\.createReadStream\((.*)\)'/, "fs.createReadStream('$1')"));
1673
+ break;
1674
+ default:
1675
+ if (postData.text) {
1676
+ reqOpts.body = postData.text;
1677
+ }
1678
+ }
1679
+ if (cookies.length) {
1680
+ reqOpts.jar = "JAR";
1681
+ push("const jar = request.jar();");
1682
+ cookies.forEach(({ name, value }) => {
1683
+ push(`jar.setCookie(request.cookie('${encodeURIComponent(name)}=${encodeURIComponent(value)}'), '${url}');`);
1684
+ });
1685
+ blank();
1686
+ addPostProcessor((code) => code.replace(/'JAR'/, "jar"));
1687
+ }
1688
+ if (includeFS) {
1689
+ unshift("const fs = require('fs');");
1690
+ }
1691
+ push(`const options = ${stringifyObject9__default.default(reqOpts, { indent: " ", inlineCharacterLimit: 80 })};`);
1692
+ blank();
1693
+ push("request(options, function (error, response, body) {");
1694
+ push("if (error) throw new Error(error);", 1);
1695
+ blank();
1696
+ push("console.log(body);", 1);
1697
+ push("});");
1698
+ return join();
1699
+ }
1700
+ };
1701
+ var unirest2 = {
1702
+ info: {
1703
+ key: "unirest",
1704
+ title: "Unirest",
1705
+ link: "http://unirest.io/nodejs.html",
1706
+ description: "Lightweight HTTP Request Client Library"
1707
+ },
1708
+ convert: ({ method, url, cookies, queryObj, postData, headersObj }, options) => {
1709
+ const opts = {
1710
+ indent: " ",
1711
+ ...options
1712
+ };
1713
+ let includeFS = false;
1714
+ const { addPostProcessor, blank, join, push, unshift } = new CodeBuilder({
1715
+ indent: opts.indent
1716
+ });
1717
+ push("const unirest = require('unirest');");
1718
+ blank();
1719
+ push(`const req = unirest('${method}', '${url}');`);
1720
+ blank();
1721
+ if (cookies.length) {
1722
+ push("const CookieJar = unirest.jar();");
1723
+ cookies.forEach((cookie) => {
1724
+ push(`CookieJar.add('${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}', '${url}');`);
1725
+ });
1726
+ push("req.jar(CookieJar);");
1727
+ blank();
1728
+ }
1729
+ if (Object.keys(queryObj).length) {
1730
+ push(`req.query(${stringifyObject9__default.default(queryObj, { indent: opts.indent })});`);
1731
+ blank();
1732
+ }
1733
+ if (Object.keys(headersObj).length) {
1734
+ push(`req.headers(${stringifyObject9__default.default(headersObj, { indent: opts.indent })});`);
1735
+ blank();
1736
+ }
1737
+ switch (postData.mimeType) {
1738
+ case "application/x-www-form-urlencoded":
1739
+ if (postData.paramsObj) {
1740
+ push(`req.form(${stringifyObject9__default.default(postData.paramsObj, { indent: opts.indent })});`);
1741
+ blank();
1742
+ }
1743
+ break;
1744
+ case "application/json":
1745
+ if (postData.jsonObj) {
1746
+ push("req.type('json');");
1747
+ push(`req.send(${stringifyObject9__default.default(postData.jsonObj, { indent: opts.indent })});`);
1748
+ blank();
1749
+ }
1750
+ break;
1751
+ case "multipart/form-data": {
1752
+ if (!postData.params) {
1753
+ break;
1754
+ }
1755
+ const multipart = [];
1756
+ postData.params.forEach((param) => {
1757
+ const part = {};
1758
+ if (param.fileName && !param.value) {
1759
+ includeFS = true;
1760
+ part.body = `fs.createReadStream('${param.fileName}')`;
1761
+ addPostProcessor((code) => code.replace(/'fs\.createReadStream\(\\'(.+)\\'\)'/, "fs.createReadStream('$1')"));
1762
+ } else if (param.value) {
1763
+ part.body = param.value;
1764
+ }
1765
+ if (part.body) {
1766
+ if (param.contentType) {
1767
+ part["content-type"] = param.contentType;
1768
+ }
1769
+ multipart.push(part);
1770
+ }
1771
+ });
1772
+ push(`req.multipart(${stringifyObject9__default.default(multipart, { indent: opts.indent })});`);
1773
+ blank();
1774
+ break;
1775
+ }
1776
+ default:
1777
+ if (postData.text) {
1778
+ push(`req.send(${stringifyObject9__default.default(postData.text, { indent: opts.indent })});`);
1779
+ blank();
1780
+ }
1781
+ }
1782
+ if (includeFS) {
1783
+ unshift("const fs = require('fs');");
1784
+ }
1785
+ push("req.end(function (res) {");
1786
+ push("if (res.error) throw new Error(res.error);", 1);
1787
+ blank();
1788
+ push("console.log(res.body);", 1);
1789
+ push("});");
1790
+ return join();
1791
+ }
1792
+ };
1793
+
1794
+ // src/targets/node/target.ts
1795
+ var node = {
1796
+ info: {
1797
+ key: "node",
1798
+ title: "Node.js",
1799
+ extname: ".js",
1800
+ default: "native",
1801
+ cli: "node %s"
1802
+ },
1803
+ clientsById: {
1804
+ native: native3,
1805
+ request,
1806
+ unirest: unirest2,
1807
+ axios: axios2,
1808
+ fetch: fetch2
1809
+ }
1810
+ };
1811
+
1812
+ // src/targets/objc/helpers.ts
1813
+ var nsDeclaration = (nsClass, name, parameters, indent) => {
1814
+ const opening = `${nsClass} *${name} = `;
1815
+ const literal = literalRepresentation(parameters, indent ? opening.length : void 0);
1816
+ return `${opening}${literal};`;
1817
+ };
1818
+ var literalRepresentation = (value, indentation) => {
1819
+ const join = indentation === void 0 ? ", " : `,
1820
+ ${" ".repeat(indentation)}`;
1821
+ switch (Object.prototype.toString.call(value)) {
1822
+ case "[object Number]":
1823
+ return `@${value}`;
1824
+ case "[object Array]": {
1825
+ const valuesRepresentation = value.map((val) => literalRepresentation(val));
1826
+ return `@[ ${valuesRepresentation.join(join)} ]`;
1827
+ }
1828
+ case "[object Object]": {
1829
+ const keyValuePairs = [];
1830
+ Object.keys(value).forEach((key) => {
1831
+ keyValuePairs.push(`@"${key}": ${literalRepresentation(value[key])}`);
1832
+ });
1833
+ return `@{ ${keyValuePairs.join(join)} }`;
1834
+ }
1835
+ case "[object Boolean]":
1836
+ return value ? "@YES" : "@NO";
1837
+ default:
1838
+ if (value === null || value === void 0) {
1839
+ return "";
1840
+ }
1841
+ return `@"${value.toString().replace(/"/g, '\\"')}"`;
1842
+ }
1843
+ };
1844
+
1845
+ // src/targets/objc/nsurlsession/client.ts
1846
+ var nsurlsession = {
1847
+ info: {
1848
+ key: "nsurlsession",
1849
+ title: "NSURLSession",
1850
+ link: "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html",
1851
+ description: "Foundation's NSURLSession request"
1852
+ },
1853
+ convert: ({ allHeaders, postData, method, fullUrl }, options) => {
1854
+ const opts = {
1855
+ indent: " ",
1856
+ pretty: true,
1857
+ timeout: 10,
1858
+ ...options
1859
+ };
1860
+ const { push, join, blank } = new CodeBuilder({ indent: opts.indent });
1861
+ const req = {
1862
+ hasHeaders: false,
1863
+ hasBody: false
1864
+ };
1865
+ push("#import <Foundation/Foundation.h>");
1866
+ if (Object.keys(allHeaders).length) {
1867
+ req.hasHeaders = true;
1868
+ blank();
1869
+ push(nsDeclaration("NSDictionary", "headers", allHeaders, opts.pretty));
1870
+ }
1871
+ if (postData.text || postData.jsonObj || postData.params) {
1872
+ req.hasBody = true;
1873
+ switch (postData.mimeType) {
1874
+ case "application/x-www-form-urlencoded":
1875
+ if (postData.params?.length) {
1876
+ blank();
1877
+ const [head, ...tail] = postData.params;
1878
+ push(
1879
+ `NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"${head.name}=${head.value}" dataUsingEncoding:NSUTF8StringEncoding]];`
1880
+ );
1881
+ tail.forEach(({ name, value }) => {
1882
+ push(`[postData appendData:[@"&${name}=${value}" dataUsingEncoding:NSUTF8StringEncoding]];`);
95
1883
  });
96
- if (cookies === null || cookies === void 0 ? void 0 : cookies.length) {
97
- request.allHeaders.cookie = cookies.join('; ');
1884
+ } else {
1885
+ req.hasBody = false;
1886
+ }
1887
+ break;
1888
+ case "application/json":
1889
+ if (postData.jsonObj) {
1890
+ push(nsDeclaration("NSDictionary", "parameters", postData.jsonObj, opts.pretty));
1891
+ blank();
1892
+ push("NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];");
1893
+ }
1894
+ break;
1895
+ case "multipart/form-data":
1896
+ push(nsDeclaration("NSArray", "parameters", postData.params || [], opts.pretty));
1897
+ push(`NSString *boundary = @"${postData.boundary}";`);
1898
+ blank();
1899
+ push("NSError *error;");
1900
+ push("NSMutableString *body = [NSMutableString string];");
1901
+ push("for (NSDictionary *param in parameters) {");
1902
+ push('[body appendFormat:@"--%@\\r\\n", boundary];', 1);
1903
+ push('if (param[@"fileName"]) {', 1);
1904
+ push(
1905
+ '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];',
1906
+ 2
1907
+ );
1908
+ push('[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];', 2);
1909
+ push(
1910
+ '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];',
1911
+ 2
1912
+ );
1913
+ push("if (error) {", 2);
1914
+ push('NSLog(@"%@", error);', 3);
1915
+ push("}", 2);
1916
+ push("} else {", 1);
1917
+ push('[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];', 2);
1918
+ push('[body appendFormat:@"%@", param[@"value"]];', 2);
1919
+ push("}", 1);
1920
+ push("}");
1921
+ push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];');
1922
+ push("NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];");
1923
+ break;
1924
+ default:
1925
+ blank();
1926
+ push(
1927
+ `NSData *postData = [[NSData alloc] initWithData:[@"${postData.text}" dataUsingEncoding:NSUTF8StringEncoding]];`
1928
+ );
1929
+ }
1930
+ }
1931
+ blank();
1932
+ push(`NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"${fullUrl}"]`);
1933
+ push(" cachePolicy:NSURLRequestUseProtocolCachePolicy");
1934
+ push(` timeoutInterval:${opts.timeout.toFixed(1)}];`);
1935
+ push(`[request setHTTPMethod:@"${method}"];`);
1936
+ if (req.hasHeaders) {
1937
+ push("[request setAllHTTPHeaderFields:headers];");
1938
+ }
1939
+ if (req.hasBody) {
1940
+ push("[request setHTTPBody:postData];");
1941
+ }
1942
+ blank();
1943
+ push("NSURLSession *session = [NSURLSession sharedSession];");
1944
+ push("NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request");
1945
+ push(
1946
+ " completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {"
1947
+ );
1948
+ push(" if (error) {", 1);
1949
+ push(' NSLog(@"%@", error);', 2);
1950
+ push(" } else {", 1);
1951
+ push(
1952
+ " NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;",
1953
+ 2
1954
+ );
1955
+ push(' NSLog(@"%@", httpResponse);', 2);
1956
+ push(" }", 1);
1957
+ push(" }];");
1958
+ push("[dataTask resume];");
1959
+ return join();
1960
+ }
1961
+ };
1962
+
1963
+ // src/targets/objc/target.ts
1964
+ var objc = {
1965
+ info: {
1966
+ key: "objc",
1967
+ title: "Objective-C",
1968
+ extname: ".m",
1969
+ default: "nsurlsession"
1970
+ },
1971
+ clientsById: {
1972
+ nsurlsession
1973
+ }
1974
+ };
1975
+
1976
+ // src/targets/ocaml/cohttp/client.ts
1977
+ var cohttp = {
1978
+ info: {
1979
+ key: "cohttp",
1980
+ title: "CoHTTP",
1981
+ link: "https://github.com/mirage/ocaml-cohttp",
1982
+ description: "Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml"
1983
+ },
1984
+ convert: ({ fullUrl, allHeaders, postData, method }, options) => {
1985
+ const opts = {
1986
+ indent: " ",
1987
+ ...options
1988
+ };
1989
+ const methods = ["get", "post", "head", "delete", "patch", "put", "options"];
1990
+ const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
1991
+ push("open Cohttp_lwt_unix");
1992
+ push("open Cohttp");
1993
+ push("open Lwt");
1994
+ blank();
1995
+ push(`let uri = Uri.of_string "${fullUrl}" in`);
1996
+ const headers = Object.keys(allHeaders);
1997
+ if (headers.length === 1) {
1998
+ push(
1999
+ `let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(
2000
+ allHeaders[headers[0]]
2001
+ )}" in`
2002
+ );
2003
+ } else if (headers.length > 1) {
2004
+ push("let headers = Header.add_list (Header.init ()) [");
2005
+ headers.forEach((key) => {
2006
+ push(`("${key}", "${escapeForDoubleQuotes(allHeaders[key])}");`, 1);
2007
+ });
2008
+ push("] in");
2009
+ }
2010
+ if (postData.text) {
2011
+ push(`let body = Cohttp_lwt_body.of_string ${JSON.stringify(postData.text)} in`);
2012
+ }
2013
+ blank();
2014
+ const h = headers.length ? "~headers " : "";
2015
+ const b = postData.text ? "~body " : "";
2016
+ const m = methods.includes(method.toLowerCase()) ? `\`${method.toUpperCase()}` : `(Code.method_of_string "${method}")`;
2017
+ push(`Client.call ${h}${b}${m} uri`);
2018
+ push(">>= fun (res, body_stream) ->");
2019
+ push("(* Do stuff with the result *)", 1);
2020
+ return join();
2021
+ }
2022
+ };
2023
+
2024
+ // src/targets/ocaml/target.ts
2025
+ var ocaml = {
2026
+ info: {
2027
+ key: "ocaml",
2028
+ title: "OCaml",
2029
+ extname: ".ml",
2030
+ default: "cohttp"
2031
+ },
2032
+ clientsById: {
2033
+ cohttp
2034
+ }
2035
+ };
2036
+
2037
+ // src/targets/php/helpers.ts
2038
+ var convertType = (obj, indent, lastIndent) => {
2039
+ lastIndent = lastIndent || "";
2040
+ indent = indent || "";
2041
+ switch (Object.prototype.toString.call(obj)) {
2042
+ case "[object Boolean]":
2043
+ return obj;
2044
+ case "[object Null]":
2045
+ return "null";
2046
+ case "[object Undefined]":
2047
+ return "null";
2048
+ case "[object String]":
2049
+ return `'${escapeString(obj, { delimiter: "'", escapeNewlines: false })}'`;
2050
+ case "[object Number]":
2051
+ return obj.toString();
2052
+ case "[object Array]": {
2053
+ const contents = obj.map((item) => convertType(item, `${indent}${indent}`, indent)).join(`,
2054
+ ${indent}`);
2055
+ return `[
2056
+ ${indent}${contents}
2057
+ ${lastIndent}]`;
2058
+ }
2059
+ case "[object Object]": {
2060
+ const result = [];
2061
+ for (const i in obj) {
2062
+ if (Object.prototype.hasOwnProperty.call(obj, i)) {
2063
+ result.push(`${convertType(i, indent)} => ${convertType(obj[i], `${indent}${indent}`, indent)}`);
2064
+ }
2065
+ }
2066
+ return `[
2067
+ ${indent}${result.join(`,
2068
+ ${indent}`)}
2069
+ ${lastIndent}]`;
2070
+ }
2071
+ default:
2072
+ return "null";
2073
+ }
2074
+ };
2075
+ var supportedMethods = [
2076
+ "ACL",
2077
+ "BASELINE_CONTROL",
2078
+ "CHECKIN",
2079
+ "CHECKOUT",
2080
+ "CONNECT",
2081
+ "COPY",
2082
+ "DELETE",
2083
+ "GET",
2084
+ "HEAD",
2085
+ "LABEL",
2086
+ "LOCK",
2087
+ "MERGE",
2088
+ "MKACTIVITY",
2089
+ "MKCOL",
2090
+ "MKWORKSPACE",
2091
+ "MOVE",
2092
+ "OPTIONS",
2093
+ "POST",
2094
+ "PROPFIND",
2095
+ "PROPPATCH",
2096
+ "PUT",
2097
+ "REPORT",
2098
+ "TRACE",
2099
+ "UNCHECKOUT",
2100
+ "UNLOCK",
2101
+ "UPDATE",
2102
+ "VERSION_CONTROL"
2103
+ ];
2104
+
2105
+ // src/targets/php/curl/client.ts
2106
+ var curl = {
2107
+ info: {
2108
+ key: "curl",
2109
+ title: "cURL",
2110
+ link: "http://php.net/manual/en/book.curl.php",
2111
+ description: "PHP with ext-curl"
2112
+ },
2113
+ convert: ({ uriObj, postData, fullUrl, method, httpVersion, cookies, headersObj }, options = {}) => {
2114
+ const {
2115
+ closingTag = false,
2116
+ indent = " ",
2117
+ maxRedirects = 10,
2118
+ namedErrors = false,
2119
+ noTags = false,
2120
+ shortTags = false,
2121
+ timeout = 30
2122
+ } = options;
2123
+ const { push, blank, join } = new CodeBuilder({ indent });
2124
+ if (!noTags) {
2125
+ push(shortTags ? "<?" : "<?php");
2126
+ blank();
2127
+ }
2128
+ push("$curl = curl_init();");
2129
+ blank();
2130
+ const curlOptions = [
2131
+ {
2132
+ escape: true,
2133
+ name: "CURLOPT_PORT",
2134
+ value: uriObj.port
2135
+ },
2136
+ {
2137
+ escape: true,
2138
+ name: "CURLOPT_URL",
2139
+ value: fullUrl
2140
+ },
2141
+ {
2142
+ escape: false,
2143
+ name: "CURLOPT_RETURNTRANSFER",
2144
+ value: "true"
2145
+ },
2146
+ {
2147
+ escape: true,
2148
+ name: "CURLOPT_ENCODING",
2149
+ value: ""
2150
+ },
2151
+ {
2152
+ escape: false,
2153
+ name: "CURLOPT_MAXREDIRS",
2154
+ value: maxRedirects
2155
+ },
2156
+ {
2157
+ escape: false,
2158
+ name: "CURLOPT_TIMEOUT",
2159
+ value: timeout
2160
+ },
2161
+ {
2162
+ escape: false,
2163
+ name: "CURLOPT_HTTP_VERSION",
2164
+ value: httpVersion === "HTTP/1.0" ? "CURL_HTTP_VERSION_1_0" : "CURL_HTTP_VERSION_1_1"
2165
+ },
2166
+ {
2167
+ escape: true,
2168
+ name: "CURLOPT_CUSTOMREQUEST",
2169
+ value: method
2170
+ },
2171
+ {
2172
+ escape: !postData.jsonObj,
2173
+ name: "CURLOPT_POSTFIELDS",
2174
+ value: postData ? postData.jsonObj ? `json_encode(${convertType(postData.jsonObj, indent.repeat(2), indent)})` : postData.text : void 0
2175
+ }
2176
+ ];
2177
+ push("curl_setopt_array($curl, [");
2178
+ const curlopts = new CodeBuilder({ indent, join: `
2179
+ ${indent}` });
2180
+ curlOptions.forEach(({ value, name, escape: escape2 }) => {
2181
+ if (value !== null && value !== void 0) {
2182
+ curlopts.push(`${name} => ${escape2 ? JSON.stringify(value) : value},`);
2183
+ }
2184
+ });
2185
+ const curlCookies = cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`);
2186
+ if (curlCookies.length) {
2187
+ curlopts.push(`CURLOPT_COOKIE => "${curlCookies.join("; ")}",`);
2188
+ }
2189
+ const headers = Object.keys(headersObj).sort().map((key) => `"${key}: ${escapeForDoubleQuotes(headersObj[key])}"`);
2190
+ if (headers.length) {
2191
+ curlopts.push("CURLOPT_HTTPHEADER => [");
2192
+ curlopts.push(headers.join(`,
2193
+ ${indent}${indent}`), 1);
2194
+ curlopts.push("],");
2195
+ }
2196
+ push(curlopts.join(), 1);
2197
+ push("]);");
2198
+ blank();
2199
+ push("$response = curl_exec($curl);");
2200
+ push("$err = curl_error($curl);");
2201
+ blank();
2202
+ push("curl_close($curl);");
2203
+ blank();
2204
+ push("if ($err) {");
2205
+ if (namedErrors) {
2206
+ push('echo array_flip(get_defined_constants(true)["curl"])[$err];', 1);
2207
+ } else {
2208
+ push('echo "cURL Error #:" . $err;', 1);
2209
+ }
2210
+ push("} else {");
2211
+ push("echo $response;", 1);
2212
+ push("}");
2213
+ if (!noTags && closingTag) {
2214
+ blank();
2215
+ push("?>");
2216
+ }
2217
+ return join();
2218
+ }
2219
+ };
2220
+
2221
+ // src/targets/php/guzzle/client.ts
2222
+ var guzzle = {
2223
+ info: {
2224
+ key: "guzzle",
2225
+ title: "Guzzle",
2226
+ link: "http://docs.guzzlephp.org/en/stable/",
2227
+ description: "PHP with Guzzle"
2228
+ },
2229
+ convert: ({ postData, fullUrl, method, cookies, headersObj }, options) => {
2230
+ const opts = {
2231
+ closingTag: false,
2232
+ indent: " ",
2233
+ noTags: false,
2234
+ shortTags: false,
2235
+ ...options
2236
+ };
2237
+ const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
2238
+ const { code: requestCode, push: requestPush, join: requestJoin } = new CodeBuilder({ indent: opts.indent });
2239
+ if (!opts.noTags) {
2240
+ push(opts.shortTags ? "<?" : "<?php");
2241
+ }
2242
+ push("require_once('vendor/autoload.php');");
2243
+ blank();
2244
+ switch (postData.mimeType) {
2245
+ case "application/x-www-form-urlencoded":
2246
+ requestPush(`'form_params' => ${convertType(postData.paramsObj, opts.indent + opts.indent, opts.indent)},`, 1);
2247
+ break;
2248
+ case "multipart/form-data": {
2249
+ const fields = [];
2250
+ if (postData.params) {
2251
+ postData.params.forEach((param) => {
2252
+ if (param.fileName) {
2253
+ const field = {
2254
+ name: param.name,
2255
+ filename: param.fileName,
2256
+ contents: param.value
2257
+ };
2258
+ if (param.contentType) {
2259
+ field.headers = { "Content-Type": param.contentType };
2260
+ }
2261
+ fields.push(field);
2262
+ } else if (param.value) {
2263
+ fields.push({
2264
+ name: param.name,
2265
+ contents: param.value
2266
+ });
98
2267
  }
99
- switch (request.postData.mimeType) {
100
- case 'multipart/mixed':
101
- case 'multipart/related':
102
- case 'multipart/form-data':
103
- case 'multipart/alternative':
104
- // reset values
105
- request.postData.text = '';
106
- request.postData.mimeType = 'multipart/form-data';
107
- if ((_c = request.postData) === null || _c === void 0 ? void 0 : _c.params) {
108
- var form_1 = new form_data_1.default();
109
- // The `form-data` module returns one of two things: a native FormData object, or its own polyfill
110
- // Since the polyfill does not support the full API of the native FormData object, when this library is running in a browser environment it'll fail on two things:
111
- //
112
- // 1. The API for `form.append()` has three arguments and the third should only be present when the second is a
113
- // Blob or USVString.
114
- // 1. `FormData.pipe()` isn't a function.
115
- //
116
- // Since the native FormData object is iterable, we easily detect what version of `form-data` we're working with here to allow `multipart/form-data` requests to be compiled under both browser and Node environments.
117
- //
118
- // This hack is pretty awful but it's the only way we can use this library in the browser as if we code this against just the native FormData object, we can't polyfill that back into Node because Blob and File objects, which something like `formdata-polyfill` requires, don't exist there.
119
- // @ts-expect-error TODO
120
- var isNativeFormData_1 = typeof form_1[Symbol.iterator] === 'function';
121
- // TODO: THIS ABSOLUTELY MUST BE REMOVED.
122
- // IT BREAKS SOME USE-CASES FOR MULTIPART FORMS THAT DEPEND ON BEING ABLE TO SET THE BOUNDARY.
123
- // easter egg
124
- var boundary = '---011000010111000001101001'; // this is binary for "api". yep.
125
- if (!isNativeFormData_1) {
126
- // @ts-expect-error THIS IS WRONG. VERY WRONG.
127
- form_1._boundary = boundary;
128
- }
129
- (_d = request.postData) === null || _d === void 0 ? void 0 : _d.params.forEach(function (param) {
130
- var name = param.name;
131
- var value = param.value || '';
132
- var filename = param.fileName || null;
133
- if (isNativeFormData_1) {
134
- if ((0, form_data_2.isBlob)(value)) {
135
- // @ts-expect-error TODO
136
- form_1.append(name, value, filename);
137
- }
138
- else {
139
- form_1.append(name, value);
140
- }
141
- }
142
- else {
143
- form_1.append(name, value, {
144
- // @ts-expect-error TODO
145
- filename: filename,
146
- // @ts-expect-error TODO
147
- contentType: param.contentType || null,
148
- });
149
- }
150
- });
151
- if (isNativeFormData_1) {
152
- try {
153
- // eslint-disable-next-line no-restricted-syntax
154
- for (var _e = __values((0, form_data_2.formDataIterator)(form_1, boundary)), _f = _e.next(); !_f.done; _f = _e.next()) {
155
- var data_1 = _f.value;
156
- request.postData.text += data_1;
157
- }
158
- }
159
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
160
- finally {
161
- try {
162
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
163
- }
164
- finally { if (e_1) throw e_1.error; }
165
- }
166
- }
167
- else {
168
- form_1.pipe(
169
- // @ts-expect-error TODO
170
- (0, event_stream_1.map)(function (data) {
171
- request.postData.text += data;
172
- }));
173
- }
174
- request.postData.boundary = boundary;
175
- // Since headers are case-sensitive we need to see if there's an existing `Content-Type` header that we can override.
176
- var contentTypeHeader = (0, headers_1.getHeaderName)(request.headersObj, 'content-type') || 'content-type';
177
- request.headersObj[contentTypeHeader] = "multipart/form-data; boundary=".concat(boundary);
178
- }
179
- break;
180
- case 'application/x-www-form-urlencoded':
181
- if (!request.postData.params) {
182
- request.postData.text = '';
183
- }
184
- else {
185
- // @ts-expect-error the `har-format` types make this challenging
186
- request.postData.paramsObj = request.postData.params.reduce(reducer_1.reducer, {});
187
- // always overwrite
188
- request.postData.text = (0, qs_1.stringify)(request.postData.paramsObj);
189
- }
190
- break;
191
- case 'text/json':
192
- case 'text/x-json':
193
- case 'application/json':
194
- case 'application/x-json':
195
- request.postData.mimeType = 'application/json';
196
- if (request.postData.text) {
197
- try {
198
- request.postData.jsonObj = JSON.parse(request.postData.text);
199
- }
200
- catch (e) {
201
- debug.info(e);
202
- // force back to `text/plain` if headers have proper content-type value, then this should also work
203
- request.postData.mimeType = 'text/plain';
204
- }
205
- }
206
- break;
2268
+ });
2269
+ }
2270
+ if (fields.length) {
2271
+ requestPush(`'multipart' => ${convertType(fields, opts.indent + opts.indent, opts.indent)}`, 1);
2272
+ if (hasHeader(headersObj, "content-type")) {
2273
+ if (getHeader2(headersObj, "content-type")?.indexOf("boundary")) {
2274
+ const headerName = getHeaderName(headersObj, "content-type");
2275
+ if (headerName) {
2276
+ delete headersObj[headerName];
2277
+ }
207
2278
  }
208
- // create allHeaders object
209
- var allHeaders = __assign(__assign({}, request.allHeaders), request.headersObj);
210
- var urlWithParsedQuery = (0, url_1.parse)(request.url, true, true); //?
211
- // query string key/value pairs in with literal querystrings containd within the url
212
- request.queryObj = __assign(__assign({}, request.queryObj), urlWithParsedQuery.query); //?
213
- // reset uriObj values for a clean url
214
- var search;
215
- if (options.harIsAlreadyEncoded) {
216
- search = (0, qs_1.stringify)(request.queryObj, {
217
- encode: false,
218
- indices: false,
219
- });
2279
+ }
2280
+ }
2281
+ break;
2282
+ }
2283
+ default:
2284
+ if (postData.text) {
2285
+ requestPush(`'body' => ${convertType(postData.text)},`, 1);
2286
+ }
2287
+ }
2288
+ const headers = Object.keys(headersObj).sort().map(function(key) {
2289
+ return `${opts.indent}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`;
2290
+ });
2291
+ const cookieString = cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`).join("; ");
2292
+ if (cookieString.length) {
2293
+ headers.push(`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`);
2294
+ }
2295
+ if (headers.length) {
2296
+ requestPush("'headers' => [", 1);
2297
+ requestPush(headers.join("\n"));
2298
+ requestPush("],", 1);
2299
+ }
2300
+ push("$client = new \\GuzzleHttp\\Client();");
2301
+ blank();
2302
+ if (requestCode.length) {
2303
+ push(`$response = $client->request('${method}', '${fullUrl}', [`);
2304
+ push(requestJoin());
2305
+ push("]);");
2306
+ } else {
2307
+ push(`$response = $client->request('${method}', '${fullUrl}');`);
2308
+ }
2309
+ blank();
2310
+ push("echo $response->getBody();");
2311
+ if (!opts.noTags && opts.closingTag) {
2312
+ blank();
2313
+ push("?>");
2314
+ }
2315
+ return join();
2316
+ }
2317
+ };
2318
+
2319
+ // src/targets/php/http1/client.ts
2320
+ var http1 = {
2321
+ info: {
2322
+ key: "http1",
2323
+ title: "HTTP v1",
2324
+ link: "http://php.net/manual/en/book.http.php",
2325
+ description: "PHP with pecl/http v1"
2326
+ },
2327
+ convert: ({ method, url, postData, queryObj, headersObj, cookiesObj }, options = {}) => {
2328
+ const { closingTag = false, indent = " ", noTags = false, shortTags = false } = options;
2329
+ const { push, blank, join } = new CodeBuilder({ indent });
2330
+ if (!noTags) {
2331
+ push(shortTags ? "<?" : "<?php");
2332
+ blank();
2333
+ }
2334
+ if (!supportedMethods.includes(method.toUpperCase())) {
2335
+ push(`HttpRequest::methodRegister('${method}');`);
2336
+ }
2337
+ push("$request = new HttpRequest();");
2338
+ push(`$request->setUrl(${convertType(url)});`);
2339
+ if (supportedMethods.includes(method.toUpperCase())) {
2340
+ push(`$request->setMethod(HTTP_METH_${method.toUpperCase()});`);
2341
+ } else {
2342
+ push(`$request->setMethod(HttpRequest::HTTP_METH_${method.toUpperCase()});`);
2343
+ }
2344
+ blank();
2345
+ if (Object.keys(queryObj).length) {
2346
+ push(`$request->setQueryData(${convertType(queryObj, indent)});`);
2347
+ blank();
2348
+ }
2349
+ if (Object.keys(headersObj).length) {
2350
+ push(`$request->setHeaders(${convertType(headersObj, indent)});`);
2351
+ blank();
2352
+ }
2353
+ if (Object.keys(cookiesObj).length) {
2354
+ push(`$request->setCookies(${convertType(cookiesObj, indent)});`);
2355
+ blank();
2356
+ }
2357
+ switch (postData.mimeType) {
2358
+ case "application/x-www-form-urlencoded":
2359
+ push(`$request->setContentType(${convertType(postData.mimeType)});`);
2360
+ push(`$request->setPostFields(${convertType(postData.paramsObj, indent)});`);
2361
+ blank();
2362
+ break;
2363
+ case "application/json":
2364
+ push(`$request->setContentType(${convertType(postData.mimeType)});`);
2365
+ push(`$request->setBody(json_encode(${convertType(postData.jsonObj, indent)}));`);
2366
+ blank();
2367
+ break;
2368
+ default:
2369
+ if (postData.text) {
2370
+ push(`$request->setBody(${convertType(postData.text)});`);
2371
+ blank();
2372
+ }
2373
+ }
2374
+ push("try {");
2375
+ push("$response = $request->send();", 1);
2376
+ blank();
2377
+ push("echo $response->getBody();", 1);
2378
+ push("} catch (HttpException $ex) {");
2379
+ push("echo $ex;", 1);
2380
+ push("}");
2381
+ if (!noTags && closingTag) {
2382
+ blank();
2383
+ push("?>");
2384
+ }
2385
+ return join();
2386
+ }
2387
+ };
2388
+
2389
+ // src/targets/php/http2/client.ts
2390
+ var http2 = {
2391
+ info: {
2392
+ key: "http2",
2393
+ title: "HTTP v2",
2394
+ link: "http://devel-m6w6.rhcloud.com/mdref/http",
2395
+ description: "PHP with pecl/http v2"
2396
+ },
2397
+ convert: ({ postData, headersObj, method, queryObj, cookiesObj, url }, options = {}) => {
2398
+ const { closingTag = false, indent = " ", noTags = false, shortTags = false } = options;
2399
+ const { push, blank, join } = new CodeBuilder({ indent });
2400
+ let hasBody = false;
2401
+ if (!noTags) {
2402
+ push(shortTags ? "<?" : "<?php");
2403
+ blank();
2404
+ }
2405
+ push("$client = new http\\Client;");
2406
+ push("$request = new http\\Client\\Request;");
2407
+ blank();
2408
+ switch (postData.mimeType) {
2409
+ case "application/x-www-form-urlencoded":
2410
+ push("$body = new http\\Message\\Body;");
2411
+ push(`$body->append(new http\\QueryString(${convertType(postData.paramsObj, indent)}));`);
2412
+ blank();
2413
+ hasBody = true;
2414
+ break;
2415
+ case "multipart/form-data": {
2416
+ if (!postData.params) {
2417
+ break;
2418
+ }
2419
+ const files = [];
2420
+ const fields = {};
2421
+ postData.params.forEach(({ name, fileName, value, contentType }) => {
2422
+ if (fileName) {
2423
+ files.push({
2424
+ name,
2425
+ type: contentType,
2426
+ file: fileName,
2427
+ data: value
2428
+ });
2429
+ return;
2430
+ }
2431
+ if (value) {
2432
+ fields[name] = value;
2433
+ }
2434
+ });
2435
+ const field = Object.keys(fields).length ? convertType(fields, indent) : "null";
2436
+ const formValue = files.length ? convertType(files, indent) : "null";
2437
+ push("$body = new http\\Message\\Body;");
2438
+ push(`$body->addForm(${field}, ${formValue});`);
2439
+ if (hasHeader(headersObj, "content-type")) {
2440
+ if (getHeader2(headersObj, "content-type")?.indexOf("boundary")) {
2441
+ const headerName = getHeaderName(headersObj, "content-type");
2442
+ if (headerName) {
2443
+ delete headersObj[headerName];
220
2444
  }
221
- else {
222
- search = (0, qs_1.stringify)(request.queryObj, {
223
- indices: false,
224
- });
2445
+ }
2446
+ }
2447
+ blank();
2448
+ hasBody = true;
2449
+ break;
2450
+ }
2451
+ case "application/json":
2452
+ push("$body = new http\\Message\\Body;");
2453
+ push(`$body->append(json_encode(${convertType(postData.jsonObj, indent)}));`);
2454
+ hasBody = true;
2455
+ break;
2456
+ default:
2457
+ if (postData.text) {
2458
+ push("$body = new http\\Message\\Body;");
2459
+ push(`$body->append(${convertType(postData.text)});`);
2460
+ blank();
2461
+ hasBody = true;
2462
+ }
2463
+ }
2464
+ push(`$request->setRequestUrl(${convertType(url)});`);
2465
+ push(`$request->setRequestMethod(${convertType(method)});`);
2466
+ if (hasBody) {
2467
+ push("$request->setBody($body);");
2468
+ blank();
2469
+ }
2470
+ if (Object.keys(queryObj).length) {
2471
+ push(`$request->setQuery(new http\\QueryString(${convertType(queryObj, indent)}));`);
2472
+ blank();
2473
+ }
2474
+ if (Object.keys(headersObj).length) {
2475
+ push(`$request->setHeaders(${convertType(headersObj, indent)});`);
2476
+ blank();
2477
+ }
2478
+ if (Object.keys(cookiesObj).length) {
2479
+ blank();
2480
+ push(`$client->setCookies(${convertType(cookiesObj, indent)});`);
2481
+ blank();
2482
+ }
2483
+ push("$client->enqueue($request)->send();");
2484
+ push("$response = $client->getResponse();");
2485
+ blank();
2486
+ push("echo $response->getBody();");
2487
+ if (!noTags && closingTag) {
2488
+ blank();
2489
+ push("?>");
2490
+ }
2491
+ return join();
2492
+ }
2493
+ };
2494
+
2495
+ // src/targets/php/target.ts
2496
+ var php = {
2497
+ info: {
2498
+ key: "php",
2499
+ title: "PHP",
2500
+ extname: ".php",
2501
+ default: "curl",
2502
+ cli: "php %s"
2503
+ },
2504
+ clientsById: {
2505
+ curl,
2506
+ guzzle,
2507
+ http1,
2508
+ http2
2509
+ }
2510
+ };
2511
+
2512
+ // src/targets/powershell/common.ts
2513
+ var generatePowershellConvert = (command) => {
2514
+ const convert = ({ method, headersObj, cookies, uriObj, fullUrl, postData, allHeaders }) => {
2515
+ const { push, join } = new CodeBuilder();
2516
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
2517
+ if (!methods.includes(method.toUpperCase())) {
2518
+ return "Method not supported";
2519
+ }
2520
+ const commandOptions = [];
2521
+ const headers = Object.keys(headersObj);
2522
+ if (headers.length) {
2523
+ push("$headers=@{}");
2524
+ headers.forEach((key) => {
2525
+ if (key !== "connection") {
2526
+ push(`$headers.Add("${key}", "${escapeString(headersObj[key], { escapeChar: "`" })}")`);
2527
+ }
2528
+ });
2529
+ commandOptions.push("-Headers $headers");
2530
+ }
2531
+ if (cookies.length) {
2532
+ push("$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession");
2533
+ cookies.forEach((cookie) => {
2534
+ push("$cookie = New-Object System.Net.Cookie");
2535
+ push(`$cookie.Name = '${cookie.name}'`);
2536
+ push(`$cookie.Value = '${cookie.value}'`);
2537
+ push(`$cookie.Domain = '${uriObj.host}'`);
2538
+ push("$session.Cookies.Add($cookie)");
2539
+ });
2540
+ commandOptions.push("-WebSession $session");
2541
+ }
2542
+ if (postData.text) {
2543
+ commandOptions.push(
2544
+ `-ContentType '${escapeString(getHeader2(allHeaders, "content-type"), { delimiter: "'", escapeChar: "`" })}'`
2545
+ );
2546
+ commandOptions.push(`-Body '${postData.text}'`);
2547
+ }
2548
+ push(`$response = ${command} -Uri '${fullUrl}' -Method ${method} ${commandOptions.join(" ")}`.trim());
2549
+ return join();
2550
+ };
2551
+ return convert;
2552
+ };
2553
+
2554
+ // src/targets/powershell/restmethod/client.ts
2555
+ var restmethod = {
2556
+ info: {
2557
+ key: "restmethod",
2558
+ title: "Invoke-RestMethod",
2559
+ link: "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-RestMethod",
2560
+ description: "Powershell Invoke-RestMethod client"
2561
+ },
2562
+ convert: generatePowershellConvert("Invoke-RestMethod")
2563
+ };
2564
+
2565
+ // src/targets/powershell/webrequest/client.ts
2566
+ var webrequest = {
2567
+ info: {
2568
+ key: "webrequest",
2569
+ title: "Invoke-WebRequest",
2570
+ link: "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest",
2571
+ description: "Powershell Invoke-WebRequest client"
2572
+ },
2573
+ convert: generatePowershellConvert("Invoke-WebRequest")
2574
+ };
2575
+
2576
+ // src/targets/powershell/target.ts
2577
+ var powershell = {
2578
+ info: {
2579
+ key: "powershell",
2580
+ title: "Powershell",
2581
+ extname: ".ps1",
2582
+ default: "webrequest"
2583
+ },
2584
+ clientsById: {
2585
+ webrequest,
2586
+ restmethod
2587
+ }
2588
+ };
2589
+
2590
+ // src/targets/python/helpers.ts
2591
+ function concatValues(concatType, values, pretty, indentation, indentLevel) {
2592
+ const currentIndent = indentation.repeat(indentLevel);
2593
+ const closingBraceIndent = indentation.repeat(indentLevel - 1);
2594
+ const join = pretty ? `,
2595
+ ${currentIndent}` : ", ";
2596
+ const openingBrace = concatType === "object" ? "{" : "[";
2597
+ const closingBrace = concatType === "object" ? "}" : "]";
2598
+ if (pretty) {
2599
+ return `${openingBrace}
2600
+ ${currentIndent}${values.join(join)}
2601
+ ${closingBraceIndent}${closingBrace}`;
2602
+ }
2603
+ if (concatType === "object" && values.length > 0) {
2604
+ return `${openingBrace} ${values.join(join)} ${closingBrace}`;
2605
+ }
2606
+ return `${openingBrace}${values.join(join)}${closingBrace}`;
2607
+ }
2608
+ var literalRepresentation2 = (value, opts, indentLevel) => {
2609
+ indentLevel = indentLevel === void 0 ? 1 : indentLevel + 1;
2610
+ switch (Object.prototype.toString.call(value)) {
2611
+ case "[object Number]":
2612
+ return value;
2613
+ case "[object Array]": {
2614
+ let pretty = false;
2615
+ const valuesRepresentation = value.map((v) => {
2616
+ if (Object.prototype.toString.call(v) === "[object Object]") {
2617
+ pretty = Object.keys(v).length > 1;
2618
+ }
2619
+ return literalRepresentation2(v, opts, indentLevel);
2620
+ });
2621
+ return concatValues("array", valuesRepresentation, pretty, opts.indent, indentLevel);
2622
+ }
2623
+ case "[object Object]": {
2624
+ const keyValuePairs = [];
2625
+ for (const key in value) {
2626
+ keyValuePairs.push(`"${key}": ${literalRepresentation2(value[key], opts, indentLevel)}`);
2627
+ }
2628
+ return concatValues("object", keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel);
2629
+ }
2630
+ case "[object Null]":
2631
+ return "None";
2632
+ case "[object Boolean]":
2633
+ return value ? "True" : "False";
2634
+ default:
2635
+ if (value === null || value === void 0) {
2636
+ return "";
2637
+ }
2638
+ return `"${value.toString().replace(/"/g, '\\"')}"`;
2639
+ }
2640
+ };
2641
+
2642
+ // src/targets/python/requests/client.ts
2643
+ var builtInMethods = ["HEAD", "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
2644
+ var requests = {
2645
+ info: {
2646
+ key: "requests",
2647
+ title: "Requests",
2648
+ link: "http://docs.python-requests.org/en/latest/api/#requests.request",
2649
+ description: "Requests HTTP library"
2650
+ },
2651
+ convert: ({ fullUrl, postData, allHeaders, method }, options) => {
2652
+ const opts = {
2653
+ indent: " ",
2654
+ pretty: true,
2655
+ ...options
2656
+ };
2657
+ const { push, blank, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent });
2658
+ push("import requests");
2659
+ blank();
2660
+ push(`url = "${fullUrl}"`);
2661
+ blank();
2662
+ const headers = allHeaders;
2663
+ let payload = {};
2664
+ const files = {};
2665
+ let hasFiles = false;
2666
+ let hasPayload = false;
2667
+ let jsonPayload = false;
2668
+ switch (postData.mimeType) {
2669
+ case "application/json":
2670
+ if (postData.jsonObj) {
2671
+ push(`payload = ${literalRepresentation2(postData.jsonObj, opts)}`);
2672
+ jsonPayload = true;
2673
+ hasPayload = true;
2674
+ }
2675
+ break;
2676
+ case "multipart/form-data":
2677
+ if (!postData.params) {
2678
+ break;
2679
+ }
2680
+ payload = {};
2681
+ postData.params.forEach((p) => {
2682
+ if (p.fileName) {
2683
+ if (p.contentType) {
2684
+ files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'), '${p.contentType}')`;
2685
+ } else {
2686
+ files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'))`;
225
2687
  }
226
- var uriObj = __assign(__assign({}, urlWithParsedQuery), { query: request.queryObj, search: search, path: search ? "".concat(urlWithParsedQuery.pathname, "?").concat(search) : urlWithParsedQuery.pathname });
227
- // keep the base url clean of queryString
228
- var url = (0, url_1.format)(__assign(__assign({}, urlWithParsedQuery), { query: null, search: null })); //?
229
- var fullUrl = (0, url_1.format)(__assign(__assign({}, urlWithParsedQuery), uriObj)); //?
230
- return __assign(__assign({}, request), { allHeaders: allHeaders, fullUrl: fullUrl, url: url, uriObj: uriObj });
231
- };
232
- this.convert = function (targetId, clientId, options) {
233
- if (!options && clientId) {
234
- options = clientId;
2688
+ hasFiles = true;
2689
+ } else {
2690
+ payload[p.name] = p.value;
2691
+ hasPayload = true;
2692
+ }
2693
+ });
2694
+ if (hasFiles) {
2695
+ push(`files = ${literalRepresentation2(files, opts)}`);
2696
+ if (hasPayload) {
2697
+ push(`payload = ${literalRepresentation2(payload, opts)}`);
2698
+ }
2699
+ const headerName = getHeaderName(headers, "content-type");
2700
+ if (headerName) {
2701
+ delete headers[headerName];
2702
+ }
2703
+ } else {
2704
+ const nonFilePayload = JSON.stringify(postData.text);
2705
+ if (nonFilePayload) {
2706
+ push(`payload = ${nonFilePayload}`);
2707
+ hasPayload = true;
2708
+ }
2709
+ }
2710
+ addPostProcessor(
2711
+ (code) => code.replace(/"\('(.+)', open\('(.+)', 'rb'\)\)"/g, '("$1", open("$2", "rb"))').replace(/"\('(.+)', open\('(.+)', 'rb'\), '(.+)'\)"/g, '("$1", open("$2", "rb"), "$3")')
2712
+ );
2713
+ break;
2714
+ default: {
2715
+ if (postData.mimeType === "application/x-www-form-urlencoded" && postData.paramsObj) {
2716
+ push(`payload = ${literalRepresentation2(postData.paramsObj, opts)}`);
2717
+ hasPayload = true;
2718
+ break;
2719
+ }
2720
+ const stringPayload = JSON.stringify(postData.text);
2721
+ if (stringPayload) {
2722
+ push(`payload = ${stringPayload}`);
2723
+ hasPayload = true;
2724
+ }
2725
+ }
2726
+ }
2727
+ const headerCount = Object.keys(headers).length;
2728
+ if (headerCount === 0 && (hasPayload || hasFiles)) {
2729
+ blank();
2730
+ } else if (headerCount === 1) {
2731
+ Object.keys(headers).forEach((header) => {
2732
+ push(`headers = {"${header}": "${escapeForDoubleQuotes(headers[header])}"}`);
2733
+ blank();
2734
+ });
2735
+ } else if (headerCount > 1) {
2736
+ let count = 1;
2737
+ push("headers = {");
2738
+ Object.keys(headers).forEach((header) => {
2739
+ if (count !== headerCount) {
2740
+ push(`"${header}": "${escapeForDoubleQuotes(headers[header])}",`, 1);
2741
+ } else {
2742
+ push(`"${header}": "${escapeForDoubleQuotes(headers[header])}"`, 1);
2743
+ }
2744
+ count += 1;
2745
+ });
2746
+ push("}");
2747
+ blank();
2748
+ }
2749
+ let request2 = builtInMethods.includes(method) ? `response = requests.${method.toLowerCase()}(url` : `response = requests.request("${method}", url`;
2750
+ if (hasPayload) {
2751
+ if (jsonPayload) {
2752
+ request2 += ", json=payload";
2753
+ } else {
2754
+ request2 += ", data=payload";
2755
+ }
2756
+ }
2757
+ if (hasFiles) {
2758
+ request2 += ", files=files";
2759
+ }
2760
+ if (headerCount > 0) {
2761
+ request2 += ", headers=headers";
2762
+ }
2763
+ request2 += ")";
2764
+ push(request2);
2765
+ blank();
2766
+ push("print(response.text)");
2767
+ return join();
2768
+ }
2769
+ };
2770
+
2771
+ // src/targets/python/target.ts
2772
+ var python = {
2773
+ info: {
2774
+ key: "python",
2775
+ title: "Python",
2776
+ extname: ".py",
2777
+ default: "requests",
2778
+ cli: "python3 %s"
2779
+ },
2780
+ clientsById: {
2781
+ requests
2782
+ }
2783
+ };
2784
+
2785
+ // src/targets/r/httr/client.ts
2786
+ var httr = {
2787
+ info: {
2788
+ key: "httr",
2789
+ title: "httr",
2790
+ link: "https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html",
2791
+ description: "httr: Tools for Working with URLs and HTTP"
2792
+ },
2793
+ convert: ({ url, queryObj, queryString, postData, allHeaders, method }) => {
2794
+ const { push, blank, join } = new CodeBuilder();
2795
+ push("library(httr)");
2796
+ blank();
2797
+ push(`url <- "${url}"`);
2798
+ blank();
2799
+ const qs = queryObj;
2800
+ delete queryObj.key;
2801
+ const queryCount = Object.keys(qs).length;
2802
+ if (queryString.length === 1) {
2803
+ push(`queryString <- list(${Object.keys(qs)} = "${Object.values(qs).toString()}")`);
2804
+ blank();
2805
+ } else if (queryString.length > 1) {
2806
+ push("queryString <- list(");
2807
+ Object.keys(qs).forEach((query, i) => {
2808
+ if (i !== queryCount - 1) {
2809
+ push(` ${query} = "${qs[query].toString()}",`);
2810
+ } else {
2811
+ push(` ${query} = "${qs[query].toString()}"`);
2812
+ }
2813
+ });
2814
+ push(")");
2815
+ blank();
2816
+ }
2817
+ const payload = JSON.stringify(postData.text);
2818
+ if (payload) {
2819
+ push(`payload <- ${payload}`);
2820
+ blank();
2821
+ }
2822
+ if (postData.text || postData.jsonObj || postData.params) {
2823
+ switch (postData.mimeType) {
2824
+ case "application/x-www-form-urlencoded":
2825
+ push('encode <- "form"');
2826
+ blank();
2827
+ break;
2828
+ case "application/json":
2829
+ push('encode <- "json"');
2830
+ blank();
2831
+ break;
2832
+ case "multipart/form-data":
2833
+ push('encode <- "multipart"');
2834
+ blank();
2835
+ break;
2836
+ default:
2837
+ push('encode <- "raw"');
2838
+ blank();
2839
+ break;
2840
+ }
2841
+ }
2842
+ const cookieHeader = getHeader2(allHeaders, "cookie");
2843
+ const acceptHeader = getHeader2(allHeaders, "accept");
2844
+ const setCookies = cookieHeader ? `set_cookies(\`${String(cookieHeader).replace(/;/g, '", `').replace(/` /g, "`").replace(/[=]/g, '` = "')}")` : void 0;
2845
+ const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : void 0;
2846
+ const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`;
2847
+ const otherHeaders = Object.entries(allHeaders).filter(([key]) => !["cookie", "accept", "content-type"].includes(key.toLowerCase())).map(([key, value]) => `'${key}' = '${escapeForSingleQuotes(value)}'`).join(", ");
2848
+ const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : void 0;
2849
+ let request2 = `response <- VERB("${method}", url`;
2850
+ if (payload) {
2851
+ request2 += ", body = payload";
2852
+ }
2853
+ if (queryString.length) {
2854
+ request2 += ", query = queryString";
2855
+ }
2856
+ const headerAdditions = [setHeaders, setContentType, setAccept, setCookies].filter((x) => !!x).join(", ");
2857
+ if (headerAdditions) {
2858
+ request2 += `, ${headerAdditions}`;
2859
+ }
2860
+ if (postData.text || postData.jsonObj || postData.params) {
2861
+ request2 += ", encode = encode";
2862
+ }
2863
+ request2 += ")";
2864
+ push(request2);
2865
+ blank();
2866
+ push('content(response, "text")');
2867
+ return join();
2868
+ }
2869
+ };
2870
+
2871
+ // src/targets/r/target.ts
2872
+ var r = {
2873
+ info: {
2874
+ key: "r",
2875
+ title: "R",
2876
+ extname: ".r",
2877
+ default: "httr"
2878
+ },
2879
+ clientsById: {
2880
+ httr
2881
+ }
2882
+ };
2883
+
2884
+ // src/targets/ruby/native/client.ts
2885
+ var native4 = {
2886
+ info: {
2887
+ key: "native",
2888
+ title: "net::http",
2889
+ link: "http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html",
2890
+ description: "Ruby HTTP client"
2891
+ },
2892
+ convert: ({ uriObj, method: rawMethod, fullUrl, postData, allHeaders }) => {
2893
+ const { push, blank, join } = new CodeBuilder();
2894
+ push("require 'uri'");
2895
+ push("require 'net/http'");
2896
+ blank();
2897
+ const method = rawMethod.toUpperCase();
2898
+ const methods = [
2899
+ "GET",
2900
+ "POST",
2901
+ "HEAD",
2902
+ "DELETE",
2903
+ "PATCH",
2904
+ "PUT",
2905
+ "OPTIONS",
2906
+ "COPY",
2907
+ "LOCK",
2908
+ "UNLOCK",
2909
+ "MOVE",
2910
+ "TRACE"
2911
+ ];
2912
+ const capMethod = method.charAt(0) + method.substring(1).toLowerCase();
2913
+ if (!methods.includes(method)) {
2914
+ push(`class Net::HTTP::${capMethod} < Net::HTTPRequest`);
2915
+ push(` METHOD = '${method.toUpperCase()}'`);
2916
+ push(` REQUEST_HAS_BODY = '${postData.text ? "true" : "false"}'`);
2917
+ push(" RESPONSE_HAS_BODY = true");
2918
+ push("end");
2919
+ blank();
2920
+ }
2921
+ push(`url = URI("${fullUrl}")`);
2922
+ blank();
2923
+ push("http = Net::HTTP.new(url.host, url.port)");
2924
+ if (uriObj.protocol === "https:") {
2925
+ push("http.use_ssl = true");
2926
+ }
2927
+ blank();
2928
+ push(`request = Net::HTTP::${capMethod}.new(url)`);
2929
+ const headers = Object.keys(allHeaders);
2930
+ if (headers.length) {
2931
+ headers.forEach((key) => {
2932
+ push(`request["${key}"] = '${escapeForSingleQuotes(allHeaders[key])}'`);
2933
+ });
2934
+ }
2935
+ if (postData.text) {
2936
+ push(`request.body = ${JSON.stringify(postData.text)}`);
2937
+ }
2938
+ blank();
2939
+ push("response = http.request(request)");
2940
+ push("puts response.read_body");
2941
+ return join();
2942
+ }
2943
+ };
2944
+
2945
+ // src/targets/ruby/target.ts
2946
+ var ruby = {
2947
+ info: {
2948
+ key: "ruby",
2949
+ title: "Ruby",
2950
+ extname: ".rb",
2951
+ default: "native"
2952
+ },
2953
+ clientsById: {
2954
+ native: native4
2955
+ }
2956
+ };
2957
+
2958
+ // src/helpers/shell.ts
2959
+ var quote = (value = "") => {
2960
+ const safe = /^[a-z0-9-_/.@%^=:]+$/i;
2961
+ const isShellSafe = safe.test(value);
2962
+ if (isShellSafe) {
2963
+ return value;
2964
+ }
2965
+ return `'${value.replace(/'/g, "'\\''")}'`;
2966
+ };
2967
+ var escape = (value) => value.replace(/\r/g, "\\r").replace(/\n/g, "\\n");
2968
+
2969
+ // src/targets/shell/curl/client.ts
2970
+ var params = {
2971
+ "http1.0": "0",
2972
+ "url ": "",
2973
+ cookie: "b",
2974
+ data: "d",
2975
+ form: "F",
2976
+ globoff: "g",
2977
+ header: "H",
2978
+ insecure: "k",
2979
+ request: "X"
2980
+ };
2981
+ var getArg = (short) => (longName) => {
2982
+ if (short) {
2983
+ const shortName = params[longName];
2984
+ if (!shortName) {
2985
+ return "";
2986
+ }
2987
+ return `-${shortName}`;
2988
+ }
2989
+ return `--${longName}`;
2990
+ };
2991
+ var curl2 = {
2992
+ info: {
2993
+ key: "curl",
2994
+ title: "cURL",
2995
+ link: "http://curl.haxx.se/",
2996
+ description: "cURL is a command line tool and library for transferring data with URL syntax"
2997
+ },
2998
+ convert: ({ fullUrl, method, httpVersion, headersObj, allHeaders, postData }, options = {}) => {
2999
+ const { indent = " ", short = false, binary = false, globOff = false } = options;
3000
+ const indentJSON = " ";
3001
+ const { push, join } = new CodeBuilder({
3002
+ ...typeof indent === "string" ? { indent } : {},
3003
+ join: indent !== false ? ` \\
3004
+ ${indent}` : " "
3005
+ });
3006
+ const arg = getArg(short);
3007
+ let formattedUrl = quote(fullUrl);
3008
+ push(`curl ${arg("request")} ${method}`);
3009
+ if (globOff) {
3010
+ formattedUrl = unescape(formattedUrl);
3011
+ push(arg("globoff"));
3012
+ }
3013
+ push(`${arg("url ")}${formattedUrl}`);
3014
+ if (httpVersion === "HTTP/1.0") {
3015
+ push(arg("http1.0"));
3016
+ }
3017
+ if (getHeader2(allHeaders, "accept-encoding")) {
3018
+ push("--compressed");
3019
+ }
3020
+ if (postData.mimeType === "multipart/form-data") {
3021
+ const contentTypeHeaderName = getHeaderName(headersObj, "content-type");
3022
+ if (contentTypeHeaderName) {
3023
+ const contentTypeHeader = headersObj[contentTypeHeaderName];
3024
+ if (contentTypeHeaderName && contentTypeHeader) {
3025
+ const noBoundary = String(contentTypeHeader).replace(/; boundary.+?(?=(;|$))/, "");
3026
+ headersObj[contentTypeHeaderName] = noBoundary;
3027
+ allHeaders[contentTypeHeaderName] = noBoundary;
3028
+ }
3029
+ }
3030
+ }
3031
+ Object.keys(headersObj).sort().forEach((key) => {
3032
+ const header = `${key}: ${headersObj[key]}`;
3033
+ push(`${arg("header")} ${quote(header)}`);
3034
+ });
3035
+ if (allHeaders.cookie) {
3036
+ push(`${arg("cookie")} ${quote(allHeaders.cookie)}`);
3037
+ }
3038
+ switch (postData.mimeType) {
3039
+ case "multipart/form-data":
3040
+ postData.params?.forEach((param) => {
3041
+ let post = "";
3042
+ if (param.fileName) {
3043
+ post = `${param.name}=@${param.fileName}`;
3044
+ } else {
3045
+ post = `${param.name}=${param.value}`;
3046
+ }
3047
+ push(`${arg("form")} ${quote(post)}`);
3048
+ });
3049
+ break;
3050
+ case "application/x-www-form-urlencoded":
3051
+ if (postData.params) {
3052
+ postData.params.forEach((param) => {
3053
+ const unencoded = param.name;
3054
+ const encoded = encodeURIComponent(param.name);
3055
+ const needsEncoding = encoded !== unencoded;
3056
+ const name = needsEncoding ? encoded : unencoded;
3057
+ const flag = binary ? "--data-binary" : `--data${needsEncoding ? "-urlencode" : ""}`;
3058
+ push(`${flag} ${quote(`${name}=${param.value}`)}`);
3059
+ });
3060
+ } else {
3061
+ push(`${binary ? "--data-binary" : arg("data")} ${quote(postData.text)}`);
3062
+ }
3063
+ break;
3064
+ default:
3065
+ if (!postData.text) {
3066
+ break;
3067
+ }
3068
+ let builtPayload = false;
3069
+ if (isMimeTypeJSON(postData.mimeType)) {
3070
+ if (postData.text.length > 20) {
3071
+ try {
3072
+ const jsonPayload = JSON.parse(postData.text);
3073
+ builtPayload = true;
3074
+ if (postData.text.indexOf("'") > 0) {
3075
+ push(
3076
+ `${binary ? "--data-binary" : arg("data")} @- <<EOF
3077
+ ${JSON.stringify(
3078
+ jsonPayload,
3079
+ null,
3080
+ indentJSON
3081
+ )}
3082
+ EOF`
3083
+ );
3084
+ } else {
3085
+ push(
3086
+ `${binary ? "--data-binary" : arg("data")} '
3087
+ ${JSON.stringify(jsonPayload, null, indentJSON)}
3088
+ '`
3089
+ );
3090
+ }
3091
+ } catch (err) {
235
3092
  }
236
- var target = targets_1.targets[targetId];
237
- if (!target) {
238
- return false;
3093
+ }
3094
+ }
3095
+ if (!builtPayload) {
3096
+ push(`${binary ? "--data-binary" : arg("data")} ${quote(postData.text)}`);
3097
+ }
3098
+ }
3099
+ return join();
3100
+ }
3101
+ };
3102
+
3103
+ // src/targets/shell/httpie/client.ts
3104
+ var httpie = {
3105
+ info: {
3106
+ key: "httpie",
3107
+ title: "HTTPie",
3108
+ link: "http://httpie.org/",
3109
+ description: "a CLI, cURL-like tool for humans"
3110
+ },
3111
+ convert: ({ allHeaders, postData, queryObj, fullUrl, method, url }, options) => {
3112
+ const opts = {
3113
+ body: false,
3114
+ cert: false,
3115
+ headers: false,
3116
+ indent: " ",
3117
+ pretty: false,
3118
+ print: false,
3119
+ queryParams: false,
3120
+ short: false,
3121
+ style: false,
3122
+ timeout: false,
3123
+ verbose: false,
3124
+ verify: false,
3125
+ ...options
3126
+ };
3127
+ const { push, join, unshift } = new CodeBuilder({
3128
+ indent: opts.indent,
3129
+ // @ts-expect-error SEEMS LEGIT
3130
+ join: opts.indent !== false ? ` \\
3131
+ ${opts.indent}` : " "
3132
+ });
3133
+ let raw = false;
3134
+ const flags = [];
3135
+ if (opts.headers) {
3136
+ flags.push(opts.short ? "-h" : "--headers");
3137
+ }
3138
+ if (opts.body) {
3139
+ flags.push(opts.short ? "-b" : "--body");
3140
+ }
3141
+ if (opts.verbose) {
3142
+ flags.push(opts.short ? "-v" : "--verbose");
3143
+ }
3144
+ if (opts.print) {
3145
+ flags.push(`${opts.short ? "-p" : "--print"}=${opts.print}`);
3146
+ }
3147
+ if (opts.verify) {
3148
+ flags.push(`--verify=${opts.verify}`);
3149
+ }
3150
+ if (opts.cert) {
3151
+ flags.push(`--cert=${opts.cert}`);
3152
+ }
3153
+ if (opts.pretty) {
3154
+ flags.push(`--pretty=${opts.pretty}`);
3155
+ }
3156
+ if (opts.style) {
3157
+ flags.push(`--style=${opts.style}`);
3158
+ }
3159
+ if (opts.timeout) {
3160
+ flags.push(`--timeout=${opts.timeout}`);
3161
+ }
3162
+ if (opts.queryParams) {
3163
+ Object.keys(queryObj).forEach((name) => {
3164
+ const value = queryObj[name];
3165
+ if (Array.isArray(value)) {
3166
+ value.forEach((val) => {
3167
+ push(`${name}==${quote(val)}`);
3168
+ });
3169
+ } else {
3170
+ push(`${name}==${quote(value)}`);
3171
+ }
3172
+ });
3173
+ }
3174
+ Object.keys(allHeaders).sort().forEach((key) => {
3175
+ push(`${key}:${quote(allHeaders[key])}`);
3176
+ });
3177
+ if (postData.mimeType === "application/x-www-form-urlencoded") {
3178
+ if (postData.params && postData.params.length) {
3179
+ flags.push(opts.short ? "-f" : "--form");
3180
+ postData.params.forEach((param) => {
3181
+ push(`${param.name}=${quote(param.value)}`);
3182
+ });
3183
+ }
3184
+ } else {
3185
+ raw = true;
3186
+ }
3187
+ const cliFlags = flags.length ? `${flags.join(" ")} ` : "";
3188
+ url = quote(opts.queryParams ? url : fullUrl);
3189
+ unshift(`http ${cliFlags}${method} ${url}`);
3190
+ if (raw && postData.text) {
3191
+ const postDataText = quote(postData.text);
3192
+ unshift(`echo ${postDataText} | `);
3193
+ }
3194
+ return join();
3195
+ }
3196
+ };
3197
+
3198
+ // src/targets/shell/wget/client.ts
3199
+ var wget = {
3200
+ info: {
3201
+ key: "wget",
3202
+ title: "Wget",
3203
+ link: "https://www.gnu.org/software/wget/",
3204
+ description: "a free software package for retrieving files using HTTP, HTTPS"
3205
+ },
3206
+ convert: ({ method, postData, allHeaders, fullUrl }, options) => {
3207
+ const opts = {
3208
+ indent: " ",
3209
+ short: false,
3210
+ verbose: false,
3211
+ ...options
3212
+ };
3213
+ const { push, join } = new CodeBuilder({
3214
+ ...typeof opts.indent === "string" ? { indent: opts.indent } : {},
3215
+ join: opts.indent !== false ? ` \\
3216
+ ${opts.indent}` : " "
3217
+ });
3218
+ if (opts.verbose) {
3219
+ push(`wget ${opts.short ? "-v" : "--verbose"}`);
3220
+ } else {
3221
+ push(`wget ${opts.short ? "-q" : "--quiet"}`);
3222
+ }
3223
+ push(`--method ${quote(method)}`);
3224
+ Object.keys(allHeaders).forEach((key) => {
3225
+ const header = `${key}: ${allHeaders[key]}`;
3226
+ push(`--header ${quote(header)}`);
3227
+ });
3228
+ if (postData.text) {
3229
+ push(`--body-data ${escape(quote(postData.text))}`);
3230
+ }
3231
+ push(opts.short ? "-O" : "--output-document");
3232
+ push(`- ${quote(fullUrl)}`);
3233
+ return join();
3234
+ }
3235
+ };
3236
+
3237
+ // src/targets/shell/target.ts
3238
+ var shell = {
3239
+ info: {
3240
+ key: "shell",
3241
+ title: "Shell",
3242
+ extname: ".sh",
3243
+ default: "curl",
3244
+ cli: "%s"
3245
+ },
3246
+ clientsById: {
3247
+ curl: curl2,
3248
+ httpie,
3249
+ wget
3250
+ }
3251
+ };
3252
+
3253
+ // src/targets/swift/helpers.ts
3254
+ var buildString = (length, str) => str.repeat(length);
3255
+ var concatArray = (arr, pretty, indentation, indentLevel) => {
3256
+ const currentIndent = buildString(indentLevel, indentation);
3257
+ const closingBraceIndent = buildString(indentLevel - 1, indentation);
3258
+ const join = pretty ? `,
3259
+ ${currentIndent}` : ", ";
3260
+ if (pretty) {
3261
+ return `[
3262
+ ${currentIndent}${arr.join(join)}
3263
+ ${closingBraceIndent}]`;
3264
+ }
3265
+ return `[${arr.join(join)}]`;
3266
+ };
3267
+ var literalDeclaration = (name, parameters, opts) => `let ${name} = ${literalRepresentation3(parameters, opts)}`;
3268
+ var literalRepresentation3 = (value, opts, indentLevel) => {
3269
+ indentLevel = indentLevel === void 0 ? 1 : indentLevel + 1;
3270
+ switch (Object.prototype.toString.call(value)) {
3271
+ case "[object Number]":
3272
+ return value;
3273
+ case "[object Array]": {
3274
+ let pretty = false;
3275
+ const valuesRepresentation = value.map((v) => {
3276
+ if (Object.prototype.toString.call(v) === "[object Object]") {
3277
+ pretty = Object.keys(v).length > 1;
3278
+ }
3279
+ return literalRepresentation3(v, opts, indentLevel);
3280
+ });
3281
+ return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel);
3282
+ }
3283
+ case "[object Object]": {
3284
+ const keyValuePairs = [];
3285
+ for (const key in value) {
3286
+ keyValuePairs.push(`"${key}": ${literalRepresentation3(value[key], opts, indentLevel)}`);
3287
+ }
3288
+ return concatArray(
3289
+ keyValuePairs,
3290
+ // @ts-expect-error needs better types
3291
+ opts.pretty && keyValuePairs.length > 1,
3292
+ // @ts-expect-error needs better types
3293
+ opts.indent,
3294
+ indentLevel
3295
+ );
3296
+ }
3297
+ case "[object Boolean]":
3298
+ return value.toString();
3299
+ default:
3300
+ if (value === null || value === void 0) {
3301
+ return "";
3302
+ }
3303
+ return `"${value.toString().replace(/"/g, '\\"')}"`;
3304
+ }
3305
+ };
3306
+
3307
+ // src/targets/swift/nsurlsession/client.ts
3308
+ var nsurlsession2 = {
3309
+ info: {
3310
+ key: "nsurlsession",
3311
+ title: "NSURLSession",
3312
+ link: "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html",
3313
+ description: "Foundation's NSURLSession request"
3314
+ },
3315
+ convert: ({ allHeaders, postData, fullUrl, method }, options) => {
3316
+ const opts = {
3317
+ indent: " ",
3318
+ pretty: true,
3319
+ timeout: "10",
3320
+ ...options
3321
+ };
3322
+ const { push, blank, join } = new CodeBuilder({ indent: opts.indent });
3323
+ const req = {
3324
+ hasHeaders: false,
3325
+ hasBody: false
3326
+ };
3327
+ push("import Foundation");
3328
+ if (Object.keys(allHeaders).length) {
3329
+ req.hasHeaders = true;
3330
+ blank();
3331
+ push(literalDeclaration("headers", allHeaders, opts));
3332
+ }
3333
+ if (postData.text || postData.jsonObj || postData.params) {
3334
+ req.hasBody = true;
3335
+ switch (postData.mimeType) {
3336
+ case "application/x-www-form-urlencoded":
3337
+ blank();
3338
+ if (postData.params?.length) {
3339
+ const [head, ...tail] = postData.params;
3340
+ push(`let postData = NSMutableData(data: "${head.name}=${head.value}".data(using: String.Encoding.utf8)!)`);
3341
+ tail.forEach(({ name, value }) => {
3342
+ push(`postData.append("&${name}=${value}".data(using: String.Encoding.utf8)!)`);
3343
+ });
3344
+ } else {
3345
+ req.hasBody = false;
3346
+ }
3347
+ break;
3348
+ case "application/json":
3349
+ if (postData.jsonObj) {
3350
+ push(`${literalDeclaration("parameters", postData.jsonObj, opts)} as [String : Any]`);
3351
+ blank();
3352
+ push("let postData = JSONSerialization.data(withJSONObject: parameters, options: [])");
3353
+ }
3354
+ break;
3355
+ case "multipart/form-data":
3356
+ push(literalDeclaration("parameters", postData.params, opts));
3357
+ blank();
3358
+ push(`let boundary = "${postData.boundary}"`);
3359
+ blank();
3360
+ push('var body = ""');
3361
+ push("var error: NSError? = nil");
3362
+ push("for param in parameters {");
3363
+ push('let paramName = param["name"]!', 1);
3364
+ push('body += "--\\(boundary)\\r\\n"', 1);
3365
+ push('body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""', 1);
3366
+ push('if let filename = param["fileName"] {', 1);
3367
+ push('let contentType = param["content-type"]!', 2);
3368
+ push("let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)", 2);
3369
+ push("if (error != nil) {", 2);
3370
+ push("print(error as Any)", 3);
3371
+ push("}", 2);
3372
+ push('body += "; filename=\\"\\(filename)\\"\\r\\n"', 2);
3373
+ push('body += "Content-Type: \\(contentType)\\r\\n\\r\\n"', 2);
3374
+ push("body += fileContent", 2);
3375
+ push('} else if let paramValue = param["value"] {', 1);
3376
+ push('body += "\\r\\n\\r\\n\\(paramValue)"', 2);
3377
+ push("}", 1);
3378
+ push("}");
3379
+ break;
3380
+ default:
3381
+ blank();
3382
+ push(`let postData = NSData(data: "${postData.text}".data(using: String.Encoding.utf8)!)`);
3383
+ }
3384
+ }
3385
+ blank();
3386
+ push(`let request = NSMutableURLRequest(url: NSURL(string: "${fullUrl}")! as URL,`);
3387
+ push(" cachePolicy: .useProtocolCachePolicy,");
3388
+ push(
3389
+ // @ts-expect-error needs better types
3390
+ ` timeoutInterval: ${parseInt(opts.timeout, 10).toFixed(1)})`
3391
+ );
3392
+ push(`request.httpMethod = "${method}"`);
3393
+ if (req.hasHeaders) {
3394
+ push("request.allHTTPHeaderFields = headers");
3395
+ }
3396
+ if (req.hasBody) {
3397
+ push("request.httpBody = postData as Data");
3398
+ }
3399
+ blank();
3400
+ push("let session = URLSession.shared");
3401
+ push(
3402
+ "let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in"
3403
+ );
3404
+ push("if (error != nil) {", 1);
3405
+ push("print(error as Any)", 2);
3406
+ push("} else {", 1);
3407
+ push("let httpResponse = response as? HTTPURLResponse", 2);
3408
+ push("print(httpResponse)", 2);
3409
+ push("}", 1);
3410
+ push("})");
3411
+ blank();
3412
+ push("dataTask.resume()");
3413
+ return join();
3414
+ }
3415
+ };
3416
+
3417
+ // src/targets/swift/target.ts
3418
+ var swift = {
3419
+ info: {
3420
+ key: "swift",
3421
+ title: "Swift",
3422
+ extname: ".swift",
3423
+ default: "nsurlsession"
3424
+ },
3425
+ clientsById: {
3426
+ nsurlsession: nsurlsession2
3427
+ }
3428
+ };
3429
+
3430
+ // src/targets/targets.ts
3431
+ var targets = {
3432
+ c,
3433
+ clojure,
3434
+ csharp,
3435
+ go,
3436
+ http,
3437
+ java,
3438
+ javascript,
3439
+ json,
3440
+ kotlin,
3441
+ node,
3442
+ objc,
3443
+ ocaml,
3444
+ php,
3445
+ powershell,
3446
+ python,
3447
+ r,
3448
+ ruby,
3449
+ shell,
3450
+ swift
3451
+ };
3452
+ var isTarget = (target) => {
3453
+ if (typeof target !== "object" || target === null || Array.isArray(target)) {
3454
+ const got = target === null ? "null" : Array.isArray(target) ? "array" : typeof target;
3455
+ throw new Error(`you tried to add a target which is not an object, got type: "${got}"`);
3456
+ }
3457
+ if (!Object.prototype.hasOwnProperty.call(target, "info")) {
3458
+ throw new Error("targets must contain an `info` object");
3459
+ }
3460
+ if (!Object.prototype.hasOwnProperty.call(target.info, "key")) {
3461
+ throw new Error("targets must have an `info` object with the property `key`");
3462
+ }
3463
+ if (!target.info.key) {
3464
+ throw new Error("target key must be a unique string");
3465
+ }
3466
+ if (Object.prototype.hasOwnProperty.call(targets, target.info.key)) {
3467
+ throw new Error(`a target already exists with this key, \`${target.info.key}\``);
3468
+ }
3469
+ if (!Object.prototype.hasOwnProperty.call(target.info, "title")) {
3470
+ throw new Error("targets must have an `info` object with the property `title`");
3471
+ }
3472
+ if (!target.info.title) {
3473
+ throw new Error("target title must be a non-zero-length string");
3474
+ }
3475
+ if (!Object.prototype.hasOwnProperty.call(target.info, "extname")) {
3476
+ throw new Error("targets must have an `info` object with the property `extname`");
3477
+ }
3478
+ if (!Object.prototype.hasOwnProperty.call(target, "clientsById") || !target.clientsById || Object.keys(target.clientsById).length === 0) {
3479
+ throw new Error(
3480
+ `No clients provided in target ${target.info.key}. You must provide the property \`clientsById\` containg your clients.`
3481
+ );
3482
+ }
3483
+ if (!Object.prototype.hasOwnProperty.call(target.info, "default")) {
3484
+ throw new Error("targets must have an `info` object with the property `default`");
3485
+ }
3486
+ if (!Object.prototype.hasOwnProperty.call(target.clientsById, target.info.default)) {
3487
+ throw new Error(
3488
+ `target ${target.info.key} is configured with a default client ${target.info.default}, but no such client was found in the property \`clientsById\` (found ${JSON.stringify(
3489
+ Object.keys(target.clientsById)
3490
+ )})`
3491
+ );
3492
+ }
3493
+ Object.values(target.clientsById).forEach(isClient);
3494
+ return true;
3495
+ };
3496
+ var addTarget = (target) => {
3497
+ if (!isTarget(target)) ;
3498
+ targets[target.info.key] = target;
3499
+ };
3500
+ var isClient = (client) => {
3501
+ if (!client) {
3502
+ throw new Error("clients must be objects");
3503
+ }
3504
+ if (!Object.prototype.hasOwnProperty.call(client, "info")) {
3505
+ throw new Error("targets client must contain an `info` object");
3506
+ }
3507
+ if (!Object.prototype.hasOwnProperty.call(client.info, "key")) {
3508
+ throw new Error("targets client must have an `info` object with property `key`");
3509
+ }
3510
+ if (!client.info.key) {
3511
+ throw new Error("client.info.key must contain an identifier unique to this target");
3512
+ }
3513
+ if (!Object.prototype.hasOwnProperty.call(client.info, "title")) {
3514
+ throw new Error("targets client must have an `info` object with property `title`");
3515
+ }
3516
+ if (!Object.prototype.hasOwnProperty.call(client.info, "description")) {
3517
+ throw new Error("targets client must have an `info` object with property `description`");
3518
+ }
3519
+ if (!Object.prototype.hasOwnProperty.call(client.info, "link")) {
3520
+ throw new Error("targets client must have an `info` object with property `link`");
3521
+ }
3522
+ if (!Object.prototype.hasOwnProperty.call(client, "convert") || typeof client.convert !== "function") {
3523
+ throw new Error("targets client must have a `convert` property containing a conversion function");
3524
+ }
3525
+ return true;
3526
+ };
3527
+ var addTargetClient = (targetId, client) => {
3528
+ if (!isClient(client)) ;
3529
+ if (!Object.prototype.hasOwnProperty.call(targets, targetId)) {
3530
+ throw new Error(`Sorry, but no ${targetId} target exists to add clients to`);
3531
+ }
3532
+ if (Object.prototype.hasOwnProperty.call(targets[targetId], client.info.key)) {
3533
+ throw new Error(
3534
+ `the target ${targetId} already has a client with the key ${client.info.key}, please use a different key`
3535
+ );
3536
+ }
3537
+ targets[targetId].clientsById[client.info.key] = client;
3538
+ };
3539
+
3540
+ // src/helpers/utils.ts
3541
+ var availableTargets = () => Object.keys(targets).map((targetId) => ({
3542
+ ...targets[targetId].info,
3543
+ clients: Object.keys(targets[targetId].clientsById).map(
3544
+ (clientId) => targets[targetId].clientsById[clientId].info
3545
+ )
3546
+ }));
3547
+ var extname = (targetId) => targets[targetId]?.info.extname || "";
3548
+
3549
+ // src/index.ts
3550
+ var isHarEntry = (value) => typeof value === "object" && "log" in value && typeof value.log === "object" && "entries" in value.log && Array.isArray(value.log.entries);
3551
+ var HTTPSnippet = class {
3552
+ constructor(input, opts = {}) {
3553
+ this.requests = [];
3554
+ this.prepare = (harRequest, options) => {
3555
+ const request2 = {
3556
+ ...harRequest,
3557
+ fullUrl: "",
3558
+ uriObj: {},
3559
+ queryObj: {},
3560
+ headersObj: {},
3561
+ cookiesObj: {},
3562
+ allHeaders: {}
3563
+ };
3564
+ if (request2.queryString && request2.queryString.length) {
3565
+ request2.queryObj = request2.queryString.reduce(reducer, {});
3566
+ }
3567
+ if (request2.headers && request2.headers.length) {
3568
+ const http2VersionRegex = /^HTTP\/2/;
3569
+ request2.headersObj = request2.headers.reduce((accumulator, { name, value }) => {
3570
+ const headerName = http2VersionRegex.exec(request2.httpVersion) ? name.toLocaleLowerCase() : name;
3571
+ return {
3572
+ ...accumulator,
3573
+ [headerName]: value
3574
+ };
3575
+ }, {});
3576
+ }
3577
+ if (request2.cookies && request2.cookies.length) {
3578
+ request2.cookiesObj = request2.cookies.reduceRight(
3579
+ (accumulator, { name, value }) => ({
3580
+ ...accumulator,
3581
+ [name]: value
3582
+ }),
3583
+ {}
3584
+ );
3585
+ }
3586
+ const cookies = request2.cookies?.map(({ name, value }) => {
3587
+ if (options.harIsAlreadyEncoded) {
3588
+ return `${name}=${value}`;
3589
+ }
3590
+ return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
3591
+ });
3592
+ if (cookies?.length) {
3593
+ request2.allHeaders.cookie = cookies.join("; ");
3594
+ }
3595
+ switch (request2.postData.mimeType) {
3596
+ case "multipart/mixed":
3597
+ case "multipart/related":
3598
+ case "multipart/form-data":
3599
+ case "multipart/alternative":
3600
+ request2.postData.text = "";
3601
+ request2.postData.mimeType = "multipart/form-data";
3602
+ if (request2.postData?.params) {
3603
+ const form = new FormData__default.default();
3604
+ const isNativeFormData = typeof form[Symbol.iterator] === "function";
3605
+ const boundary = "---011000010111000001101001";
3606
+ if (!isNativeFormData) {
3607
+ form._boundary = boundary;
3608
+ }
3609
+ request2.postData?.params.forEach((param) => {
3610
+ const name = param.name;
3611
+ const value = param.value || "";
3612
+ const filename = param.fileName || null;
3613
+ if (isNativeFormData) {
3614
+ if (isBlob(value)) {
3615
+ form.append(name, value, filename);
3616
+ } else {
3617
+ form.append(name, value);
3618
+ }
3619
+ } else {
3620
+ form.append(name, value, {
3621
+ // @ts-expect-error TODO
3622
+ filename,
3623
+ // @ts-expect-error TODO
3624
+ contentType: param.contentType || null
3625
+ });
3626
+ }
3627
+ });
3628
+ if (isNativeFormData) {
3629
+ for (const data of formDataIterator(form, boundary)) {
3630
+ request2.postData.text += data;
3631
+ }
3632
+ } else {
3633
+ form.pipe(
3634
+ // @ts-expect-error TODO
3635
+ eventStream.map((data) => {
3636
+ request2.postData.text += data;
3637
+ })
3638
+ );
239
3639
  }
240
- var convert = target.clientsById[clientId || target.info.default].convert;
241
- var results = _this.requests.map(function (request) { return convert(request, options); });
242
- return results.length === 1 ? results[0] : results;
243
- };
244
- var entries = [];
245
- var options = __assign({ harIsAlreadyEncoded: false }, opts);
246
- // prep the main container
247
- this.requests = [];
248
- // is it har?
249
- if (isHarEntry(input)) {
250
- entries = input.log.entries;
251
- }
252
- else {
253
- entries = [
254
- {
255
- request: input,
256
- },
257
- ];
258
- }
259
- entries.forEach(function (_a) {
260
- var _b;
261
- var request = _a.request;
262
- // add optional properties to make validation successful
263
- var req = __assign({ bodySize: 0, headersSize: 0, headers: [], cookies: [], httpVersion: 'HTTP/1.1', queryString: [], postData: {
264
- mimeType: ((_b = request.postData) === null || _b === void 0 ? void 0 : _b.mimeType) || 'application/octet-stream',
265
- } }, request);
266
- // Per the HAR spec `mimeType` needs to always be present if we have a `postData` object.
267
- if (req.postData && !req.postData.mimeType) {
268
- req.postData.mimeType = 'application/octet-stream';
3640
+ request2.postData.boundary = boundary;
3641
+ const contentTypeHeader = getHeaderName(request2.headersObj, "content-type") || "content-type";
3642
+ request2.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`;
3643
+ }
3644
+ break;
3645
+ case "application/x-www-form-urlencoded":
3646
+ if (!request2.postData.params) {
3647
+ request2.postData.text = "";
3648
+ } else {
3649
+ request2.postData.paramsObj = request2.postData.params.reduce(reducer, {});
3650
+ request2.postData.text = qs.stringify(request2.postData.paramsObj);
3651
+ }
3652
+ break;
3653
+ case "text/json":
3654
+ case "text/x-json":
3655
+ case "application/json":
3656
+ case "application/x-json":
3657
+ request2.postData.mimeType = "application/json";
3658
+ if (request2.postData.text) {
3659
+ try {
3660
+ request2.postData.jsonObj = JSON.parse(request2.postData.text);
3661
+ } catch (e) {
3662
+ request2.postData.mimeType = "text/plain";
269
3663
  }
270
- _this.requests.push(_this.prepare(req, options));
3664
+ }
3665
+ break;
3666
+ }
3667
+ const allHeaders = {
3668
+ ...request2.allHeaders,
3669
+ ...request2.headersObj
3670
+ };
3671
+ const urlWithParsedQuery = url.parse(request2.url, true, true);
3672
+ request2.queryObj = {
3673
+ ...request2.queryObj,
3674
+ ...urlWithParsedQuery.query
3675
+ };
3676
+ let search;
3677
+ if (options.harIsAlreadyEncoded) {
3678
+ search = qs.stringify(request2.queryObj, {
3679
+ encode: false,
3680
+ indices: false
3681
+ });
3682
+ } else {
3683
+ search = qs.stringify(request2.queryObj, {
3684
+ indices: false
271
3685
  });
3686
+ }
3687
+ const uriObj = {
3688
+ ...urlWithParsedQuery,
3689
+ query: request2.queryObj,
3690
+ search,
3691
+ path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname
3692
+ };
3693
+ const url$1 = url.format({
3694
+ ...urlWithParsedQuery,
3695
+ query: null,
3696
+ search: null
3697
+ });
3698
+ const fullUrl = url.format({
3699
+ ...urlWithParsedQuery,
3700
+ ...uriObj
3701
+ });
3702
+ return {
3703
+ ...request2,
3704
+ allHeaders,
3705
+ fullUrl,
3706
+ url: url$1,
3707
+ uriObj
3708
+ };
3709
+ };
3710
+ this.convert = (targetId, clientId, options) => {
3711
+ if (!options && clientId) {
3712
+ options = clientId;
3713
+ }
3714
+ const target = targets[targetId];
3715
+ if (!target) {
3716
+ return false;
3717
+ }
3718
+ const { convert } = target.clientsById[clientId || target.info.default];
3719
+ const results = this.requests.map((request2) => convert(request2, options));
3720
+ return results.length === 1 ? results[0] : results;
3721
+ };
3722
+ let entries = [];
3723
+ const options = {
3724
+ harIsAlreadyEncoded: false,
3725
+ ...opts
3726
+ };
3727
+ this.requests = [];
3728
+ if (isHarEntry(input)) {
3729
+ entries = input.log.entries;
3730
+ } else {
3731
+ entries = [
3732
+ {
3733
+ request: input
3734
+ }
3735
+ ];
272
3736
  }
273
- return HTTPSnippet;
274
- }());
3737
+ entries.forEach(({ request: request2 }) => {
3738
+ const req = {
3739
+ bodySize: 0,
3740
+ headersSize: 0,
3741
+ headers: [],
3742
+ cookies: [],
3743
+ httpVersion: "HTTP/1.1",
3744
+ queryString: [],
3745
+ postData: {
3746
+ mimeType: request2.postData?.mimeType || "application/octet-stream"
3747
+ },
3748
+ ...request2
3749
+ };
3750
+ if (req.postData && !req.postData.mimeType) {
3751
+ req.postData.mimeType = "application/octet-stream";
3752
+ }
3753
+ this.requests.push(this.prepare(req, options));
3754
+ });
3755
+ }
3756
+ };
3757
+ /**
3758
+ * @license https://raw.githubusercontent.com/node-fetch/node-fetch/master/LICENSE.md
3759
+ *
3760
+ * The MIT License (MIT)
3761
+ *
3762
+ * Copyright (c) 2016 - 2020 Node Fetch Team
3763
+ *
3764
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
3765
+ * of this software and associated documentation files (the "Software"), to deal
3766
+ * in the Software without restriction, including without limitation the rights
3767
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3768
+ * copies of the Software, and to permit persons to whom the Software is
3769
+ * furnished to do so, subject to the following conditions:
3770
+ *
3771
+ * The above copyright notice and this permission notice shall be included in all
3772
+ * copies or substantial portions of the Software.
3773
+ *
3774
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3775
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3776
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3777
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3778
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3779
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
3780
+ * SOFTWARE.
3781
+ *
3782
+ * Extracted from https://github.com/node-fetch/node-fetch/blob/64c5c296a0250b852010746c76144cb9e14698d9/src/utils/form-data.js
3783
+ */
3784
+
275
3785
  exports.HTTPSnippet = HTTPSnippet;
3786
+ exports.addTarget = addTarget;
3787
+ exports.addTargetClient = addTargetClient;
3788
+ exports.availableTargets = availableTargets;
3789
+ exports.extname = extname;
3790
+ //# sourceMappingURL=out.js.map
3791
+ //# sourceMappingURL=index.js.map