preproc.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { pipe, flow } from "fp-ts/function"
  2. import * as S from "fp-ts/string"
  3. import * as O from "fp-ts/Option"
  4. import * as A from "fp-ts/Array"
  5. const replaceables: { [key: string]: string } = {
  6. "--request": "-X",
  7. "--header": "-H",
  8. "--url": "",
  9. "--form": "-F",
  10. "--data-raw": "--data",
  11. "--data": "-d",
  12. "--data-ascii": "-d",
  13. "--data-binary": "-d",
  14. "--user": "-u",
  15. "--get": "-G",
  16. }
  17. const paperCuts = flow(
  18. // remove '\' and newlines
  19. S.replace(/ ?\\ ?$/gm, " "),
  20. S.replace(/\n/g, " "),
  21. // remove all $ symbols from start of argument values
  22. S.replace(/\$'/g, "'"),
  23. S.replace(/\$"/g, '"'),
  24. S.trim
  25. )
  26. // replace --zargs option with -Z
  27. const replaceLongOptions = (curlCmd: string) =>
  28. pipe(Object.keys(replaceables), A.reduce(curlCmd, replaceFunction))
  29. const replaceFunction = (curlCmd: string, r: string) =>
  30. pipe(
  31. curlCmd,
  32. O.fromPredicate(
  33. () => r.includes("data") || r.includes("form") || r.includes("header")
  34. ),
  35. O.map(S.replace(RegExp(`[ \t]${r}(["' ])`, "g"), ` ${replaceables[r]}$1`)),
  36. O.alt(() =>
  37. pipe(
  38. curlCmd,
  39. S.replace(RegExp(`[ \t]${r}(["' ])`), ` ${replaceables[r]}$1`),
  40. O.of
  41. )
  42. ),
  43. O.getOrElse(() => "")
  44. )
  45. // yargs parses -XPOST as separate arguments. just prescreen for it.
  46. const prescreenXArgs = flow(
  47. S.replace(
  48. / -X(GET|POST|PUT|PATCH|DELETE|HEAD|CONNECT|OPTIONS|TRACE)/,
  49. " -X $1"
  50. ),
  51. S.trim
  52. )
  53. /**
  54. * Sanitizes and makes curl string processable
  55. * @param curlCommand Raw curl command string
  56. * @returns Processed curl command string
  57. */
  58. export const preProcessCurlCommand = (curlCommand: string) =>
  59. pipe(
  60. curlCommand,
  61. O.fromPredicate((curlCmd) => curlCmd.length > 0),
  62. O.map(flow(paperCuts, replaceLongOptions, prescreenXArgs)),
  63. O.getOrElse(() => "")
  64. )