consola.06ad8a64.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { formatWithOptions } from 'node:util';
  2. import { sep } from 'node:path';
  3. function parseStack(stack) {
  4. const cwd = process.cwd() + sep;
  5. const lines = stack.split("\n").splice(1).map((l) => l.trim().replace("file://", "").replace(cwd, ""));
  6. return lines;
  7. }
  8. function writeStream(data, stream) {
  9. const write = stream.__write || stream.write;
  10. return write.call(stream, data);
  11. }
  12. const bracket = (x) => x ? `[${x}]` : "";
  13. class BasicReporter {
  14. formatStack(stack, opts) {
  15. return " " + parseStack(stack).join("\n ");
  16. }
  17. formatArgs(args, opts) {
  18. const _args = args.map((arg) => {
  19. if (arg && typeof arg.stack === "string") {
  20. return arg.message + "\n" + this.formatStack(arg.stack, opts);
  21. }
  22. return arg;
  23. });
  24. return formatWithOptions(opts, ..._args);
  25. }
  26. formatDate(date, opts) {
  27. return opts.date ? date.toLocaleTimeString() : "";
  28. }
  29. filterAndJoin(arr) {
  30. return arr.filter(Boolean).join(" ");
  31. }
  32. formatLogObj(logObj, opts) {
  33. const message = this.formatArgs(logObj.args, opts);
  34. if (logObj.type === "box") {
  35. return "\n" + [
  36. bracket(logObj.tag),
  37. logObj.title && logObj.title,
  38. ...message.split("\n")
  39. ].filter(Boolean).map((l) => " > " + l).join("\n") + "\n";
  40. }
  41. return this.filterAndJoin([
  42. bracket(logObj.type),
  43. bracket(logObj.tag),
  44. message
  45. ]);
  46. }
  47. log(logObj, ctx) {
  48. const line = this.formatLogObj(logObj, {
  49. columns: ctx.options.stdout.columns || 0,
  50. ...ctx.options.formatOptions
  51. });
  52. return writeStream(
  53. line + "\n",
  54. logObj.level < 2 ? ctx.options.stderr || process.stderr : ctx.options.stdout || process.stdout
  55. );
  56. }
  57. }
  58. export { BasicReporter as B, parseStack as p };