@readme/httpsnippet 7.1.1 → 8.0.0

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