@holz/console-backend 0.1.0 → 0.3.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.
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const c=1e3,r=60*c,i=60*r,u=24*i,f=(a,t=a)=>{const e=a.getTime()-t.getTime(),o=Math.abs(e),s=e<0?"":"+";return o>=u?`${s}${Math.round(e/u)}d`:o>=i?`${s}${Math.round(e/i)}h`:o>=r?`${s}${Math.round(e/r)}m`:o>=c?`${s}${Math.round(e/c)}s`:`${s}${e}ms`};class l{constructor(t={}){this.console=t.console??console}processLog(t){const e=this.stamp,o=new Date;this.stamp=o;const s=[{include:!0,format:"%s",values:[t.message]},{include:Object.keys(t.context).length>0,format:"%o",values:[t.context]},{include:!0,format:"%c%s",values:["color: gray",f(o,e)]},{include:t.origin.length>0,format:"%c%s",values:["color: rgba(128, 128, 128, 0.6); font-style: italic",t.origin.join(":")]}].filter(n=>n.include),m=s.map(n=>n.format).join(" "),d=s.flatMap(n=>n.values);this.console[t.level](m,...d)}}exports.ConsoleBackend=l;exports.default=l;
@@ -1,43 +1,44 @@
1
- var c = /* @__PURE__ */ ((e) => (e.Error = "error", e.Warn = "warn", e.Info = "info", e.Debug = "debug", e))(c || {});
2
- class i {
3
- constructor(n = {}) {
4
- this.console = n.console ?? console;
1
+ const i = (c, t = c) => {
2
+ const e = c.getTime() - t.getTime(), n = Math.abs(e), s = e < 0 ? "" : "+";
3
+ return n >= 864e5 ? `${s}${Math.round(e / 864e5)}d` : n >= 36e5 ? `${s}${Math.round(e / 36e5)}h` : n >= 6e4 ? `${s}${Math.round(e / 6e4)}m` : n >= 1e3 ? `${s}${Math.round(e / 1e3)}s` : `${s}${e}ms`;
4
+ };
5
+ class u {
6
+ constructor(t = {}) {
7
+ this.console = t.console ?? console;
5
8
  }
6
- processLog(n) {
7
- const t = [
9
+ processLog(t) {
10
+ const e = this.stamp, n = new Date();
11
+ this.stamp = n;
12
+ const s = [
8
13
  {
9
14
  include: !0,
10
- command: "%c%s",
11
- content: n.message,
12
- style: `color: ${n.level === c.Debug ? "gray" : "unset"}`
15
+ format: "%s",
16
+ values: [t.message]
13
17
  },
14
18
  {
15
- include: Object.keys(n.context).length > 0,
16
- command: "%c%o",
19
+ include: Object.keys(t.context).length > 0,
20
+ format: "%o",
17
21
  // Chrome hides object content with `%O`.
18
- content: n.context,
19
- style: ""
22
+ values: [t.context]
20
23
  },
21
24
  {
22
- include: n.origin.length > 0,
23
- command: "%c%s",
24
- content: n.origin.join(":"),
25
- style: "color: rgba(128, 128, 128, 0.6); font-style: italic"
25
+ include: !0,
26
+ format: "%c%s",
27
+ values: ["color: gray", i(n, e)]
28
+ },
29
+ {
30
+ include: t.origin.length > 0,
31
+ format: "%c%s",
32
+ values: [
33
+ "color: rgba(128, 128, 128, 0.6); font-style: italic",
34
+ t.origin.join(":")
35
+ ]
26
36
  }
27
- ].filter((o) => o.include), r = t.map((o) => o.command).join(" "), s = t.flatMap((o) => [
28
- o.style,
29
- o.content
30
- ]), a = l[n.level];
31
- this.console[a](r, ...s);
37
+ ].filter((o) => o.include), a = s.map((o) => o.format).join(" "), r = s.flatMap((o) => o.values);
38
+ this.console[t.level](a, ...r);
32
39
  }
33
40
  }
34
- const l = {
35
- [c.Debug]: "debug",
36
- [c.Info]: "info",
37
- [c.Warn]: "warn",
38
- [c.Error]: "error"
39
- };
40
41
  export {
41
- i as ConsoleBackend,
42
- i as default
42
+ u as ConsoleBackend,
43
+ u as default
43
44
  };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@holz/console-backend",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "A console backend for Holz",
5
5
  "type": "module",
6
- "main": "./dist/holz-console-backend.umd.cjs",
6
+ "main": "./dist/holz-console-backend.cjs",
7
7
  "module": "./dist/holz-console-backend.js",
8
8
  "types": "./src/index.ts",
9
9
  "repository": {
@@ -13,7 +13,7 @@
13
13
  },
14
14
  "exports": {
15
15
  ".": {
16
- "require": "./dist/holz-console-backend.umd.cjs",
16
+ "require": "./dist/holz-console-backend.cjs",
17
17
  "import": "./dist/holz-console-backend.js"
18
18
  }
19
19
  },
@@ -34,12 +34,12 @@
34
34
  "debugger"
35
35
  ],
36
36
  "scripts": {
37
- "prepare": "vite build",
37
+ "prepack": "vite build",
38
38
  "test:unit": "vitest --color --passWithNoTests",
39
39
  "test:types": "tsc"
40
40
  },
41
41
  "devDependencies": {
42
- "@holz/core": "0.1.0",
42
+ "@holz/core": "0.2.0",
43
43
  "@types/node": "^18.14.0",
44
44
  "@vitest/coverage-c8": "0.28.5",
45
45
  "typescript": "4.9.5",
@@ -2,13 +2,13 @@
2
2
 
3
3
  exports[`Console backend > avoids changing debug messages 1`] = `
4
4
  [
5
- "%c%s %c%o %c%s",
6
- "color: gray",
5
+ "%s %o %c%s %c%s",
7
6
  "just spam",
8
- "",
9
7
  {
10
8
  "id": 1234,
11
9
  },
10
+ "color: gray",
11
+ "+0ms",
12
12
  "color: rgba(128, 128, 128, 0.6); font-style: italic",
13
13
  "ns-1:ns-2",
14
14
  ]
@@ -16,13 +16,13 @@ exports[`Console backend > avoids changing debug messages 1`] = `
16
16
 
17
17
  exports[`Console backend > avoids changing error messages 1`] = `
18
18
  [
19
- "%c%s %c%o %c%s",
20
- "color: unset",
19
+ "%s %o %c%s %c%s",
21
20
  "some error message",
22
- "",
23
21
  {
24
22
  "id": 1234,
25
23
  },
24
+ "color: gray",
25
+ "+0ms",
26
26
  "color: rgba(128, 128, 128, 0.6); font-style: italic",
27
27
  "ns-1:ns-2",
28
28
  ]
@@ -30,13 +30,13 @@ exports[`Console backend > avoids changing error messages 1`] = `
30
30
 
31
31
  exports[`Console backend > avoids changing info messages 1`] = `
32
32
  [
33
- "%c%s %c%o %c%s",
34
- "color: unset",
33
+ "%s %o %c%s %c%s",
35
34
  "a little info",
36
- "",
37
35
  {
38
36
  "id": 1234,
39
37
  },
38
+ "color: gray",
39
+ "+0ms",
40
40
  "color: rgba(128, 128, 128, 0.6); font-style: italic",
41
41
  "ns-1:ns-2",
42
42
  ]
@@ -44,13 +44,13 @@ exports[`Console backend > avoids changing info messages 1`] = `
44
44
 
45
45
  exports[`Console backend > avoids changing warn messages 1`] = `
46
46
  [
47
- "%c%s %c%o %c%s",
48
- "color: unset",
47
+ "%s %o %c%s %c%s",
49
48
  "a warning",
50
- "",
51
49
  {
52
50
  "id": 1234,
53
51
  },
52
+ "color: gray",
53
+ "+0ms",
54
54
  "color: rgba(128, 128, 128, 0.6); font-style: italic",
55
55
  "ns-1:ns-2",
56
56
  ]
@@ -18,6 +18,16 @@ class MockConsole implements MinimalConsole {
18
18
  }
19
19
 
20
20
  describe('Console backend', () => {
21
+ beforeEach(() => {
22
+ vi.useFakeTimers({
23
+ now: new Date('2020-01-01T00:00:00.000Z'),
24
+ });
25
+ });
26
+
27
+ afterEach(() => {
28
+ vi.useRealTimers();
29
+ });
30
+
21
31
  it('prints messages to the console', () => {
22
32
  const output = new MockConsole();
23
33
  const backend = new ConsoleBackend({ console: output });
@@ -72,6 +82,18 @@ describe('Console backend', () => {
72
82
  expect(output.print).not.toHaveBeenCalledWith(expect.stringContaining('}'));
73
83
  });
74
84
 
85
+ it('prints the time since the last log', () => {
86
+ const output = new MockConsole();
87
+ const backend = new ConsoleBackend({ console: output });
88
+ const logger = createLogger(backend);
89
+
90
+ logger.info('first message');
91
+ vi.advanceTimersByTime(1000);
92
+ logger.info('second message');
93
+
94
+ expect(output.print).toHaveBeenCalledWith(expect.stringContaining('+1s'));
95
+ });
96
+
75
97
  // Snapshot the exact output of each log level. This mostly prevents
76
98
  // regressions while doing innocent refactors.
77
99
  it.each([
@@ -0,0 +1,29 @@
1
+ import { timeDelta } from '../time-delta';
2
+
3
+ describe('timeDelta', () => {
4
+ it('formats the difference in human-readable time', () => {
5
+ expect(timeDelta(new Date(0), new Date(0))).toBe('+0ms');
6
+ expect(timeDelta(new Date(1), new Date(0))).toBe('+1ms');
7
+ expect(timeDelta(new Date(999), new Date(0))).toBe('+999ms');
8
+ expect(timeDelta(new Date(1_000), new Date(0))).toBe('+1s');
9
+
10
+ expect(timeDelta(new Date(1_499), new Date(0))).toBe('+1s');
11
+ expect(timeDelta(new Date(1_500), new Date(0))).toBe('+2s');
12
+
13
+ // Not quite a full minute. Kinda weird, but only if you think about it.
14
+ expect(timeDelta(new Date(59_999), new Date(0))).toBe('+60s');
15
+
16
+ expect(timeDelta(new Date(60_000), new Date(0))).toBe('+1m');
17
+ expect(timeDelta(new Date(3_600_000), new Date(0))).toBe('+1h');
18
+ expect(timeDelta(new Date(86_400_000), new Date(0))).toBe('+1d');
19
+ });
20
+
21
+ it('uses the current time if the last point is unknown', () => {
22
+ expect(timeDelta(new Date(0))).toBe('+0ms');
23
+ });
24
+
25
+ it('handles negative time differences', () => {
26
+ expect(timeDelta(new Date(0), new Date(1))).toBe('-1ms');
27
+ expect(timeDelta(new Date(0), new Date(60_000))).toBe('-1m');
28
+ });
29
+ });
@@ -1,5 +1,5 @@
1
1
  import type { Log, LogProcessor } from '@holz/core';
2
- import { LogLevel } from '@holz/core';
2
+ import { timeDelta } from './time-delta';
3
3
 
4
4
  /**
5
5
  * A backend that pretty-prints logs to a browser console, or any
@@ -7,54 +7,53 @@ import { LogLevel } from '@holz/core';
7
7
  */
8
8
  export default class ConsoleBackend implements LogProcessor {
9
9
  private console: MinimalConsole;
10
+ private stamp?: Date;
10
11
 
11
12
  constructor(options: Options = {}) {
12
13
  this.console = options.console ?? console;
13
14
  }
14
15
 
15
16
  processLog(log: Log) {
17
+ const lastTimestamp = this.stamp;
18
+ const now = new Date();
19
+
20
+ // Track the time spent between logs.
21
+ this.stamp = now;
22
+
16
23
  const segments = [
17
24
  {
18
25
  include: true,
19
- command: '%c%s',
20
- content: log.message,
21
- style: `color: ${log.level === LogLevel.Debug ? 'gray' : 'unset'}`,
26
+ format: '%s',
27
+ values: [log.message],
22
28
  },
23
29
  {
24
30
  include: Object.keys(log.context).length > 0,
25
- command: '%c%o', // Chrome hides object content with `%O`.
26
- content: log.context,
27
- style: '',
31
+ format: '%o', // Chrome hides object content with `%O`.
32
+ values: [log.context],
33
+ },
34
+ {
35
+ include: true,
36
+ format: '%c%s',
37
+ values: ['color: gray', timeDelta(now, lastTimestamp)],
28
38
  },
29
39
  {
30
40
  include: log.origin.length > 0,
31
- command: '%c%s',
32
- content: log.origin.join(':'),
33
- style: 'color: rgba(128, 128, 128, 0.6); font-style: italic',
41
+ format: '%c%s',
42
+ values: [
43
+ 'color: rgba(128, 128, 128, 0.6); font-style: italic',
44
+ log.origin.join(':'),
45
+ ],
34
46
  },
35
47
  ].filter((segment) => segment.include);
36
48
 
37
- const command = segments.map((segment) => segment.command).join(' ');
38
- const values = segments.flatMap((segment) => [
39
- segment.style,
40
- segment.content,
41
- ]);
42
-
43
- // Errors should always use stderr.
44
- const channel = LOG_METHOD[log.level];
49
+ const format = segments.map((segment) => segment.format).join(' ');
50
+ const values = segments.flatMap<unknown>((segment) => segment.values);
45
51
 
46
- this.console[channel](command, ...values);
52
+ // Browsers have UIs for filtering by log level. Leverage that.
53
+ this.console[log.level](format, ...values);
47
54
  }
48
55
  }
49
56
 
50
- // Browsers have UIs for filtering by log level. Leverage that.
51
- const LOG_METHOD: Record<LogLevel, keyof MinimalConsole> = {
52
- [LogLevel.Debug]: 'debug',
53
- [LogLevel.Info]: 'info',
54
- [LogLevel.Warn]: 'warn',
55
- [LogLevel.Error]: 'error',
56
- };
57
-
58
57
  interface Options {
59
58
  console?: MinimalConsole;
60
59
  }
@@ -0,0 +1,33 @@
1
+ const second = 1_000;
2
+ const minute = 60 * second;
3
+ const hour = 60 * minute;
4
+ const day = 24 * hour;
5
+
6
+ /**
7
+ * Formats the difference between two dates in human-readable time.
8
+ *
9
+ * Inspired by the `ms` package. Thanks TJ.
10
+ */
11
+ export const timeDelta = (now: Date, then: Date = now) => {
12
+ const offset = now.getTime() - then.getTime();
13
+ const distance = Math.abs(offset);
14
+ const sign = offset < 0 ? '' : '+';
15
+
16
+ if (distance >= day) {
17
+ return `${sign}${Math.round(offset / day)}d`;
18
+ }
19
+
20
+ if (distance >= hour) {
21
+ return `${sign}${Math.round(offset / hour)}h`;
22
+ }
23
+
24
+ if (distance >= minute) {
25
+ return `${sign}${Math.round(offset / minute)}m`;
26
+ }
27
+
28
+ if (distance >= second) {
29
+ return `${sign}${Math.round(offset / second)}s`;
30
+ }
31
+
32
+ return `${sign}${offset}ms`;
33
+ };
@@ -1 +0,0 @@
1
- (function(o,e){typeof exports=="object"&&typeof module<"u"?e(exports):typeof define=="function"&&define.amd?define(["exports"],e):(o=typeof globalThis<"u"?globalThis:o||self,e(o["holz-console-backend"]={}))})(this,function(o){"use strict";var e=(t=>(t.Error="error",t.Warn="warn",t.Info="info",t.Debug="debug",t))(e||{});class s{constructor(n={}){this.console=n.console??console}processLog(n){const l=[{include:!0,command:"%c%s",content:n.message,style:`color: ${n.level===e.Debug?"gray":"unset"}`},{include:Object.keys(n.context).length>0,command:"%c%o",content:n.context,style:""},{include:n.origin.length>0,command:"%c%s",content:n.origin.join(":"),style:"color: rgba(128, 128, 128, 0.6); font-style: italic"}].filter(c=>c.include),r=l.map(c=>c.command).join(" "),d=l.flatMap(c=>[c.style,c.content]),a=i[n.level];this.console[a](r,...d)}}const i={[e.Debug]:"debug",[e.Info]:"info",[e.Warn]:"warn",[e.Error]:"error"};o.ConsoleBackend=s,o.default=s,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});