1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | export type Log = {
|
7 | type: string,
|
8 | message?: string,
|
9 | data?: any,
|
10 | id: string,
|
11 | date: Date,
|
12 | };
|
13 |
|
14 | export type Unsubscribe = () => void;
|
15 |
|
16 | let id = 0;
|
17 | const subscribers = [];
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export const log = (type: string, message?: string, data?: any) => {
|
25 | const obj: Log = { type, id: String(++id), date: new Date() };
|
26 | if (message) obj.message = message;
|
27 | if (data) obj.data = data;
|
28 | dispatch(obj);
|
29 | };
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | export const listen = (cb: (Log) => void): Unsubscribe => {
|
37 | subscribers.push(cb);
|
38 | return () => {
|
39 | const i = subscribers.indexOf(cb);
|
40 | if (i !== -1) {
|
41 |
|
42 | subscribers[i] = subscribers[subscribers.length - 1];
|
43 | subscribers.pop();
|
44 | }
|
45 | };
|
46 | };
|
47 |
|
48 | function dispatch(log: Log) {
|
49 | for (let i = 0; i < subscribers.length; i++) {
|
50 | try {
|
51 | subscribers[i](log);
|
52 | } catch (e) {
|
53 | console.error(e);
|
54 | }
|
55 | }
|
56 | }
|
57 |
|
58 |
|
59 | if (typeof window !== "undefined") {
|
60 | window.__ledgerLogsListen = listen;
|
61 | }
|