-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
1479 lines (1263 loc) · 38.8 KB
/
index.html
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html manifest="./manifest.appcache"><head>
<title>---</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<meta charset=utf-8></head>
<body></body>
<script>
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var h = require('hscrpt')
function select (ready) {
return h('input', {type: 'file', onchange: function (ev) {
var file = ev.target.files[0]
ready(new FileReader(), file)
}})
}
module.exports = function (onFile) {
return select(function (reader, file) {
reader.onload = function () {
onFile(reader.result)
}
reader.readAsArrayBuffer(file)
})
}
module.exports.asDataURL = function (onFile) {
return select(function (reader, file) {
reader.onload = function () {
onFile(reader.result)
}
reader.readAsDataURL(file)
})
}
},{"hscrpt":2}],2:[function(require,module,exports){
module.exports = function h (tag, attrs, content) {
if(Array.isArray(attrs)) content = attrs, attrs = {}
var el = document.createElement(tag)
for(var k in attrs) el[k] = attrs[k]
if(content) content.forEach(function (e) {
if(e) el.appendChild('string' == typeof e ? document.createTextNode(e) : e)
})
return el
}
},{}],3:[function(require,module,exports){
function create (tag, classname, children) {
var el = document.createElement(tag)
classname && el.classList.add(classname)
children && children.forEach(function (e) {
el.appendChild(
'string' === typeof e ? document.createTextNode(e) : e
)
})
return el
}
module.exports = function (steps) {
var list = create('ul', 'hyperprogress__list')
var error = create('pre', 'hyperprogress__error')
var liquid = create('div', 'hyperprogress__liquid', ['.'])
var bar = create('div', 'hyperprogress__bar', [liquid])
liquid.style.width = '0%'
var n = 0
var prog = create('div', 'hyperprogress', [
steps ? bar : '',
list,
//only show bar if a number of steps is provided.
error
])
prog.complete = function () {
liquid.style.width = '100%'
prog.classList.add('hyperprogress--complete')
}
prog.next = function (name) {
n = Math.min(n+1, steps)
if(list.lastChild)
list.lastChild.classList.add('hyperprogress--okay')
if(name)
list.appendChild(create('li', 'hyperprogress__started', [name]))
liquid.style.width = Math.round((n/steps)*100)+'%'
if(n === steps)
prog.complete()
}
prog.fail = function (err) {
prog.classList.add('hyperprogress--failed')
if(err && err.stack && err.name) {
if(err.stack.indexOf(err.name) == 0) //chrome, node
error.textContent = err.stack
else //firefox
error.textContent = err.name+': '+err.message + '\n' + err.stack
}
else if(err && err.name && err.message)
error.textContent = err.name + ': ' + err.message
else
error.textContent = JSON.stringify(err)
return err
}
prog.reset = function () {
n = 0
error.innerHTML = list.innerHTML = ''
liquid.style.width = '0%'
return prog
}
return prog
}
},{}],4:[function(require,module,exports){
var SecureUrl = require('./fetch')
var u = require('./util')
module.exports = function (prefix, store, log) {
var appname = prefix
var wb, running = false
//destroy everything
function scorchedEarth () {
for(var k in localStorage) {
delete localStorage[k]
}
}
function onProgress (ev) {
wb.onprogress && wb.onprogress(ev)
}
var init = '#'+appname+'_INIT'
return wb = {
scorchedEarth: scorchedEarth,
isInit: function () {
return location.hash.substring(0, init.length) === init
},
setup: function () {
if(!wb.isInit())
location.hash = init + location.hash
location.reload()
},
reinitialize: function (cb) {
log.destroy(function () {
store.destroy(cb)
})
},
install: function (url, cb) {
onProgress('installing from:'+url)
var id = SecureUrl.isSecureUrl(url)
if(!id) return cb(new Error('not a secure url:'+url))
//check whether we already have this
//before downloading anything
store.get(id, function (err, data) {
if(!err) return cb(null, data, id)
SecureUrl(url, function (err, data, id) {
if(err) cb(err)
else store.add(data, id, function (err) {
cb(err, data, id)
})
})
})
},
installAndRun: function (url, cb) {
wb.install(url, function (err, _, id) {
if(err) cb(err)
else wb.run(id, cb)
})
},
add: store.add,
run: function (id, cb) {
if(SecureUrl.isSecureUrl(id))
return cb(new Error('use WebBoot.installAndRun, to load a secure url'))
if(!id) return cb(new Error('WebBoot.run: id must be provided'))
var _id
//if we are already running, restart
//clear out init code, if we are in setup mode
if(wb.isInit())
location.hash = location.hash.substring(init.length)
log.head(function (err, data) {
if(err) return cb(err)
if(data) _id = data.value
if(_id === id)
run(id)
else
log.append(id, function (err) {
if(err) return cb(err)
run(id)
})
})
function run (id) {
if(running) {
//reload, and then the current version will trigger.
cb()
location.reload()
}
else
store.get(id, function (err, data) {
if(err) return cb(err)
var script = document.createElement('script')
running = true
document.body.innerHTML = ''
script.textContent = u.toUtf8(data)
document.head.appendChild(script) //run javascript.
cb()
})
}
},
size: function (cb) {
store.ls(function (err, ls) {
if(err) cb(err)
else cb(null, ls.reduce(function (total, item) {
return total + item.size
}, 0))
})
},
//clear target amount of space.
prune: function (target, cb) {
if(!target) return cb(new Error('WebBoot.prune: size to clear must be provided'))
var cleared = 0, remove = []
function clear () {
var n = remove.length
while(remove.length) store.rm(remove.shift(), function () {
if(--n) return
if(cleared < target)
cb(new Error('could not clear requested space'), cleared)
else
cb(null, cleared)
})
}
store.ls(function (err, ls) {
if(err) return cb(err)
log.unfiltered(function (err, unfiltered) {
if(err) return cb(err)
var stored = unfiltered.reverse()
ls.forEach(function (a) {
if(!unfiltered.find(function (b) {
return a.id == b.id
})) {
cleared += a.size
remove.push(a.id)
}
})
for(var i = 0; i < stored.length; i++) {
var id = stored[i].value
var item = ls.find(function (e) {
return e.id === id
})
if(item) {
cleared += item.size
remove.push(id)
if(cleared >= target) return clear()
}
}
clear()
})
})
},
version: require('./package.json').version,
remove: store.rm,
has: store.has,
versions: function (cb) {
log.filtered(function (err, ls) {
if(err) return cb(err)
else if(ls.length) cb(null, ls)
else {
var versions = u.parse(localStorage[appname+'_versions'])
if(!versions) return cb(null, [])
var n = Object.keys(versions).length
for(var ts in versions) {
log.append(versions[ts], function () {
if(--n) return
//try again
log.filtered(cb)
})
}
}
})
},
history: log.unfiltered,
current: log.head,
append: log.append,
revert: log.revert,
onprogress: null
}
}
},{"./fetch":5,"./package.json":17,"./util":20}],5:[function(require,module,exports){
var BinaryXHR = require('binary-xhr')
var hasHash = /([A-Za-z0-9\/+]{43}=)\.sha256/
var isUrl = /^https?:\/\//
var u = require('./util')
//before calling this, always check whether you alread have
//a file with this hash.
exports = module.exports = function (url, cb) {
var id = exports.isSecureUrl(url)
if(!id)
return cb(new Error('is not a secure url:'+url))
BinaryXHR(url, function (err, data) {
if(err)
return cb(new Error('could not retrive secure url:'+err))
if(!data || !(data.length || data.byteLength))
return cb(new Error('empty response from: '+url))
u.hash(data, function (err, _id) {
if(_id !== id) cb(u.HashError(_id, id))
cb(null, data, id)
})
})
}
exports.isSecureUrl = function (string) {
var h = hasHash.exec(string)
return isUrl.test(string) && h && h[1]
}
},{"./util":20,"binary-xhr":9}],6:[function(require,module,exports){
'use strict'
var appname = 'SWB'
var store = require('./store')(appname, localStorage)
var log = require('./log')(appname, localStorage)
var wb = window.WebBoot = require('./bootloader')(appname, store, log)
//minimal user interface...
require('./ui')(appname, wb)
},{"./bootloader":4,"./log":7,"./store":18,"./ui":19}],7:[function(require,module,exports){
var u = require('./util')
/*
this uses localStorage, so it doesn't need async,
but i used async api anyway,
so it will be easy to switch to indexeddb.
*/
module.exports = function (prefix, storage) {
//pass in non-local storage, to make testing easy.
storage = storage || localStorage
var log
function _append (data, cb) {
var log = u.parse(storage[prefix]) || []
log.unshift(data)
storage[prefix] = JSON.stringify(log)
cb(null, data)
}
function filtered (log) {
var revert = null
var output = []
for(var i = 0; i < log.length; i++) {
var item = log[i]
if(revert && revert <= item.ts) //this op was reverted.
;
else if(item.revert)
revert = item.revert
else
output.push(item)
}
return output
}
function getLog() {
return u.parse(storage[prefix]) || []
}
return log = {
head: function (cb) {
cb(null, filtered(getLog())[0])
},
filtered: function (cb) {
cb(null, filtered(getLog()))
},
unfiltered: function (cb) {
cb(null, getLog())
},
append: function (data, cb) {
_append({value: data, ts: Date.now()}, cb)
},
revert: function (ts, cb) {
if(!ts) return cb(new Error('log.revert: must provide ts to revert to'))
_append({revert: ts, ts: Date.now()}, function (err) {
if(err) cb(err)
else cb(null, filtered(getLog())[0])
})
},
destroy: function (cb) {
delete storage[prefix]
cb()
}
}
}
},{"./util":20}],8:[function(require,module,exports){
module.exports = function ToBase64(buf) {
buf = new Uint8Array(buf)
var s = ''
for(var i = 0; i < buf.byteLength; i++)
s+=String.fromCharCode(buf[i])
return btoa(s)
}
},{}],9:[function(require,module,exports){
var inherits = require('inherits')
module.exports = function(url, cb) {
return new BinaryXHR(url, cb)
}
function BinaryXHR(url, cb) {
var self = this
var xhr = new XMLHttpRequest()
this.xhr = xhr
xhr.open("GET", url, true)
xhr.responseType = 'arraybuffer'
xhr.onreadystatechange = function () {
XHR = xhr
if (self.xhr.readyState === 4) {
if (self.xhr.status !== 200) {
cb(self.xhr.status, self.xhr.response);
} else if (self.xhr.response && self.xhr.response.byteLength > 0) {
cb(false, self.xhr.response)
} else {
if (self.xhr.response && self.xhr.response.byteLength === 0) return cb('response length 0')
cb('no response')
}
}
}
xhr.send(null)
}
},{"inherits":13}],10:[function(require,module,exports){
},{}],11:[function(require,module,exports){
arguments[4][2][0].apply(exports,arguments)
},{"dup":2}],12:[function(require,module,exports){
/**
* Print a human readable timestamp to the terminal
* given a number representing seconds
*
* Author: Dave Eddy <dave@daveeddy.com>
* Date: 8/18/2014
* License: MIT
*/
var util = require('util');
module.exports = human;
function human(seconds) {
if (seconds instanceof Date)
seconds = Math.round((Date.now() - seconds) / 1000);
var suffix = seconds < 0 ? 'from now' : 'ago';
seconds = Math.abs(seconds);
var times = [
seconds / 60 / 60 / 24 / 365, // years
seconds / 60 / 60 / 24 / 30, // months
seconds / 60 / 60 / 24 / 7, // weeks
seconds / 60 / 60 / 24, // days
seconds / 60 / 60, // hours
seconds / 60, // minutes
seconds // seconds
];
var names = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second'];
for (var i = 0; i < names.length; i++) {
var time = Math.floor(times[i]);
if (time > 1)
return util.format('%d %ss %s', time, names[i], suffix);
else if (time === 1)
return util.format('%d %s %s', time, names[i], suffix);
}
return util.format('0 seconds %s', suffix);
}
},{"util":16}],13:[function(require,module,exports){
module.exports = inherits
function inherits (c, p, proto) {
proto = proto || {}
var e = {}
;[c.prototype, proto].forEach(function (s) {
Object.getOwnPropertyNames(s).forEach(function (k) {
e[k] = Object.getOwnPropertyDescriptor(s, k)
})
})
c.prototype = Object.create(p.prototype, e)
c.super = p
}
//function Child () {
// Child.super.call(this)
// console.error([this
// ,this.constructor
// ,this.constructor === Child
// ,this.constructor.super === Parent
// ,Object.getPrototypeOf(this) === Child.prototype
// ,Object.getPrototypeOf(Object.getPrototypeOf(this))
// === Parent.prototype
// ,this instanceof Child
// ,this instanceof Parent])
//}
//function Parent () {}
//inherits(Child, Parent)
//new Child
},{}],14:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],15:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],16:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}