forked from cujojs/when
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebug.js
329 lines (271 loc) · 7.64 KB
/
debug.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/** @license MIT License (c) copyright B Cavalier & J Hann */
/*jshint devel: true*/
/*global console:true, setTimeout:true*/
/**
* This is a drop-in replacement for the when module that sets up automatic
* debug output for promises created or consumed by when.js. Use this
* instead of when to help with debugging.
*
* WARNING: This module **should never** be use this in a production environment.
* It exposes details of the promise
*
* In an AMD environment, you can simply change your path or package mappings:
*
* paths: {
* // 'when': 'path/to/when/when'
* 'when': 'path/to/when/debug'
* }
*
* or
*
* packages: [
* // { name: 'when', location: 'path/to/when', main: 'when' }
* { name: 'when', location: 'path/to/when', main: 'debug' }
* ]
*
* In a CommonJS environment, you can directly require this module where
* you would normally require 'when':
*
* // var when = require('when');
* var when = require('when/debug');
*
* Or you can temporarily modify the package.js to point main at debug.
* For example, when/package.json:
*
* ...
* "main": "./debug"
* ...
*
* @author [email protected]
*/
(function(define) {
define(['./when'], function(when) {
var promiseId, pending, exceptionsToRethrow, own, undef;
promiseId = 0;
pending = {};
own = Object.prototype.hasOwnProperty;
exceptionsToRethrow = {
RangeError: 1,
ReferenceError: 1,
SyntaxError: 1,
TypeError: 1
};
/**
* Replacement for when() that sets up debug logging on the
* returned promise.
*/
function whenDebug(promise, cb, eb, pb) {
var args = [promise].concat(wrapCallbacks(promise, [cb, eb, pb]));
return debugPromise(when.apply(null, args), promise);
}
/**
* Setup debug output handlers for the supplied promise.
* @param p {Promise} A trusted (when.js) promise
* @param parent {Promise} promise from which p was created (e.g. via then())
* @return {Promise} a new promise that outputs debug info and
* has a useful toString
*/
function debugPromise(p, parent) {
var id, origThen, newPromise, logReject;
if(own.call(p, 'parent')) {
return p;
}
promiseId++;
id = (parent && 'id' in parent) ? (parent.id + '.' + promiseId) : promiseId;
origThen = p.then;
newPromise = beget(p);
newPromise.id = id;
newPromise.parent = parent;
newPromise.toString = function() {
return toString('Promise', id);
};
newPromise.then = function(cb, eb) {
if(typeof eb === 'function') {
var promise = newPromise;
do {
promise.handled = true;
} while((promise = promise.parent) && !promise.handled);
}
return debugPromise(origThen.apply(p, wrapCallbacks(newPromise, arguments)), newPromise);
};
logReject = function() {
console.error(newPromise.toString());
};
p.then(
function(val) {
newPromise.toString = function() {
return toString('Promise', id, 'resolved', val);
};
return val;
},
wrapCallback(newPromise, function(err) {
newPromise.toString = function() {
return toString('Promise', id, 'REJECTED', err);
};
callGlobalHandler('reject', newPromise, err);
if(!newPromise.handled) {
logReject();
}
throw err;
})
);
return newPromise;
}
/**
* Replacement for when.defer() that sets up debug logging
* on the created Deferred, its resolver, and its promise.
* @param [id] anything optional identifier for this Deferred that will show
* up in debug output
* @return {Deferred} a Deferred with debug logging
*/
function deferDebug() {
var d, status, value, origResolve, origReject, origProgress, origThen, id;
// Delegate to create a Deferred;
d = when.defer();
status = 'pending';
value = pending;
// if no id provided, generate one. Not sure if this is
// useful or not.
id = arguments[arguments.length - 1];
if(id === undef) {
id = ++promiseId;
}
// Promise and resolver are frozen, so have to delegate
// in order to setup toString() on promise, resolver,
// and deferred
origThen = d.promise.then;
d.id = id;
d.promise = debugPromise(d.promise, d);
d.resolver = beget(d.resolver);
d.resolver.toString = function() {
return toString('Resolver', id, status, value);
};
origProgress = d.resolver.progress;
d.progress = d.resolver.progress = function(update) {
// Notify global debug handler, if set
callGlobalHandler('progress', d, update);
return origProgress(update);
};
origResolve = d.resolver.resolve;
d.resolve = d.resolver.resolve = function(val) {
value = val;
status = 'resolving';
// Notify global debug handler, if set
callGlobalHandler('resolve', d, val);
return origResolve.apply(undef, arguments);
};
origReject = d.resolver.reject;
d.reject = d.resolver.reject = function(err) {
value = err;
status = 'REJECTING';
return origReject.apply(undef, arguments);
};
d.toString = function() {
return toString('Deferred', id, status, value);
};
// Setup final state change handlers
d.then(
function(v) { status = 'resolved'; return v; },
function(e) { status = 'REJECTED'; return when.reject(e); }
);
d.then = d.promise.then;
// Add an id to all directly created promises. It'd be great
// to find a way to propagate this id to promise created by .then()
d.resolver.id = id;
return d;
}
whenDebug.defer = deferDebug;
whenDebug.isPromise = when.isPromise;
// For each method we haven't already replaced, replace it with
// one that sets up debug logging on the returned promise
for(var p in when) {
if(when.hasOwnProperty(p) && !(p in whenDebug)) {
makeDebug(p, when[p]);
}
}
return whenDebug;
// Wrap result of when[name] in a debug promise
function makeDebug(name, func) {
whenDebug[name] = function() {
return debugPromise(func.apply(when, arguments));
};
}
// Wrap a promise callback to catch exceptions and log or
// rethrow as uncatchable
function wrapCallback(promise, cb) {
return function(v) {
try {
return cb(v);
} catch(err) {
if(err) {
if (err.name in exceptionsToRethrow) {
throwUncatchable(err);
}
callGlobalHandler('reject', promise, err);
}
throw err;
}
};
}
// Wrap a callback, errback, progressback tuple
function wrapCallbacks(promise, callbacks) {
var cb, args, len, i;
args = [];
for(i = 0, len = callbacks.length; i < len; i++) {
args[i] = typeof (cb = callbacks[i]) == 'function'
? wrapCallback(promise, cb)
: cb;
}
return args;
}
function callGlobalHandler(handler, promise, triggeringValue, auxValue) {
var globalHandlers = whenDebug.debug;
if(!(globalHandlers && typeof globalHandlers[handler] === 'function')) {
return;
}
if(arguments.length < 4 && handler == 'reject') {
try {
throw new Error(promise.toString());
} catch(e) {
auxValue = e;
}
}
try {
globalHandlers[handler](promise, triggeringValue, auxValue);
} catch(handlerError) {
throwUncatchable(new Error('when.js global debug handler threw: ' + String(handlerError)));
}
}
// Stringify a promise, deferred, or resolver
function toString(name, id, status, value) {
var s = '[object ' + name + ' ' + id + ']';
if(arguments.length > 2) {
s += ' ' + status;
if(value !== pending) {
s += ': ' + value;
}
}
return s;
}
function throwUncatchable(err) {
setTimeout(function() {
throw err;
}, 0);
}
// The usual Crockford
function F() {}
function beget(o) {
F.prototype = o;
o = new F();
F.prototype = undef;
return o;
}
});
})(typeof define == 'function'
? define
: function (deps, factory) { typeof module != 'undefined'
? (module.exports = factory(require('./when')))
: (this.when = factory(this.when));
}
// Boilerplate for AMD, Node, and browser global
);