Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80647 views
1
var inherits = require('inherits');
2
3
function Reporter(options) {
4
this._reporterState = {
5
obj: null,
6
path: [],
7
options: options || {},
8
errors: []
9
};
10
}
11
exports.Reporter = Reporter;
12
13
Reporter.prototype.isError = function isError(obj) {
14
return obj instanceof ReporterError;
15
};
16
17
Reporter.prototype.save = function save() {
18
var state = this._reporterState;
19
20
return { obj: state.obj, pathLen: state.path.length };
21
};
22
23
Reporter.prototype.restore = function restore(data) {
24
var state = this._reporterState;
25
26
state.obj = data.obj;
27
state.path = state.path.slice(0, data.pathLen);
28
};
29
30
Reporter.prototype.enterKey = function enterKey(key) {
31
return this._reporterState.path.push(key);
32
};
33
34
Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
35
var state = this._reporterState;
36
37
state.path = state.path.slice(0, index - 1);
38
if (state.obj !== null)
39
state.obj[key] = value;
40
};
41
42
Reporter.prototype.enterObject = function enterObject() {
43
var state = this._reporterState;
44
45
var prev = state.obj;
46
state.obj = {};
47
return prev;
48
};
49
50
Reporter.prototype.leaveObject = function leaveObject(prev) {
51
var state = this._reporterState;
52
53
var now = state.obj;
54
state.obj = prev;
55
return now;
56
};
57
58
Reporter.prototype.error = function error(msg) {
59
var err;
60
var state = this._reporterState;
61
62
var inherited = msg instanceof ReporterError;
63
if (inherited) {
64
err = msg;
65
} else {
66
err = new ReporterError(state.path.map(function(elem) {
67
return '[' + JSON.stringify(elem) + ']';
68
}).join(''), msg.message || msg, msg.stack);
69
}
70
71
if (!state.options.partial)
72
throw err;
73
74
if (!inherited)
75
state.errors.push(err);
76
77
return err;
78
};
79
80
Reporter.prototype.wrapResult = function wrapResult(result) {
81
var state = this._reporterState;
82
if (!state.options.partial)
83
return result;
84
85
return {
86
result: this.isError(result) ? null : result,
87
errors: state.errors
88
};
89
};
90
91
function ReporterError(path, msg) {
92
this.path = path;
93
this.rethrow(msg);
94
};
95
inherits(ReporterError, Error);
96
97
ReporterError.prototype.rethrow = function rethrow(msg) {
98
this.message = msg + ' at: ' + (this.path || '(shallow)');
99
Error.captureStackTrace(this, ReporterError);
100
101
return this;
102
};
103
104