index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const dedent_1 = __importDefault(require("dedent"));
  7. const objectorarray_1 = __importDefault(require("objectorarray"));
  8. const fast_json_parse_1 = __importDefault(require("fast-json-parse"));
  9. const ENDENT_ID = "twhZNwxI1aFG3r4";
  10. function endent(strings, ...values) {
  11. let result = "";
  12. for (let i = 0; i < strings.length; i++) {
  13. result += strings[i];
  14. if (i < values.length) {
  15. let value = values[i];
  16. let isJson = false;
  17. if (fast_json_parse_1.default(value).value) {
  18. value = fast_json_parse_1.default(value).value;
  19. isJson = true;
  20. }
  21. if ((value && value[ENDENT_ID]) || isJson) {
  22. let rawlines = result.split("\n");
  23. let l = rawlines[rawlines.length - 1].search(/\S/);
  24. let endentation = l > 0 ? " ".repeat(l) : "";
  25. let valueJson = isJson
  26. ? JSON.stringify(value, null, 2)
  27. : value[ENDENT_ID];
  28. let valueLines = valueJson.split("\n");
  29. valueLines.forEach((l, index) => {
  30. if (index > 0) {
  31. result += "\n" + endentation + l;
  32. }
  33. else {
  34. result += l;
  35. }
  36. });
  37. }
  38. else if (typeof value === "string" && value.includes("\n")) {
  39. let endentations = result.match(/(?:^|\n)( *)$/);
  40. if (typeof value === "string") {
  41. let endentation = endentations ? endentations[1] : "";
  42. result += value
  43. .split("\n")
  44. .map((str, i) => {
  45. str = ENDENT_ID + str;
  46. return i === 0 ? str : `${endentation}${str}`;
  47. })
  48. .join("\n");
  49. }
  50. else {
  51. result += value;
  52. }
  53. }
  54. else {
  55. result += value;
  56. }
  57. }
  58. }
  59. result = dedent_1.default(result);
  60. return result.split(ENDENT_ID).join("");
  61. }
  62. endent.pretty = (data) => {
  63. return objectorarray_1.default(data)
  64. ? { [ENDENT_ID]: JSON.stringify(data, null, 2) }
  65. : data;
  66. };
  67. exports.default = endent;