UNPKG

1.69 MBJavaScriptView Raw
1'use strict';
2(function (main, globalVal) {
3 globalVal = typeof global !== 'undefined' ? global : globalVal;
4 var cached = {};
5 var loading = {};
6
7 function bundleRequire(id) {
8 var bundle = main[id];
9 if (!bundle) {
10 throw new Error('Invalid module id ' + id);
11 }
12 if (cached[id]) {
13 return cached[id];
14 }
15 if (loading[id]) {
16 return loading[id];
17 }
18 var module = {exports: loading[id] = {}};
19 bundle[0].call(module.exports, module.exports, function bundlerRequire(moduleName) {
20 if (typeof core != 'undefined' && core.indexOf(moduleName) > -1) {
21 return require(moduleName); // fallback to node require
22 }
23 return bundleRequire(bundle[1][moduleName] || moduleName);
24 }, module, globalVal);
25 loading[id] = null;
26 return cached[id] = module.exports;
27 }
28
29 bundleRequire(0);
30})({0: [function (exports, require, module, global) {'use strict';
31
32let time = Date.now();
33let Bundler = require(time.toString.somethingUndefined || './index');
34
35let bundler = new Bundler({
36 strict: true,
37 web: true,
38 out: 'out.js'
39});
40bundler.addFile('test.js');
41bundler.on('bundle', function (e) {
42 console.log('bundled and took ' + (Date.now() - time));
43});
44}, {"./index":1}],1: [function (exports, require, module, global) {if (process.env.NODE_ENV === 'development') {
45 require('longjohn');
46}
47
48var fs = require('fs');
49var path = require('path');
50var crypto = require('crypto');
51var esprima = require('esprima');
52var resolve = require('resolve');
53var browserResolve = require('browser-resolve');
54var events = require('events');
55
56var core = {
57 "assert": "assert",
58 "buffer_ieee754": "buffer-browserify/buffer_ieee754",
59 "buffer": "buffer-browserify",
60 "child_process": "",
61 "cluster": "",
62 "console": "console-browserify",
63 "constants": "constants-browserify",
64 "crypto": "crypto-browserify",
65 "_debugger": "",
66 "dgram": "",
67 "dns": "",
68 "domain": "",
69 "events": "events",
70 "freelist": "",
71 "fs": "browserify-fs",
72 "http": "http-browserify",
73 "https": "https-browserify",
74 "_linklist": "",
75 "module": "",
76 "net": "",
77 "os": "os-browserify",
78 "path": "path-browserify",
79 "punycode": "punycode",
80 "querystring": "querystring",
81 "readline": "",
82 "repl": "",
83 "stream": "stream-browserify",
84 "string_decoder": "string_decoder",
85 "sys": "",
86 "timers": "timers-browserify",
87 "tls": "",
88 "tty": "tty-browserify",
89 "url": "url",
90 "util": "util",
91 "vm": "vm-browserify",
92 "zlib": "browserify-zlib"
93};
94
95var mainHeader = function (main, globalVal) {
96 globalVal = typeof global !== 'undefined' ? global : globalVal;
97 var cached = {};
98 var loading = {};
99 /*core*/
100 function bundleRequire(id) {
101 var bundle = main[id];
102 if (!bundle) {
103 throw new Error('Invalid module id ' + id);
104 }
105 if (cached[id]) {
106 return cached[id];
107 }
108 if (loading[id]) {
109 return loading[id];
110 }
111 var module = {exports: loading[id] = {}};
112 bundle[0].call(module.exports, module.exports, function bundlerRequire(moduleName) {
113 if (typeof core != 'undefined' && core.indexOf(moduleName) > -1) {
114 return require(moduleName); // fallback to node require
115 }
116 return bundleRequire(bundle[1][moduleName] || moduleName);
117 }, module, globalVal);
118 loading[id] = null;
119 return cached[id] = module.exports;
120 }
121
122 bundleRequire(0);
123}.toString();
124
125function Bundler(options) {
126 events.EventEmitter.call(this);
127 var defaults = {
128 directory: process.cwd(), // the main directory
129 strict: false, // if to append 'use strict'; in the header
130 web: false, // if to add core node modules
131 extensions: ['.js', '.json'], // files to require
132 out: null, // file to save as
133 wait: 1 // how long to wait
134 };
135 if (options) {
136 for (var property in defaults) {
137 if (defaults.hasOwnProperty(property) && options.hasOwnProperty(property)) {
138 defaults[property] = options[property];
139 }
140 }
141 }
142 this.options = defaults;
143}
144
145Bundler.prototype = events.EventEmitter.prototype;
146
147Bundler.prototype.files = {};
148
149Bundler.prototype.addFile = function (file, directory) {
150 if (!fs.existsSync(file)) {
151 throw new Error('File ' + file + ' not found');
152 }
153 if (!directory) {
154 file = path.join(this.options.directory, file);
155 this.main = file;
156 }
157 var bundled = this.files[file] = new BundledFile(file, directory || '', this);
158 bundled.checkContents(); // check AFTER setting file
159 this.needsRebundle();
160};
161
162Bundler.prototype.reloadFile = function (file, directory) {
163 var bundled = this.files[file];
164 if (bundled) {
165 bundled.checkContents();
166 } else {
167 this.addFile(file, directory);
168 }
169};
170
171Bundler.prototype.loadDependencies = function (contents, file, directory) {
172 var tokens;
173 try {
174 tokens = esprima.tokenize(contents);
175 } catch (e) {
176 console.error('Failed to tokenize ' + file, e.stack);
177 return [];
178 }
179 var dependencies = [];
180 for (var i = 0, length = tokens.length; i < length; i++) {
181 var token = tokens[i];
182 if (token.type === 'Identifier' && token.value === 'require' && i < length - 3) {
183 // check the require statement, it should start with a (, have a string, then end with a )
184 var next = tokens[i + 1];
185 if (next.type !== 'Punctuator' || next.value !== '(') {
186 continue;
187 }
188 next = tokens[i + 3];
189 if (next.type !== 'Punctuator' || next.value !== ')') {
190 // loop until we find a string
191 while (next.type !== 'String' && next.value !== ')' && i < length - 3) {
192 next = tokens[++i];
193 console.log('checking ', next);
194 }
195 i -= 2;
196 }
197 next = tokens[i + 2];
198 if (next.type !== 'String') {
199 continue;
200 }
201 var value = next.value.replace(/['"]+/g, '');
202 if (resolve.isCore(value)) {
203 if (this.options.web) {
204 // use special modules if available
205 var specialModule = core[value];
206 if (specialModule.length === 0) {
207 throw new Error('There is no web version of the core module ' + value + '!');
208 }
209 var module = resolve.sync(specialModule, {basedir: __dirname});
210 if (!this.files[module]) {
211 this.reloadFile(module, path.dirname(module));
212 }
213 dependencies.push({module: module, value: value});
214 } else {
215 dependencies.push(value); // regular node importing
216 }
217 } else {
218 try {
219 var module;
220 if (this.options.web) {
221 module = browserResolve.sync(value, {filename: file, extensions: this.options.extensions});
222 } else {
223 module = resolve.sync(value, {basedir: directory || this.options.directory, extensions: this.options.extensions});
224 }
225 if (!this.files[module]) {
226 this.reloadFile(module, path.dirname(module));
227 }
228 dependencies.push({module: module, value: value});
229 } catch (e) {
230 console.error('Failed to load module', value, e.message);
231 }
232 }
233 }
234 }
235 return dependencies;
236};
237
238Bundler.prototype.needsRebundle = function () {
239 if (this._bundling) {
240 return;
241 }
242 this._bundling = true;
243 setTimeout(() => {
244 this._bundling = false;
245 this.bundle();
246 }, this.options.wait); // allow other processes to run and cancel
247};
248
249Bundler.prototype.bundle = function () {
250 var start = Date.now();
251 this.emit('bundleStart', start);
252 var array = [];
253 var i = 0;
254 var reverseIds = {};
255 // first loop, assign ids
256 for (var property in this.files) {
257 if (this.files.hasOwnProperty(property)) {
258 if (reverseIds[property]) {
259 continue; // already bundled
260 }
261 reverseIds[property] = i++;
262 }
263 }
264 // second loop, build code
265 for (var property in this.files) {
266 if (this.files.hasOwnProperty(property)) {
267 // todo check if previously bundled
268 var bundled = this.files[property];
269 var dependencies = {};
270
271 for (var j = 0, length = bundled.dependencies.length; j < length; j++) {
272 var dependency = bundled.dependencies[j];
273 if (typeof dependency !== 'string') {
274 dependencies[dependency.value] = reverseIds[dependency.module];
275 }
276 }
277
278 var event = {
279 file: property,
280 content: bundled.contents
281 };
282 if (bundled.changed) {
283 this.emit('bundleFile', event);
284 bundled.changed = false;
285 }
286 if (path.extname(event.file) === '.json') {
287 array.push(reverseIds[bundled.file] + `: [function (exports, require, module, global) {module.exports = ${event.content}}, ${JSON.stringify(dependencies)}]`);
288 } else {
289 array.push(reverseIds[bundled.file] + `: [function (exports, require, module, global) {${event.content}}, ${JSON.stringify(dependencies)}]`);
290 }
291 }
292 }
293 var header = mainHeader;
294 header = header.replace('/*main*/', this.main);
295 header = header.replace('/*core*/', this.options.web ? '' : 'var core = ' + JSON.stringify(Object.keys(core)) + ';');
296
297 var text = '(' + header + ')({' + array.join(',') + '}, this);';
298 if (this.options.strict) {
299 text = '\'use strict\';\n' + text;
300 }
301
302 var event = {content: text, time: Date.now() - start, files: array.length};
303 this.emit('bundle', event);
304 if (typeof this.options.out === 'string') {
305 fs.writeFileSync(this.options.out, event.content);
306 } else if (this.options.out) {
307 this.options.out(event.content);
308 } else {
309 process.stdout.write(event.content);
310 }
311};
312
313module.exports = Bundler;
314
315function BundledFile(file, directory, bundler) {
316 this.file = file;
317 this.directory = directory;
318 this.bundler = bundler;
319 this.changed = false;
320}
321
322BundledFile.prototype.checkContents = function () {
323 try {
324 var contents = fs.readFileSync(this.file);
325 var newHash;
326 if (!this.contents || this.contents.length != contents.length || this.hash != (newHash = calculateHash(contents))) {
327 this.hash = newHash;
328 this.contents = contents;
329 this.changed = true;
330 var event = {contents: this.contents, file: this.file};
331 this.bundler.emit('fileUpdate', event);
332 this.contents = event.contents;
333 this.dependencies = this.bundler.loadDependencies(this.contents, this.file, this.directory);
334 this.bundler.needsRebundle();
335 }
336 } catch (e) {
337 e.message = this.file + '\n' + (e.message || '');
338 throw e;
339 }
340};
341
342function calculateHash(contents) {
343 return crypto.createHash('sha512').update(contents).digest('hex');
344}
345}, {"longjohn":2,"fs":16,"path":8,"crypto":146,"esprima":335,"resolve":336,"browser-resolve":343,"events":3}],2: [function (exports, require, module, global) {(function() {
346 var ERROR_ID, EventEmitter, create_callsite, current_trace_error, filename, format_location, format_method, in_prepare, limit_frames, prepareStackTrace, source_map, wrap_callback, __nextDomainTick, _addListener, _listeners, _nextTick, _on, _once, _ref, _setImmediate, _setInterval, _setTimeout;
347
348 EventEmitter = require('events').EventEmitter;
349
350 if ((_ref = EventEmitter.prototype.on) != null ? _ref['longjohn'] : void 0) {
351 return module.exports = EventEmitter.prototype.on['longjohn'];
352 }
353
354 source_map = require('source-map-support');
355
356 source_map.install();
357
358 filename = __filename;
359
360 current_trace_error = null;
361
362 in_prepare = 0;
363
364 exports.empty_frame = '---------------------------------------------';
365
366 exports.async_trace_limit = 10;
367
368 format_location = function(frame) {
369 var column, file, line;
370 if (frame.isNative()) {
371 return 'native';
372 }
373 if (frame.isEval()) {
374 return 'eval at ' + frame.getEvalOrigin();
375 }
376 file = frame.getFileName();
377 file = frame.getFileName() || '<anonymous>';
378 line = frame.getLineNumber();
379 column = frame.getColumnNumber();
380 column = column != null ? ':' + column : '';
381 line = line != null ? ':' + line : '';
382 return file + line + column;
383 };
384
385 format_method = function(frame) {
386 var function_name, method, type;
387 function_name = frame.getFunctionName();
388 if (!(frame.isToplevel() || frame.isConstructor())) {
389 method = frame.getMethodName();
390 type = frame.getTypeName();
391 if (function_name == null) {
392 return "" + type + "." + (method != null ? method : '<anonymous>');
393 }
394 if (method === function_name) {
395 return "" + type + "." + function_name;
396 }
397 "" + type + "." + function_name + " [as " + method + "]";
398 }
399 if (frame.isConstructor()) {
400 return "new " + (function_name != null ? function_name : '<anonymous>');
401 }
402 if (function_name != null) {
403 return function_name;
404 }
405 return null;
406 };
407
408 exports.format_stack_frame = function(frame) {
409 if (frame.getFileName() === exports.empty_frame) {
410 return exports.empty_frame;
411 }
412 return ' at ' + source_map.wrapCallSite(frame);
413 };
414
415 exports.format_stack = function(err, frames) {
416 var e, lines;
417 lines = [];
418 try {
419 lines.push(err.toString());
420 } catch (_error) {
421 e = _error;
422 console.log('Caught error in longjohn. Please report this to matt.insler@gmail.com.');
423 }
424 lines.push.apply(lines, frames.map(exports.format_stack_frame));
425 return lines.join('\n');
426 };
427
428 create_callsite = function(location) {
429 return Object.create({
430 getFileName: function() {
431 return location;
432 },
433 getLineNumber: function() {
434 return null;
435 },
436 getFunctionName: function() {
437 return null;
438 },
439 getTypeName: function() {
440 return null;
441 },
442 getMethodName: function() {
443 return null;
444 },
445 getColumnNumber: function() {
446 return null;
447 },
448 isNative: function() {
449 return null;
450 }
451 });
452 };
453
454 prepareStackTrace = function(error, structured_stack_trace) {
455 var previous_stack, _ref1;
456 ++in_prepare;
457 if (error.__cached_trace__ == null) {
458 Object.defineProperty(error, '__cached_trace__', {
459 writable: true,
460 enumerable: false,
461 configurable: true,
462 value: structured_stack_trace.filter(function(f) {
463 return f.getFileName() !== filename;
464 })
465 });
466 if ((error.__previous__ == null) && in_prepare === 1) {
467 Object.defineProperty(error, '__previous__', {
468 writable: true,
469 enumerable: false,
470 configurable: true,
471 value: current_trace_error
472 });
473 }
474 if (error.__previous__ != null) {
475 previous_stack = prepareStackTrace(error.__previous__, error.__previous__.__stack__);
476 if ((previous_stack != null ? previous_stack.length : void 0) > 0) {
477 error.__cached_trace__.push(create_callsite(exports.empty_frame));
478 (_ref1 = error.__cached_trace__).push.apply(_ref1, previous_stack);
479 }
480 }
481 }
482 --in_prepare;
483 if (in_prepare > 0) {
484 return error.__cached_trace__;
485 }
486 return exports.format_stack(error, error.__cached_trace__);
487 };
488
489 limit_frames = function(stack) {
490 var count, previous;
491 if (exports.async_trace_limit <= 0) {
492 return;
493 }
494 count = exports.async_trace_limit - 1;
495 previous = stack;
496 while ((previous != null) && count > 1) {
497 previous = previous.__previous__;
498 --count;
499 }
500 if (previous != null) {
501 return delete previous.__previous__;
502 }
503 };
504
505 ERROR_ID = 1;
506
507 wrap_callback = function(callback, location) {
508 var new_callback, orig, trace_error;
509 orig = Error.prepareStackTrace;
510 Error.prepareStackTrace = function(x, stack) {
511 return stack;
512 };
513 trace_error = new Error();
514 Error.captureStackTrace(trace_error, arguments.callee);
515 trace_error.__stack__ = trace_error.stack;
516 Error.prepareStackTrace = orig;
517 trace_error.id = ERROR_ID++;
518 if (trace_error.stack[1]) {
519 trace_error.location = "" + (trace_error.stack[1].getFunctionName()) + " (" + (trace_error.stack[1].getFileName()) + ":" + (trace_error.stack[1].getLineNumber()) + ")";
520 } else {
521 trace_error.location = 'bad call_stack_location';
522 }
523 trace_error.__location__ = location;
524 trace_error.__previous__ = current_trace_error;
525 trace_error.__trace_count__ = current_trace_error != null ? current_trace_error.__trace_count__ + 1 : 1;
526 limit_frames(trace_error);
527 new_callback = function() {
528 var e;
529 current_trace_error = trace_error;
530 trace_error = null;
531 try {
532 return callback.apply(this, arguments);
533 } catch (_error) {
534 e = _error;
535 e.stack;
536 throw e;
537 } finally {
538 current_trace_error = null;
539 }
540 };
541 new_callback.listener = callback;
542 return new_callback;
543 };
544
545 _on = EventEmitter.prototype.on;
546
547 _addListener = EventEmitter.prototype.addListener;
548
549 _once = EventEmitter.prototype.once;
550
551 _listeners = EventEmitter.prototype.listeners;
552
553 EventEmitter.prototype.addListener = function(event, callback) {
554 var args;
555 args = Array.prototype.slice.call(arguments);
556 args[1] = wrap_callback(callback, 'EventEmitter.addListener');
557 return _addListener.apply(this, args);
558 };
559
560 EventEmitter.prototype.on = function(event, callback) {
561 var args;
562 args = Array.prototype.slice.call(arguments);
563 args[1] = wrap_callback(callback, 'EventEmitter.on');
564 return _on.apply(this, args);
565 };
566
567 EventEmitter.prototype.once = function(event, callback) {
568 var args;
569 args = Array.prototype.slice.call(arguments);
570 args[1] = wrap_callback(callback, 'EventEmitter.once');
571 return _once.apply(this, args);
572 };
573
574 EventEmitter.prototype.listeners = function(event) {
575 var l, listeners, unwrapped, _i, _len;
576 listeners = _listeners.call(this, event);
577 unwrapped = [];
578 for (_i = 0, _len = listeners.length; _i < _len; _i++) {
579 l = listeners[_i];
580 if (l.listener) {
581 unwrapped.push(l.listener);
582 } else {
583 unwrapped.push(l);
584 }
585 }
586 return unwrapped;
587 };
588
589 Object.defineProperty(EventEmitter.prototype.on, 'longjohn', {
590 writable: true,
591 enumerable: false,
592 configurable: true,
593 value: this
594 });
595
596 _nextTick = process.nextTick;
597
598 process.nextTick = function(callback) {
599 var args;
600 args = Array.prototype.slice.call(arguments);
601 args[0] = wrap_callback(callback, 'process.nextTick');
602 return _nextTick.apply(this, args);
603 };
604
605 __nextDomainTick = process._nextDomainTick;
606
607 process._nextDomainTick = function(callback) {
608 var args;
609 args = Array.prototype.slice.call(arguments);
610 args[0] = wrap_callback(callback, 'process.nextDomainTick');
611 return __nextDomainTick.apply(this, args);
612 };
613
614 _setTimeout = global.setTimeout;
615
616 _setInterval = global.setInterval;
617
618 global.setTimeout = function(callback) {
619 var args;
620 args = Array.prototype.slice.call(arguments);
621 args[0] = wrap_callback(callback, 'global.setTimeout');
622 return _setTimeout.apply(this, args);
623 };
624
625 global.setInterval = function(callback) {
626 var args;
627 args = Array.prototype.slice.call(arguments);
628 args[0] = wrap_callback(callback, 'global.setInterval');
629 return _setInterval.apply(this, args);
630 };
631
632 if (global.setImmediate != null) {
633 _setImmediate = global.setImmediate;
634 global.setImmediate = function(callback) {
635 var args;
636 args = Array.prototype.slice.call(arguments);
637 args[0] = wrap_callback(callback, 'global.setImmediate');
638 return _setImmediate.apply(this, args);
639 };
640 }
641
642 Error.prepareStackTrace = prepareStackTrace;
643
644 if (process.env.NODE_ENV === 'production') {
645 console.warn('NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime.\nIt generally should not be used in production applications.');
646 }
647
648}).call(this);
649}, {"events":3,"source-map-support":4}],3: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
650//
651// Permission is hereby granted, free of charge, to any person obtaining a
652// copy of this software and associated documentation files (the
653// "Software"), to deal in the Software without restriction, including
654// without limitation the rights to use, copy, modify, merge, publish,
655// distribute, sublicense, and/or sell copies of the Software, and to permit
656// persons to whom the Software is furnished to do so, subject to the
657// following conditions:
658//
659// The above copyright notice and this permission notice shall be included
660// in all copies or substantial portions of the Software.
661//
662// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
663// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
664// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
665// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
666// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
667// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
668// USE OR OTHER DEALINGS IN THE SOFTWARE.
669
670function EventEmitter() {
671 this._events = this._events || {};
672 this._maxListeners = this._maxListeners || undefined;
673}
674module.exports = EventEmitter;
675
676// Backwards-compat with node 0.10.x
677EventEmitter.EventEmitter = EventEmitter;
678
679EventEmitter.prototype._events = undefined;
680EventEmitter.prototype._maxListeners = undefined;
681
682// By default EventEmitters will print a warning if more than 10 listeners are
683// added to it. This is a useful default which helps finding memory leaks.
684EventEmitter.defaultMaxListeners = 10;
685
686// Obviously not all Emitters should be limited to 10. This function allows
687// that to be increased. Set to zero for unlimited.
688EventEmitter.prototype.setMaxListeners = function(n) {
689 if (!isNumber(n) || n < 0 || isNaN(n))
690 throw TypeError('n must be a positive number');
691 this._maxListeners = n;
692 return this;
693};
694
695EventEmitter.prototype.emit = function(type) {
696 var er, handler, len, args, i, listeners;
697
698 if (!this._events)
699 this._events = {};
700
701 // If there is no 'error' event listener then throw.
702 if (type === 'error') {
703 if (!this._events.error ||
704 (isObject(this._events.error) && !this._events.error.length)) {
705 er = arguments[1];
706 if (er instanceof Error) {
707 throw er; // Unhandled 'error' event
708 }
709 throw TypeError('Uncaught, unspecified "error" event.');
710 }
711 }
712
713 handler = this._events[type];
714
715 if (isUndefined(handler))
716 return false;
717
718 if (isFunction(handler)) {
719 switch (arguments.length) {
720 // fast cases
721 case 1:
722 handler.call(this);
723 break;
724 case 2:
725 handler.call(this, arguments[1]);
726 break;
727 case 3:
728 handler.call(this, arguments[1], arguments[2]);
729 break;
730 // slower
731 default:
732 args = Array.prototype.slice.call(arguments, 1);
733 handler.apply(this, args);
734 }
735 } else if (isObject(handler)) {
736 args = Array.prototype.slice.call(arguments, 1);
737 listeners = handler.slice();
738 len = listeners.length;
739 for (i = 0; i < len; i++)
740 listeners[i].apply(this, args);
741 }
742
743 return true;
744};
745
746EventEmitter.prototype.addListener = function(type, listener) {
747 var m;
748
749 if (!isFunction(listener))
750 throw TypeError('listener must be a function');
751
752 if (!this._events)
753 this._events = {};
754
755 // To avoid recursion in the case that type === "newListener"! Before
756 // adding it to the listeners, first emit "newListener".
757 if (this._events.newListener)
758 this.emit('newListener', type,
759 isFunction(listener.listener) ?
760 listener.listener : listener);
761
762 if (!this._events[type])
763 // Optimize the case of one listener. Don't need the extra array object.
764 this._events[type] = listener;
765 else if (isObject(this._events[type]))
766 // If we've already got an array, just append.
767 this._events[type].push(listener);
768 else
769 // Adding the second element, need to change to array.
770 this._events[type] = [this._events[type], listener];
771
772 // Check for listener leak
773 if (isObject(this._events[type]) && !this._events[type].warned) {
774 if (!isUndefined(this._maxListeners)) {
775 m = this._maxListeners;
776 } else {
777 m = EventEmitter.defaultMaxListeners;
778 }
779
780 if (m && m > 0 && this._events[type].length > m) {
781 this._events[type].warned = true;
782 console.error('(node) warning: possible EventEmitter memory ' +
783 'leak detected. %d listeners added. ' +
784 'Use emitter.setMaxListeners() to increase limit.',
785 this._events[type].length);
786 if (typeof console.trace === 'function') {
787 // not supported in IE 10
788 console.trace();
789 }
790 }
791 }
792
793 return this;
794};
795
796EventEmitter.prototype.on = EventEmitter.prototype.addListener;
797
798EventEmitter.prototype.once = function(type, listener) {
799 if (!isFunction(listener))
800 throw TypeError('listener must be a function');
801
802 var fired = false;
803
804 function g() {
805 this.removeListener(type, g);
806
807 if (!fired) {
808 fired = true;
809 listener.apply(this, arguments);
810 }
811 }
812
813 g.listener = listener;
814 this.on(type, g);
815
816 return this;
817};
818
819// emits a 'removeListener' event iff the listener was removed
820EventEmitter.prototype.removeListener = function(type, listener) {
821 var list, position, length, i;
822
823 if (!isFunction(listener))
824 throw TypeError('listener must be a function');
825
826 if (!this._events || !this._events[type])
827 return this;
828
829 list = this._events[type];
830 length = list.length;
831 position = -1;
832
833 if (list === listener ||
834 (isFunction(list.listener) && list.listener === listener)) {
835 delete this._events[type];
836 if (this._events.removeListener)
837 this.emit('removeListener', type, listener);
838
839 } else if (isObject(list)) {
840 for (i = length; i-- > 0;) {
841 if (list[i] === listener ||
842 (list[i].listener && list[i].listener === listener)) {
843 position = i;
844 break;
845 }
846 }
847
848 if (position < 0)
849 return this;
850
851 if (list.length === 1) {
852 list.length = 0;
853 delete this._events[type];
854 } else {
855 list.splice(position, 1);
856 }
857
858 if (this._events.removeListener)
859 this.emit('removeListener', type, listener);
860 }
861
862 return this;
863};
864
865EventEmitter.prototype.removeAllListeners = function(type) {
866 var key, listeners;
867
868 if (!this._events)
869 return this;
870
871 // not listening for removeListener, no need to emit
872 if (!this._events.removeListener) {
873 if (arguments.length === 0)
874 this._events = {};
875 else if (this._events[type])
876 delete this._events[type];
877 return this;
878 }
879
880 // emit removeListener for all listeners on all events
881 if (arguments.length === 0) {
882 for (key in this._events) {
883 if (key === 'removeListener') continue;
884 this.removeAllListeners(key);
885 }
886 this.removeAllListeners('removeListener');
887 this._events = {};
888 return this;
889 }
890
891 listeners = this._events[type];
892
893 if (isFunction(listeners)) {
894 this.removeListener(type, listeners);
895 } else if (listeners) {
896 // LIFO order
897 while (listeners.length)
898 this.removeListener(type, listeners[listeners.length - 1]);
899 }
900 delete this._events[type];
901
902 return this;
903};
904
905EventEmitter.prototype.listeners = function(type) {
906 var ret;
907 if (!this._events || !this._events[type])
908 ret = [];
909 else if (isFunction(this._events[type]))
910 ret = [this._events[type]];
911 else
912 ret = this._events[type].slice();
913 return ret;
914};
915
916EventEmitter.prototype.listenerCount = function(type) {
917 if (this._events) {
918 var evlistener = this._events[type];
919
920 if (isFunction(evlistener))
921 return 1;
922 else if (evlistener)
923 return evlistener.length;
924 }
925 return 0;
926};
927
928EventEmitter.listenerCount = function(emitter, type) {
929 return emitter.listenerCount(type);
930};
931
932function isFunction(arg) {
933 return typeof arg === 'function';
934}
935
936function isNumber(arg) {
937 return typeof arg === 'number';
938}
939
940function isObject(arg) {
941 return typeof arg === 'object' && arg !== null;
942}
943
944function isUndefined(arg) {
945 return arg === void 0;
946}
947}, {}],4: [function (exports, require, module, global) {var SourceMapConsumer = require('source-map').SourceMapConsumer;
948var path = require('path');
949var fs = require('fs');
950
951// Only install once if called multiple times
952var alreadyInstalled = false;
953
954// If true, the caches are reset before a stack trace formatting operation
955var emptyCacheBetweenOperations = false;
956
957// Maps a file path to a string containing the file contents
958var fileContentsCache = {};
959
960// Maps a file path to a source map for that file
961var sourceMapCache = {};
962
963// Regex for detecting source maps
964var reSourceMap = /^data:application\/json[^,]+base64,/;
965
966function isInBrowser() {
967 return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function'));
968}
969
970function hasGlobalProcessEventEmitter() {
971 return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
972}
973
974function retrieveFile(path) {
975 // Trim the path to make sure there is no extra whitespace.
976 path = path.trim();
977 if (path in fileContentsCache) {
978 return fileContentsCache[path];
979 }
980
981 try {
982 // Use SJAX if we are in the browser
983 if (isInBrowser()) {
984 var xhr = new XMLHttpRequest();
985 xhr.open('GET', path, false);
986 xhr.send(null);
987 var contents = null
988 if (xhr.readyState === 4 && xhr.status === 200) {
989 contents = xhr.responseText
990 }
991 }
992
993 // Otherwise, use the filesystem
994 else {
995 var contents = fs.readFileSync(path, 'utf8');
996 }
997 } catch (e) {
998 var contents = null;
999 }
1000
1001 return fileContentsCache[path] = contents;
1002}
1003
1004// Support URLs relative to a directory, but be careful about a protocol prefix
1005// in case we are in the browser (i.e. directories may start with "http://")
1006function supportRelativeURL(file, url) {
1007 if (!file) return url;
1008 var dir = path.dirname(file);
1009 var match = /^\w+:\/\/[^\/]*/.exec(dir);
1010 var protocol = match ? match[0] : '';
1011 return protocol + path.resolve(dir.slice(protocol.length), url);
1012}
1013
1014function retrieveSourceMapURL(source) {
1015 var fileData;
1016
1017 if (isInBrowser()) {
1018 var xhr = new XMLHttpRequest();
1019 xhr.open('GET', source, false);
1020 xhr.send(null);
1021 fileData = xhr.readyState === 4 ? xhr.responseText : null;
1022
1023 // Support providing a sourceMappingURL via the SourceMap header
1024 var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
1025 xhr.getResponseHeader("X-SourceMap");
1026 if (sourceMapHeader) {
1027 return sourceMapHeader;
1028 }
1029 }
1030
1031 // Get the URL of the source map
1032 fileData = retrieveFile(source);
1033 var re = /\/\/[#@]\s*sourceMappingURL=([^'"]+)\s*$/mg;
1034 // Keep executing the search to find the *last* sourceMappingURL to avoid
1035 // picking up sourceMappingURLs from comments, strings, etc.
1036 var lastMatch, match;
1037 while (match = re.exec(fileData)) lastMatch = match;
1038 if (!lastMatch) return null;
1039 return lastMatch[1];
1040};
1041
1042// Can be overridden by the retrieveSourceMap option to install. Takes a
1043// generated source filename; returns a {map, optional url} object, or null if
1044// there is no source map. The map field may be either a string or the parsed
1045// JSON object (ie, it must be a valid argument to the SourceMapConsumer
1046// constructor).
1047function retrieveSourceMap(source) {
1048 var sourceMappingURL = retrieveSourceMapURL(source);
1049 if (!sourceMappingURL) return null;
1050
1051 // Read the contents of the source map
1052 var sourceMapData;
1053 if (reSourceMap.test(sourceMappingURL)) {
1054 // Support source map URL as a data url
1055 var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
1056 sourceMapData = new Buffer(rawData, "base64").toString();
1057 sourceMappingURL = null;
1058 } else {
1059 // Support source map URLs relative to the source URL
1060 sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
1061 sourceMapData = retrieveFile(sourceMappingURL);
1062 }
1063
1064 if (!sourceMapData) {
1065 return null;
1066 }
1067
1068 return {
1069 url: sourceMappingURL,
1070 map: sourceMapData
1071 };
1072}
1073
1074function mapSourcePosition(position) {
1075 var sourceMap = sourceMapCache[position.source];
1076 if (!sourceMap) {
1077 // Call the (overrideable) retrieveSourceMap function to get the source map.
1078 var urlAndMap = retrieveSourceMap(position.source);
1079 if (urlAndMap) {
1080 sourceMap = sourceMapCache[position.source] = {
1081 url: urlAndMap.url,
1082 map: new SourceMapConsumer(urlAndMap.map)
1083 };
1084
1085 // Load all sources stored inline with the source map into the file cache
1086 // to pretend like they are already loaded. They may not exist on disk.
1087 if (sourceMap.map.sourcesContent) {
1088 sourceMap.map.sources.forEach(function(source, i) {
1089 var contents = sourceMap.map.sourcesContent[i];
1090 if (contents) {
1091 var url = supportRelativeURL(sourceMap.url, source);
1092 fileContentsCache[url] = contents;
1093 }
1094 });
1095 }
1096 } else {
1097 sourceMap = sourceMapCache[position.source] = {
1098 url: null,
1099 map: null
1100 };
1101 }
1102 }
1103
1104 // Resolve the source URL relative to the URL of the source map
1105 if (sourceMap && sourceMap.map) {
1106 var originalPosition = sourceMap.map.originalPositionFor(position);
1107
1108 // Only return the original position if a matching line was found. If no
1109 // matching line is found then we return position instead, which will cause
1110 // the stack trace to print the path and line for the compiled file. It is
1111 // better to give a precise location in the compiled file than a vague
1112 // location in the original file.
1113 if (originalPosition.source !== null) {
1114 originalPosition.source = supportRelativeURL(
1115 sourceMap.url, originalPosition.source);
1116 return originalPosition;
1117 }
1118 }
1119
1120 return position;
1121}
1122
1123// Parses code generated by FormatEvalOrigin(), a function inside V8:
1124// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
1125function mapEvalOrigin(origin) {
1126 // Most eval() calls are in this format
1127 var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
1128 if (match) {
1129 var position = mapSourcePosition({
1130 source: match[2],
1131 line: match[3],
1132 column: match[4] - 1
1133 });
1134 return 'eval at ' + match[1] + ' (' + position.source + ':' +
1135 position.line + ':' + (position.column + 1) + ')';
1136 }
1137
1138 // Parse nested eval() calls using recursion
1139 match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
1140 if (match) {
1141 return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
1142 }
1143
1144 // Make sure we still return useful information if we didn't find anything
1145 return origin;
1146}
1147
1148// This is copied almost verbatim from the V8 source code at
1149// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
1150// implementation of wrapCallSite() used to just forward to the actual source
1151// code of CallSite.prototype.toString but unfortunately a new release of V8
1152// did something to the prototype chain and broke the shim. The only fix I
1153// could find was copy/paste.
1154function CallSiteToString() {
1155 var fileName;
1156 var fileLocation = "";
1157 if (this.isNative()) {
1158 fileLocation = "native";
1159 } else {
1160 fileName = this.getScriptNameOrSourceURL();
1161 if (!fileName && this.isEval()) {
1162 fileLocation = this.getEvalOrigin();
1163 fileLocation += ", "; // Expecting source position to follow.
1164 }
1165
1166 if (fileName) {
1167 fileLocation += fileName;
1168 } else {
1169 // Source code does not originate from a file and is not native, but we
1170 // can still get the source position inside the source string, e.g. in
1171 // an eval string.
1172 fileLocation += "<anonymous>";
1173 }
1174 var lineNumber = this.getLineNumber();
1175 if (lineNumber != null) {
1176 fileLocation += ":" + lineNumber;
1177 var columnNumber = this.getColumnNumber();
1178 if (columnNumber) {
1179 fileLocation += ":" + columnNumber;
1180 }
1181 }
1182 }
1183
1184 var line = "";
1185 var functionName = this.getFunctionName();
1186 var addSuffix = true;
1187 var isConstructor = this.isConstructor();
1188 var isMethodCall = !(this.isToplevel() || isConstructor);
1189 if (isMethodCall) {
1190 var typeName = this.getTypeName();
1191 var methodName = this.getMethodName();
1192 if (functionName) {
1193 if (typeName && functionName.indexOf(typeName) != 0) {
1194 line += typeName + ".";
1195 }
1196 line += functionName;
1197 if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
1198 line += " [as " + methodName + "]";
1199 }
1200 } else {
1201 line += typeName + "." + (methodName || "<anonymous>");
1202 }
1203 } else if (isConstructor) {
1204 line += "new " + (functionName || "<anonymous>");
1205 } else if (functionName) {
1206 line += functionName;
1207 } else {
1208 line += fileLocation;
1209 addSuffix = false;
1210 }
1211 if (addSuffix) {
1212 line += " (" + fileLocation + ")";
1213 }
1214 return line;
1215}
1216
1217function cloneCallSite(frame) {
1218 var object = {};
1219 Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
1220 object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
1221 });
1222 object.toString = CallSiteToString;
1223 return object;
1224}
1225
1226function wrapCallSite(frame) {
1227 // Most call sites will return the source file from getFileName(), but code
1228 // passed to eval() ending in "//# sourceURL=..." will return the source file
1229 // from getScriptNameOrSourceURL() instead
1230 var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
1231 if (source) {
1232 var line = frame.getLineNumber();
1233 var column = frame.getColumnNumber() - 1;
1234
1235 // Fix position in Node where some (internal) code is prepended.
1236 // See https://github.com/evanw/node-source-map-support/issues/36
1237 if (line === 1 && !isInBrowser() && !frame.isEval()) {
1238 column -= 62;
1239 }
1240
1241 var position = mapSourcePosition({
1242 source: source,
1243 line: line,
1244 column: column
1245 });
1246 frame = cloneCallSite(frame);
1247 frame.getFileName = function() { return position.source; };
1248 frame.getLineNumber = function() { return position.line; };
1249 frame.getColumnNumber = function() { return position.column + 1; };
1250 frame.getScriptNameOrSourceURL = function() { return position.source; };
1251 return frame;
1252 }
1253
1254 // Code called using eval() needs special handling
1255 var origin = frame.isEval() && frame.getEvalOrigin();
1256 if (origin) {
1257 origin = mapEvalOrigin(origin);
1258 frame = cloneCallSite(frame);
1259 frame.getEvalOrigin = function() { return origin; };
1260 return frame;
1261 }
1262
1263 // If we get here then we were unable to change the source position
1264 return frame;
1265}
1266
1267// This function is part of the V8 stack trace API, for more info see:
1268// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
1269function prepareStackTrace(error, stack) {
1270 if (emptyCacheBetweenOperations) {
1271 fileContentsCache = {};
1272 sourceMapCache = {};
1273 }
1274
1275 return error + stack.map(function(frame) {
1276 return '\n at ' + wrapCallSite(frame);
1277 }).join('');
1278}
1279
1280// Generate position and snippet of original source with pointer
1281function getErrorSource(error) {
1282 var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
1283 if (match) {
1284 var source = match[1];
1285 var line = +match[2];
1286 var column = +match[3];
1287
1288 // Support the inline sourceContents inside the source map
1289 var contents = fileContentsCache[source];
1290
1291 // Support files on disk
1292 if (!contents && fs.existsSync(source)) {
1293 contents = fs.readFileSync(source, 'utf8');
1294 }
1295
1296 // Format the line from the original source code like node does
1297 if (contents) {
1298 var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
1299 if (code) {
1300 return source + ':' + line + '\n' + code + '\n' +
1301 new Array(column).join(' ') + '^';
1302 }
1303 }
1304 }
1305 return null;
1306}
1307
1308function printErrorAndExit (error) {
1309 var source = getErrorSource(error);
1310
1311 if (source) {
1312 console.error();
1313 console.error(source);
1314 }
1315
1316 console.error(error.stack);
1317 process.exit(1);
1318}
1319
1320function shimEmitUncaughtException () {
1321 var origEmit = process.emit;
1322
1323 process.emit = function (type) {
1324 if (type === 'uncaughtException') {
1325 var hasStack = (arguments[1] && arguments[1].stack);
1326 var hasListeners = (this.listeners(type).length > 0);
1327
1328 if (hasStack && !hasListeners) {
1329 return printErrorAndExit(arguments[1]);
1330 }
1331 }
1332
1333 return origEmit.apply(this, arguments);
1334 }
1335}
1336
1337exports.wrapCallSite = wrapCallSite;
1338exports.getErrorSource = getErrorSource;
1339exports.mapSourcePosition = mapSourcePosition;
1340exports.retrieveSourceMap = retrieveSourceMap;
1341
1342exports.install = function(options) {
1343 if (!alreadyInstalled) {
1344 alreadyInstalled = true;
1345 Error.prepareStackTrace = prepareStackTrace;
1346
1347 // Configure options
1348 options = options || {};
1349 var installHandler = 'handleUncaughtExceptions' in options ?
1350 options.handleUncaughtExceptions : true;
1351 emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
1352 options.emptyCacheBetweenOperations : false;
1353
1354 // Allow sources to be found by methods other than reading the files
1355 // directly from disk.
1356 if (options.retrieveFile)
1357 retrieveFile = options.retrieveFile;
1358
1359 // Allow source maps to be found by methods other than reading the files
1360 // directly from disk.
1361 if (options.retrieveSourceMap)
1362 retrieveSourceMap = options.retrieveSourceMap;
1363
1364 // Provide the option to not install the uncaught exception handler. This is
1365 // to support other uncaught exception handlers (in test frameworks, for
1366 // example). If this handler is not installed and there are no other uncaught
1367 // exception handlers, uncaught exceptions will be caught by node's built-in
1368 // exception handler and the process will still be terminated. However, the
1369 // generated JavaScript code will be shown above the stack trace instead of
1370 // the original source code.
1371 if (installHandler && hasGlobalProcessEventEmitter()) {
1372 shimEmitUncaughtException();
1373 }
1374 }
1375};
1376}, {"source-map":5,"path":8,"fs":16}],5: [function (exports, require, module, global) {/*
1377 * Copyright 2009-2011 Mozilla Foundation and contributors
1378 * Licensed under the New BSD license. See LICENSE.txt or:
1379 * http://opensource.org/licenses/BSD-3-Clause
1380 */
1381exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
1382exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
1383exports.SourceNode = require('./source-map/source-node').SourceNode;
1384}, {"./source-map/source-map-generator":6,"./source-map/source-map-consumer":13,"./source-map/source-node":15}],6: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
1385/*
1386 * Copyright 2011 Mozilla Foundation and contributors
1387 * Licensed under the New BSD license. See LICENSE or:
1388 * http://opensource.org/licenses/BSD-3-Clause
1389 */
1390if (typeof define !== 'function') {
1391 var define = require('amdefine')(module, require);
1392}
1393define(function (require, exports, module) {
1394
1395 var base64VLQ = require('./base64-vlq');
1396 var util = require('./util');
1397 var ArraySet = require('./array-set').ArraySet;
1398
1399 /**
1400 * An instance of the SourceMapGenerator represents a source map which is
1401 * being built incrementally. To create a new one, you must pass an object
1402 * with the following properties:
1403 *
1404 * - file: The filename of the generated source.
1405 * - sourceRoot: An optional root for all URLs in this source map.
1406 */
1407 function SourceMapGenerator(aArgs) {
1408 this._file = util.getArg(aArgs, 'file');
1409 this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
1410 this._sources = new ArraySet();
1411 this._names = new ArraySet();
1412 this._mappings = [];
1413 this._sourcesContents = null;
1414 }
1415
1416 SourceMapGenerator.prototype._version = 3;
1417
1418 /**
1419 * Creates a new SourceMapGenerator based on a SourceMapConsumer
1420 *
1421 * @param aSourceMapConsumer The SourceMap.
1422 */
1423 SourceMapGenerator.fromSourceMap =
1424 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
1425 var sourceRoot = aSourceMapConsumer.sourceRoot;
1426 var generator = new SourceMapGenerator({
1427 file: aSourceMapConsumer.file,
1428 sourceRoot: sourceRoot
1429 });
1430 aSourceMapConsumer.eachMapping(function (mapping) {
1431 var newMapping = {
1432 generated: {
1433 line: mapping.generatedLine,
1434 column: mapping.generatedColumn
1435 }
1436 };
1437
1438 if (mapping.source) {
1439 newMapping.source = mapping.source;
1440 if (sourceRoot) {
1441 newMapping.source = util.relative(sourceRoot, newMapping.source);
1442 }
1443
1444 newMapping.original = {
1445 line: mapping.originalLine,
1446 column: mapping.originalColumn
1447 };
1448
1449 if (mapping.name) {
1450 newMapping.name = mapping.name;
1451 }
1452 }
1453
1454 generator.addMapping(newMapping);
1455 });
1456 aSourceMapConsumer.sources.forEach(function (sourceFile) {
1457 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
1458 if (content) {
1459 generator.setSourceContent(sourceFile, content);
1460 }
1461 });
1462 return generator;
1463 };
1464
1465 /**
1466 * Add a single mapping from original source line and column to the generated
1467 * source's line and column for this source map being created. The mapping
1468 * object should have the following properties:
1469 *
1470 * - generated: An object with the generated line and column positions.
1471 * - original: An object with the original line and column positions.
1472 * - source: The original source file (relative to the sourceRoot).
1473 * - name: An optional original token name for this mapping.
1474 */
1475 SourceMapGenerator.prototype.addMapping =
1476 function SourceMapGenerator_addMapping(aArgs) {
1477 var generated = util.getArg(aArgs, 'generated');
1478 var original = util.getArg(aArgs, 'original', null);
1479 var source = util.getArg(aArgs, 'source', null);
1480 var name = util.getArg(aArgs, 'name', null);
1481
1482 this._validateMapping(generated, original, source, name);
1483
1484 if (source && !this._sources.has(source)) {
1485 this._sources.add(source);
1486 }
1487
1488 if (name && !this._names.has(name)) {
1489 this._names.add(name);
1490 }
1491
1492 this._mappings.push({
1493 generatedLine: generated.line,
1494 generatedColumn: generated.column,
1495 originalLine: original != null && original.line,
1496 originalColumn: original != null && original.column,
1497 source: source,
1498 name: name
1499 });
1500 };
1501
1502 /**
1503 * Set the source content for a source file.
1504 */
1505 SourceMapGenerator.prototype.setSourceContent =
1506 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
1507 var source = aSourceFile;
1508 if (this._sourceRoot) {
1509 source = util.relative(this._sourceRoot, source);
1510 }
1511
1512 if (aSourceContent !== null) {
1513 // Add the source content to the _sourcesContents map.
1514 // Create a new _sourcesContents map if the property is null.
1515 if (!this._sourcesContents) {
1516 this._sourcesContents = {};
1517 }
1518 this._sourcesContents[util.toSetString(source)] = aSourceContent;
1519 } else {
1520 // Remove the source file from the _sourcesContents map.
1521 // If the _sourcesContents map is empty, set the property to null.
1522 delete this._sourcesContents[util.toSetString(source)];
1523 if (Object.keys(this._sourcesContents).length === 0) {
1524 this._sourcesContents = null;
1525 }
1526 }
1527 };
1528
1529 /**
1530 * Applies the mappings of a sub-source-map for a specific source file to the
1531 * source map being generated. Each mapping to the supplied source file is
1532 * rewritten using the supplied source map. Note: The resolution for the
1533 * resulting mappings is the minimium of this map and the supplied map.
1534 *
1535 * @param aSourceMapConsumer The source map to be applied.
1536 * @param aSourceFile Optional. The filename of the source file.
1537 * If omitted, SourceMapConsumer's file property will be used.
1538 */
1539 SourceMapGenerator.prototype.applySourceMap =
1540 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
1541 // If aSourceFile is omitted, we will use the file property of the SourceMap
1542 if (!aSourceFile) {
1543 aSourceFile = aSourceMapConsumer.file;
1544 }
1545 var sourceRoot = this._sourceRoot;
1546 // Make "aSourceFile" relative if an absolute Url is passed.
1547 if (sourceRoot) {
1548 aSourceFile = util.relative(sourceRoot, aSourceFile);
1549 }
1550 // Applying the SourceMap can add and remove items from the sources and
1551 // the names array.
1552 var newSources = new ArraySet();
1553 var newNames = new ArraySet();
1554
1555 // Find mappings for the "aSourceFile"
1556 this._mappings.forEach(function (mapping) {
1557 if (mapping.source === aSourceFile && mapping.originalLine) {
1558 // Check if it can be mapped by the source map, then update the mapping.
1559 var original = aSourceMapConsumer.originalPositionFor({
1560 line: mapping.originalLine,
1561 column: mapping.originalColumn
1562 });
1563 if (original.source !== null) {
1564 // Copy mapping
1565 if (sourceRoot) {
1566 mapping.source = util.relative(sourceRoot, original.source);
1567 } else {
1568 mapping.source = original.source;
1569 }
1570 mapping.originalLine = original.line;
1571 mapping.originalColumn = original.column;
1572 if (original.name !== null && mapping.name !== null) {
1573 // Only use the identifier name if it's an identifier
1574 // in both SourceMaps
1575 mapping.name = original.name;
1576 }
1577 }
1578 }
1579
1580 var source = mapping.source;
1581 if (source && !newSources.has(source)) {
1582 newSources.add(source);
1583 }
1584
1585 var name = mapping.name;
1586 if (name && !newNames.has(name)) {
1587 newNames.add(name);
1588 }
1589
1590 }, this);
1591 this._sources = newSources;
1592 this._names = newNames;
1593
1594 // Copy sourcesContents of applied map.
1595 aSourceMapConsumer.sources.forEach(function (sourceFile) {
1596 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
1597 if (content) {
1598 if (sourceRoot) {
1599 sourceFile = util.relative(sourceRoot, sourceFile);
1600 }
1601 this.setSourceContent(sourceFile, content);
1602 }
1603 }, this);
1604 };
1605
1606 /**
1607 * A mapping can have one of the three levels of data:
1608 *
1609 * 1. Just the generated position.
1610 * 2. The Generated position, original position, and original source.
1611 * 3. Generated and original position, original source, as well as a name
1612 * token.
1613 *
1614 * To maintain consistency, we validate that any new mapping being added falls
1615 * in to one of these categories.
1616 */
1617 SourceMapGenerator.prototype._validateMapping =
1618 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
1619 aName) {
1620 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
1621 && aGenerated.line > 0 && aGenerated.column >= 0
1622 && !aOriginal && !aSource && !aName) {
1623 // Case 1.
1624 return;
1625 }
1626 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
1627 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
1628 && aGenerated.line > 0 && aGenerated.column >= 0
1629 && aOriginal.line > 0 && aOriginal.column >= 0
1630 && aSource) {
1631 // Cases 2 and 3.
1632 return;
1633 }
1634 else {
1635 throw new Error('Invalid mapping: ' + JSON.stringify({
1636 generated: aGenerated,
1637 source: aSource,
1638 original: aOriginal,
1639 name: aName
1640 }));
1641 }
1642 };
1643
1644 /**
1645 * Serialize the accumulated mappings in to the stream of base 64 VLQs
1646 * specified by the source map format.
1647 */
1648 SourceMapGenerator.prototype._serializeMappings =
1649 function SourceMapGenerator_serializeMappings() {
1650 var previousGeneratedColumn = 0;
1651 var previousGeneratedLine = 1;
1652 var previousOriginalColumn = 0;
1653 var previousOriginalLine = 0;
1654 var previousName = 0;
1655 var previousSource = 0;
1656 var result = '';
1657 var mapping;
1658
1659 // The mappings must be guaranteed to be in sorted order before we start
1660 // serializing them or else the generated line numbers (which are defined
1661 // via the ';' separators) will be all messed up. Note: it might be more
1662 // performant to maintain the sorting as we insert them, rather than as we
1663 // serialize them, but the big O is the same either way.
1664 this._mappings.sort(util.compareByGeneratedPositions);
1665
1666 for (var i = 0, len = this._mappings.length; i < len; i++) {
1667 mapping = this._mappings[i];
1668
1669 if (mapping.generatedLine !== previousGeneratedLine) {
1670 previousGeneratedColumn = 0;
1671 while (mapping.generatedLine !== previousGeneratedLine) {
1672 result += ';';
1673 previousGeneratedLine++;
1674 }
1675 }
1676 else {
1677 if (i > 0) {
1678 if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
1679 continue;
1680 }
1681 result += ',';
1682 }
1683 }
1684
1685 result += base64VLQ.encode(mapping.generatedColumn
1686 - previousGeneratedColumn);
1687 previousGeneratedColumn = mapping.generatedColumn;
1688
1689 if (mapping.source) {
1690 result += base64VLQ.encode(this._sources.indexOf(mapping.source)
1691 - previousSource);
1692 previousSource = this._sources.indexOf(mapping.source);
1693
1694 // lines are stored 0-based in SourceMap spec version 3
1695 result += base64VLQ.encode(mapping.originalLine - 1
1696 - previousOriginalLine);
1697 previousOriginalLine = mapping.originalLine - 1;
1698
1699 result += base64VLQ.encode(mapping.originalColumn
1700 - previousOriginalColumn);
1701 previousOriginalColumn = mapping.originalColumn;
1702
1703 if (mapping.name) {
1704 result += base64VLQ.encode(this._names.indexOf(mapping.name)
1705 - previousName);
1706 previousName = this._names.indexOf(mapping.name);
1707 }
1708 }
1709 }
1710
1711 return result;
1712 };
1713
1714 SourceMapGenerator.prototype._generateSourcesContent =
1715 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
1716 return aSources.map(function (source) {
1717 if (!this._sourcesContents) {
1718 return null;
1719 }
1720 if (aSourceRoot) {
1721 source = util.relative(aSourceRoot, source);
1722 }
1723 var key = util.toSetString(source);
1724 return Object.prototype.hasOwnProperty.call(this._sourcesContents,
1725 key)
1726 ? this._sourcesContents[key]
1727 : null;
1728 }, this);
1729 };
1730
1731 /**
1732 * Externalize the source map.
1733 */
1734 SourceMapGenerator.prototype.toJSON =
1735 function SourceMapGenerator_toJSON() {
1736 var map = {
1737 version: this._version,
1738 file: this._file,
1739 sources: this._sources.toArray(),
1740 names: this._names.toArray(),
1741 mappings: this._serializeMappings()
1742 };
1743 if (this._sourceRoot) {
1744 map.sourceRoot = this._sourceRoot;
1745 }
1746 if (this._sourcesContents) {
1747 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
1748 }
1749
1750 return map;
1751 };
1752
1753 /**
1754 * Render the source map being generated to a string.
1755 */
1756 SourceMapGenerator.prototype.toString =
1757 function SourceMapGenerator_toString() {
1758 return JSON.stringify(this);
1759 };
1760
1761 exports.SourceMapGenerator = SourceMapGenerator;
1762
1763});
1764}, {"amdefine":7,"./base64-vlq":9,"./util":11,"./array-set":12}],7: [function (exports, require, module, global) {/** vim: et:ts=4:sw=4:sts=4
1765 * @license amdefine 1.0.0 Copyright (c) 2011-2015, The Dojo Foundation All Rights Reserved.
1766 * Available via the MIT or new BSD license.
1767 * see: http://github.com/jrburke/amdefine for details
1768 */
1769
1770/*jslint node: true */
1771/*global module, process */
1772'use strict';
1773
1774/**
1775 * Creates a define for node.
1776 * @param {Object} module the "module" object that is defined by Node for the
1777 * current module.
1778 * @param {Function} [requireFn]. Node's require function for the current module.
1779 * It only needs to be passed in Node versions before 0.5, when module.require
1780 * did not exist.
1781 * @returns {Function} a define function that is usable for the current node
1782 * module.
1783 */
1784function amdefine(module, requireFn) {
1785 'use strict';
1786 var defineCache = {},
1787 loaderCache = {},
1788 alreadyCalled = false,
1789 path = require('path'),
1790 makeRequire, stringRequire;
1791
1792 /**
1793 * Trims the . and .. from an array of path segments.
1794 * It will keep a leading path segment if a .. will become
1795 * the first path segment, to help with module name lookups,
1796 * which act like paths, but can be remapped. But the end result,
1797 * all paths that use this function should look normalized.
1798 * NOTE: this method MODIFIES the input array.
1799 * @param {Array} ary the array of path segments.
1800 */
1801 function trimDots(ary) {
1802 var i, part;
1803 for (i = 0; ary[i]; i+= 1) {
1804 part = ary[i];
1805 if (part === '.') {
1806 ary.splice(i, 1);
1807 i -= 1;
1808 } else if (part === '..') {
1809 if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
1810 //End of the line. Keep at least one non-dot
1811 //path segment at the front so it can be mapped
1812 //correctly to disk. Otherwise, there is likely
1813 //no path mapping for a path starting with '..'.
1814 //This can still fail, but catches the most reasonable
1815 //uses of ..
1816 break;
1817 } else if (i > 0) {
1818 ary.splice(i - 1, 2);
1819 i -= 2;
1820 }
1821 }
1822 }
1823 }
1824
1825 function normalize(name, baseName) {
1826 var baseParts;
1827
1828 //Adjust any relative paths.
1829 if (name && name.charAt(0) === '.') {
1830 //If have a base name, try to normalize against it,
1831 //otherwise, assume it is a top-level require that will
1832 //be relative to baseUrl in the end.
1833 if (baseName) {
1834 baseParts = baseName.split('/');
1835 baseParts = baseParts.slice(0, baseParts.length - 1);
1836 baseParts = baseParts.concat(name.split('/'));
1837 trimDots(baseParts);
1838 name = baseParts.join('/');
1839 }
1840 }
1841
1842 return name;
1843 }
1844
1845 /**
1846 * Create the normalize() function passed to a loader plugin's
1847 * normalize method.
1848 */
1849 function makeNormalize(relName) {
1850 return function (name) {
1851 return normalize(name, relName);
1852 };
1853 }
1854
1855 function makeLoad(id) {
1856 function load(value) {
1857 loaderCache[id] = value;
1858 }
1859
1860 load.fromText = function (id, text) {
1861 //This one is difficult because the text can/probably uses
1862 //define, and any relative paths and requires should be relative
1863 //to that id was it would be found on disk. But this would require
1864 //bootstrapping a module/require fairly deeply from node core.
1865 //Not sure how best to go about that yet.
1866 throw new Error('amdefine does not implement load.fromText');
1867 };
1868
1869 return load;
1870 }
1871
1872 makeRequire = function (systemRequire, exports, module, relId) {
1873 function amdRequire(deps, callback) {
1874 if (typeof deps === 'string') {
1875 //Synchronous, single module require('')
1876 return stringRequire(systemRequire, exports, module, deps, relId);
1877 } else {
1878 //Array of dependencies with a callback.
1879
1880 //Convert the dependencies to modules.
1881 deps = deps.map(function (depName) {
1882 return stringRequire(systemRequire, exports, module, depName, relId);
1883 });
1884
1885 //Wait for next tick to call back the require call.
1886 if (callback) {
1887 process.nextTick(function () {
1888 callback.apply(null, deps);
1889 });
1890 }
1891 }
1892 }
1893
1894 amdRequire.toUrl = function (filePath) {
1895 if (filePath.indexOf('.') === 0) {
1896 return normalize(filePath, path.dirname(module.filename));
1897 } else {
1898 return filePath;
1899 }
1900 };
1901
1902 return amdRequire;
1903 };
1904
1905 //Favor explicit value, passed in if the module wants to support Node 0.4.
1906 requireFn = requireFn || function req() {
1907 return module.require.apply(module, arguments);
1908 };
1909
1910 function runFactory(id, deps, factory) {
1911 var r, e, m, result;
1912
1913 if (id) {
1914 e = loaderCache[id] = {};
1915 m = {
1916 id: id,
1917 uri: __filename,
1918 exports: e
1919 };
1920 r = makeRequire(requireFn, e, m, id);
1921 } else {
1922 //Only support one define call per file
1923 if (alreadyCalled) {
1924 throw new Error('amdefine with no module ID cannot be called more than once per file.');
1925 }
1926 alreadyCalled = true;
1927
1928 //Use the real variables from node
1929 //Use module.exports for exports, since
1930 //the exports in here is amdefine exports.
1931 e = module.exports;
1932 m = module;
1933 r = makeRequire(requireFn, e, m, module.id);
1934 }
1935
1936 //If there are dependencies, they are strings, so need
1937 //to convert them to dependency values.
1938 if (deps) {
1939 deps = deps.map(function (depName) {
1940 return r(depName);
1941 });
1942 }
1943
1944 //Call the factory with the right dependencies.
1945 if (typeof factory === 'function') {
1946 result = factory.apply(m.exports, deps);
1947 } else {
1948 result = factory;
1949 }
1950
1951 if (result !== undefined) {
1952 m.exports = result;
1953 if (id) {
1954 loaderCache[id] = m.exports;
1955 }
1956 }
1957 }
1958
1959 stringRequire = function (systemRequire, exports, module, id, relId) {
1960 //Split the ID by a ! so that
1961 var index = id.indexOf('!'),
1962 originalId = id,
1963 prefix, plugin;
1964
1965 if (index === -1) {
1966 id = normalize(id, relId);
1967
1968 //Straight module lookup. If it is one of the special dependencies,
1969 //deal with it, otherwise, delegate to node.
1970 if (id === 'require') {
1971 return makeRequire(systemRequire, exports, module, relId);
1972 } else if (id === 'exports') {
1973 return exports;
1974 } else if (id === 'module') {
1975 return module;
1976 } else if (loaderCache.hasOwnProperty(id)) {
1977 return loaderCache[id];
1978 } else if (defineCache[id]) {
1979 runFactory.apply(null, defineCache[id]);
1980 return loaderCache[id];
1981 } else {
1982 if(systemRequire) {
1983 return systemRequire(originalId);
1984 } else {
1985 throw new Error('No module with ID: ' + id);
1986 }
1987 }
1988 } else {
1989 //There is a plugin in play.
1990 prefix = id.substring(0, index);
1991 id = id.substring(index + 1, id.length);
1992
1993 plugin = stringRequire(systemRequire, exports, module, prefix, relId);
1994
1995 if (plugin.normalize) {
1996 id = plugin.normalize(id, makeNormalize(relId));
1997 } else {
1998 //Normalize the ID normally.
1999 id = normalize(id, relId);
2000 }
2001
2002 if (loaderCache[id]) {
2003 return loaderCache[id];
2004 } else {
2005 plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
2006
2007 return loaderCache[id];
2008 }
2009 }
2010 };
2011
2012 //Create a define function specific to the module asking for amdefine.
2013 function define(id, deps, factory) {
2014 if (Array.isArray(id)) {
2015 factory = deps;
2016 deps = id;
2017 id = undefined;
2018 } else if (typeof id !== 'string') {
2019 factory = id;
2020 id = deps = undefined;
2021 }
2022
2023 if (deps && !Array.isArray(deps)) {
2024 factory = deps;
2025 deps = undefined;
2026 }
2027
2028 if (!deps) {
2029 deps = ['require', 'exports', 'module'];
2030 }
2031
2032 //Set up properties for this module. If an ID, then use
2033 //internal cache. If no ID, then use the external variables
2034 //for this node module.
2035 if (id) {
2036 //Put the module in deep freeze until there is a
2037 //require call for it.
2038 defineCache[id] = [id, deps, factory];
2039 } else {
2040 runFactory(id, deps, factory);
2041 }
2042 }
2043
2044 //define.require, which has access to all the values in the
2045 //cache. Useful for AMD modules that all have IDs in the file,
2046 //but need to finally export a value to node based on one of those
2047 //IDs.
2048 define.require = function (id) {
2049 if (loaderCache[id]) {
2050 return loaderCache[id];
2051 }
2052
2053 if (defineCache[id]) {
2054 runFactory.apply(null, defineCache[id]);
2055 return loaderCache[id];
2056 }
2057 };
2058
2059 define.amd = {};
2060
2061 return define;
2062}
2063
2064module.exports = amdefine;
2065}, {"path":8}],8: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
2066//
2067// Permission is hereby granted, free of charge, to any person obtaining a
2068// copy of this software and associated documentation files (the
2069// "Software"), to deal in the Software without restriction, including
2070// without limitation the rights to use, copy, modify, merge, publish,
2071// distribute, sublicense, and/or sell copies of the Software, and to permit
2072// persons to whom the Software is furnished to do so, subject to the
2073// following conditions:
2074//
2075// The above copyright notice and this permission notice shall be included
2076// in all copies or substantial portions of the Software.
2077//
2078// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2079// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2080// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2081// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2082// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2083// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2084// USE OR OTHER DEALINGS IN THE SOFTWARE.
2085
2086// resolves . and .. elements in a path array with directory names there
2087// must be no slashes, empty elements, or device names (c:\) in the array
2088// (so also no leading and trailing slashes - it does not distinguish
2089// relative and absolute paths)
2090function normalizeArray(parts, allowAboveRoot) {
2091 // if the path tries to go above the root, `up` ends up > 0
2092 var up = 0;
2093 for (var i = parts.length - 1; i >= 0; i--) {
2094 var last = parts[i];
2095 if (last === '.') {
2096 parts.splice(i, 1);
2097 } else if (last === '..') {
2098 parts.splice(i, 1);
2099 up++;
2100 } else if (up) {
2101 parts.splice(i, 1);
2102 up--;
2103 }
2104 }
2105
2106 // if the path is allowed to go above the root, restore leading ..s
2107 if (allowAboveRoot) {
2108 for (; up--; up) {
2109 parts.unshift('..');
2110 }
2111 }
2112
2113 return parts;
2114}
2115
2116// Split a filename into [root, dir, basename, ext], unix version
2117// 'root' is just a slash, or nothing.
2118var splitPathRe =
2119 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
2120var splitPath = function(filename) {
2121 return splitPathRe.exec(filename).slice(1);
2122};
2123
2124// path.resolve([from ...], to)
2125// posix version
2126exports.resolve = function() {
2127 var resolvedPath = '',
2128 resolvedAbsolute = false;
2129
2130 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
2131 var path = (i >= 0) ? arguments[i] : process.cwd();
2132
2133 // Skip empty and invalid entries
2134 if (typeof path !== 'string') {
2135 throw new TypeError('Arguments to path.resolve must be strings');
2136 } else if (!path) {
2137 continue;
2138 }
2139
2140 resolvedPath = path + '/' + resolvedPath;
2141 resolvedAbsolute = path.charAt(0) === '/';
2142 }
2143
2144 // At this point the path should be resolved to a full absolute path, but
2145 // handle relative paths to be safe (might happen when process.cwd() fails)
2146
2147 // Normalize the path
2148 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
2149 return !!p;
2150 }), !resolvedAbsolute).join('/');
2151
2152 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
2153};
2154
2155// path.normalize(path)
2156// posix version
2157exports.normalize = function(path) {
2158 var isAbsolute = exports.isAbsolute(path),
2159 trailingSlash = substr(path, -1) === '/';
2160
2161 // Normalize the path
2162 path = normalizeArray(filter(path.split('/'), function(p) {
2163 return !!p;
2164 }), !isAbsolute).join('/');
2165
2166 if (!path && !isAbsolute) {
2167 path = '.';
2168 }
2169 if (path && trailingSlash) {
2170 path += '/';
2171 }
2172
2173 return (isAbsolute ? '/' : '') + path;
2174};
2175
2176// posix version
2177exports.isAbsolute = function(path) {
2178 return path.charAt(0) === '/';
2179};
2180
2181// posix version
2182exports.join = function() {
2183 var paths = Array.prototype.slice.call(arguments, 0);
2184 return exports.normalize(filter(paths, function(p, index) {
2185 if (typeof p !== 'string') {
2186 throw new TypeError('Arguments to path.join must be strings');
2187 }
2188 return p;
2189 }).join('/'));
2190};
2191
2192
2193// path.relative(from, to)
2194// posix version
2195exports.relative = function(from, to) {
2196 from = exports.resolve(from).substr(1);
2197 to = exports.resolve(to).substr(1);
2198
2199 function trim(arr) {
2200 var start = 0;
2201 for (; start < arr.length; start++) {
2202 if (arr[start] !== '') break;
2203 }
2204
2205 var end = arr.length - 1;
2206 for (; end >= 0; end--) {
2207 if (arr[end] !== '') break;
2208 }
2209
2210 if (start > end) return [];
2211 return arr.slice(start, end - start + 1);
2212 }
2213
2214 var fromParts = trim(from.split('/'));
2215 var toParts = trim(to.split('/'));
2216
2217 var length = Math.min(fromParts.length, toParts.length);
2218 var samePartsLength = length;
2219 for (var i = 0; i < length; i++) {
2220 if (fromParts[i] !== toParts[i]) {
2221 samePartsLength = i;
2222 break;
2223 }
2224 }
2225
2226 var outputParts = [];
2227 for (var i = samePartsLength; i < fromParts.length; i++) {
2228 outputParts.push('..');
2229 }
2230
2231 outputParts = outputParts.concat(toParts.slice(samePartsLength));
2232
2233 return outputParts.join('/');
2234};
2235
2236exports.sep = '/';
2237exports.delimiter = ':';
2238
2239exports.dirname = function(path) {
2240 var result = splitPath(path),
2241 root = result[0],
2242 dir = result[1];
2243
2244 if (!root && !dir) {
2245 // No dirname whatsoever
2246 return '.';
2247 }
2248
2249 if (dir) {
2250 // It has a dirname, strip trailing slash
2251 dir = dir.substr(0, dir.length - 1);
2252 }
2253
2254 return root + dir;
2255};
2256
2257
2258exports.basename = function(path, ext) {
2259 var f = splitPath(path)[2];
2260 // TODO: make this comparison case-insensitive on windows?
2261 if (ext && f.substr(-1 * ext.length) === ext) {
2262 f = f.substr(0, f.length - ext.length);
2263 }
2264 return f;
2265};
2266
2267
2268exports.extname = function(path) {
2269 return splitPath(path)[3];
2270};
2271
2272function filter (xs, f) {
2273 if (xs.filter) return xs.filter(f);
2274 var res = [];
2275 for (var i = 0; i < xs.length; i++) {
2276 if (f(xs[i], i, xs)) res.push(xs[i]);
2277 }
2278 return res;
2279}
2280
2281// String.prototype.substr - negative index don't work in IE8
2282var substr = 'ab'.substr(-1) === 'b'
2283 ? function (str, start, len) { return str.substr(start, len) }
2284 : function (str, start, len) {
2285 if (start < 0) start = str.length + start;
2286 return str.substr(start, len);
2287 }
2288;
2289}, {}],9: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
2290/*
2291 * Copyright 2011 Mozilla Foundation and contributors
2292 * Licensed under the New BSD license. See LICENSE or:
2293 * http://opensource.org/licenses/BSD-3-Clause
2294 *
2295 * Based on the Base 64 VLQ implementation in Closure Compiler:
2296 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
2297 *
2298 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
2299 * Redistribution and use in source and binary forms, with or without
2300 * modification, are permitted provided that the following conditions are
2301 * met:
2302 *
2303 * * Redistributions of source code must retain the above copyright
2304 * notice, this list of conditions and the following disclaimer.
2305 * * Redistributions in binary form must reproduce the above
2306 * copyright notice, this list of conditions and the following
2307 * disclaimer in the documentation and/or other materials provided
2308 * with the distribution.
2309 * * Neither the name of Google Inc. nor the names of its
2310 * contributors may be used to endorse or promote products derived
2311 * from this software without specific prior written permission.
2312 *
2313 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2314 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2315 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2316 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2317 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2318 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2319 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2320 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2321 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2322 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2323 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2324 */
2325if (typeof define !== 'function') {
2326 var define = require('amdefine')(module, require);
2327}
2328define(function (require, exports, module) {
2329
2330 var base64 = require('./base64');
2331
2332 // A single base 64 digit can contain 6 bits of data. For the base 64 variable
2333 // length quantities we use in the source map spec, the first bit is the sign,
2334 // the next four bits are the actual value, and the 6th bit is the
2335 // continuation bit. The continuation bit tells us whether there are more
2336 // digits in this value following this digit.
2337 //
2338 // Continuation
2339 // | Sign
2340 // | |
2341 // V V
2342 // 101011
2343
2344 var VLQ_BASE_SHIFT = 5;
2345
2346 // binary: 100000
2347 var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
2348
2349 // binary: 011111
2350 var VLQ_BASE_MASK = VLQ_BASE - 1;
2351
2352 // binary: 100000
2353 var VLQ_CONTINUATION_BIT = VLQ_BASE;
2354
2355 /**
2356 * Converts from a two-complement value to a value where the sign bit is
2357 * is placed in the least significant bit. For example, as decimals:
2358 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
2359 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
2360 */
2361 function toVLQSigned(aValue) {
2362 return aValue < 0
2363 ? ((-aValue) << 1) + 1
2364 : (aValue << 1) + 0;
2365 }
2366
2367 /**
2368 * Converts to a two-complement value from a value where the sign bit is
2369 * is placed in the least significant bit. For example, as decimals:
2370 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
2371 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
2372 */
2373 function fromVLQSigned(aValue) {
2374 var isNegative = (aValue & 1) === 1;
2375 var shifted = aValue >> 1;
2376 return isNegative
2377 ? -shifted
2378 : shifted;
2379 }
2380
2381 /**
2382 * Returns the base 64 VLQ encoded value.
2383 */
2384 exports.encode = function base64VLQ_encode(aValue) {
2385 var encoded = "";
2386 var digit;
2387
2388 var vlq = toVLQSigned(aValue);
2389
2390 do {
2391 digit = vlq & VLQ_BASE_MASK;
2392 vlq >>>= VLQ_BASE_SHIFT;
2393 if (vlq > 0) {
2394 // There are still more digits in this value, so we must make sure the
2395 // continuation bit is marked.
2396 digit |= VLQ_CONTINUATION_BIT;
2397 }
2398 encoded += base64.encode(digit);
2399 } while (vlq > 0);
2400
2401 return encoded;
2402 };
2403
2404 /**
2405 * Decodes the next base 64 VLQ value from the given string and returns the
2406 * value and the rest of the string.
2407 */
2408 exports.decode = function base64VLQ_decode(aStr) {
2409 var i = 0;
2410 var strLen = aStr.length;
2411 var result = 0;
2412 var shift = 0;
2413 var continuation, digit;
2414
2415 do {
2416 if (i >= strLen) {
2417 throw new Error("Expected more digits in base 64 VLQ value.");
2418 }
2419 digit = base64.decode(aStr.charAt(i++));
2420 continuation = !!(digit & VLQ_CONTINUATION_BIT);
2421 digit &= VLQ_BASE_MASK;
2422 result = result + (digit << shift);
2423 shift += VLQ_BASE_SHIFT;
2424 } while (continuation);
2425
2426 return {
2427 value: fromVLQSigned(result),
2428 rest: aStr.slice(i)
2429 };
2430 };
2431
2432});
2433}, {"amdefine":7,"./base64":10}],10: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
2434/*
2435 * Copyright 2011 Mozilla Foundation and contributors
2436 * Licensed under the New BSD license. See LICENSE or:
2437 * http://opensource.org/licenses/BSD-3-Clause
2438 */
2439if (typeof define !== 'function') {
2440 var define = require('amdefine')(module, require);
2441}
2442define(function (require, exports, module) {
2443
2444 var charToIntMap = {};
2445 var intToCharMap = {};
2446
2447 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
2448 .split('')
2449 .forEach(function (ch, index) {
2450 charToIntMap[ch] = index;
2451 intToCharMap[index] = ch;
2452 });
2453
2454 /**
2455 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
2456 */
2457 exports.encode = function base64_encode(aNumber) {
2458 if (aNumber in intToCharMap) {
2459 return intToCharMap[aNumber];
2460 }
2461 throw new TypeError("Must be between 0 and 63: " + aNumber);
2462 };
2463
2464 /**
2465 * Decode a single base 64 digit to an integer.
2466 */
2467 exports.decode = function base64_decode(aChar) {
2468 if (aChar in charToIntMap) {
2469 return charToIntMap[aChar];
2470 }
2471 throw new TypeError("Not a valid base 64 digit: " + aChar);
2472 };
2473
2474});
2475}, {"amdefine":7}],11: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
2476/*
2477 * Copyright 2011 Mozilla Foundation and contributors
2478 * Licensed under the New BSD license. See LICENSE or:
2479 * http://opensource.org/licenses/BSD-3-Clause
2480 */
2481if (typeof define !== 'function') {
2482 var define = require('amdefine')(module, require);
2483}
2484define(function (require, exports, module) {
2485
2486 /**
2487 * This is a helper function for getting values from parameter/options
2488 * objects.
2489 *
2490 * @param args The object we are extracting values from
2491 * @param name The name of the property we are getting.
2492 * @param defaultValue An optional value to return if the property is missing
2493 * from the object. If this is not specified and the property is missing, an
2494 * error will be thrown.
2495 */
2496 function getArg(aArgs, aName, aDefaultValue) {
2497 if (aName in aArgs) {
2498 return aArgs[aName];
2499 } else if (arguments.length === 3) {
2500 return aDefaultValue;
2501 } else {
2502 throw new Error('"' + aName + '" is a required argument.');
2503 }
2504 }
2505 exports.getArg = getArg;
2506
2507 var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
2508 var dataUrlRegexp = /^data:.+\,.+/;
2509
2510 function urlParse(aUrl) {
2511 var match = aUrl.match(urlRegexp);
2512 if (!match) {
2513 return null;
2514 }
2515 return {
2516 scheme: match[1],
2517 auth: match[3],
2518 host: match[4],
2519 port: match[6],
2520 path: match[7]
2521 };
2522 }
2523 exports.urlParse = urlParse;
2524
2525 function urlGenerate(aParsedUrl) {
2526 var url = aParsedUrl.scheme + "://";
2527 if (aParsedUrl.auth) {
2528 url += aParsedUrl.auth + "@"
2529 }
2530 if (aParsedUrl.host) {
2531 url += aParsedUrl.host;
2532 }
2533 if (aParsedUrl.port) {
2534 url += ":" + aParsedUrl.port
2535 }
2536 if (aParsedUrl.path) {
2537 url += aParsedUrl.path;
2538 }
2539 return url;
2540 }
2541 exports.urlGenerate = urlGenerate;
2542
2543 function join(aRoot, aPath) {
2544 var url;
2545
2546 if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
2547 return aPath;
2548 }
2549
2550 if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
2551 url.path = aPath;
2552 return urlGenerate(url);
2553 }
2554
2555 return aRoot.replace(/\/$/, '') + '/' + aPath;
2556 }
2557 exports.join = join;
2558
2559 /**
2560 * Because behavior goes wacky when you set `__proto__` on objects, we
2561 * have to prefix all the strings in our set with an arbitrary character.
2562 *
2563 * See https://github.com/mozilla/source-map/pull/31 and
2564 * https://github.com/mozilla/source-map/issues/30
2565 *
2566 * @param String aStr
2567 */
2568 function toSetString(aStr) {
2569 return '$' + aStr;
2570 }
2571 exports.toSetString = toSetString;
2572
2573 function fromSetString(aStr) {
2574 return aStr.substr(1);
2575 }
2576 exports.fromSetString = fromSetString;
2577
2578 function relative(aRoot, aPath) {
2579 aRoot = aRoot.replace(/\/$/, '');
2580
2581 var url = urlParse(aRoot);
2582 if (aPath.charAt(0) == "/" && url && url.path == "/") {
2583 return aPath.slice(1);
2584 }
2585
2586 return aPath.indexOf(aRoot + '/') === 0
2587 ? aPath.substr(aRoot.length + 1)
2588 : aPath;
2589 }
2590 exports.relative = relative;
2591
2592 function strcmp(aStr1, aStr2) {
2593 var s1 = aStr1 || "";
2594 var s2 = aStr2 || "";
2595 return (s1 > s2) - (s1 < s2);
2596 }
2597
2598 /**
2599 * Comparator between two mappings where the original positions are compared.
2600 *
2601 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
2602 * mappings with the same original source/line/column, but different generated
2603 * line and column the same. Useful when searching for a mapping with a
2604 * stubbed out mapping.
2605 */
2606 function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
2607 var cmp;
2608
2609 cmp = strcmp(mappingA.source, mappingB.source);
2610 if (cmp) {
2611 return cmp;
2612 }
2613
2614 cmp = mappingA.originalLine - mappingB.originalLine;
2615 if (cmp) {
2616 return cmp;
2617 }
2618
2619 cmp = mappingA.originalColumn - mappingB.originalColumn;
2620 if (cmp || onlyCompareOriginal) {
2621 return cmp;
2622 }
2623
2624 cmp = strcmp(mappingA.name, mappingB.name);
2625 if (cmp) {
2626 return cmp;
2627 }
2628
2629 cmp = mappingA.generatedLine - mappingB.generatedLine;
2630 if (cmp) {
2631 return cmp;
2632 }
2633
2634 return mappingA.generatedColumn - mappingB.generatedColumn;
2635 };
2636 exports.compareByOriginalPositions = compareByOriginalPositions;
2637
2638 /**
2639 * Comparator between two mappings where the generated positions are
2640 * compared.
2641 *
2642 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
2643 * mappings with the same generated line and column, but different
2644 * source/name/original line and column the same. Useful when searching for a
2645 * mapping with a stubbed out mapping.
2646 */
2647 function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
2648 var cmp;
2649
2650 cmp = mappingA.generatedLine - mappingB.generatedLine;
2651 if (cmp) {
2652 return cmp;
2653 }
2654
2655 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
2656 if (cmp || onlyCompareGenerated) {
2657 return cmp;
2658 }
2659
2660 cmp = strcmp(mappingA.source, mappingB.source);
2661 if (cmp) {
2662 return cmp;
2663 }
2664
2665 cmp = mappingA.originalLine - mappingB.originalLine;
2666 if (cmp) {
2667 return cmp;
2668 }
2669
2670 cmp = mappingA.originalColumn - mappingB.originalColumn;
2671 if (cmp) {
2672 return cmp;
2673 }
2674
2675 return strcmp(mappingA.name, mappingB.name);
2676 };
2677 exports.compareByGeneratedPositions = compareByGeneratedPositions;
2678
2679});
2680}, {"amdefine":7}],12: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
2681/*
2682 * Copyright 2011 Mozilla Foundation and contributors
2683 * Licensed under the New BSD license. See LICENSE or:
2684 * http://opensource.org/licenses/BSD-3-Clause
2685 */
2686if (typeof define !== 'function') {
2687 var define = require('amdefine')(module, require);
2688}
2689define(function (require, exports, module) {
2690
2691 var util = require('./util');
2692
2693 /**
2694 * A data structure which is a combination of an array and a set. Adding a new
2695 * member is O(1), testing for membership is O(1), and finding the index of an
2696 * element is O(1). Removing elements from the set is not supported. Only
2697 * strings are supported for membership.
2698 */
2699 function ArraySet() {
2700 this._array = [];
2701 this._set = {};
2702 }
2703
2704 /**
2705 * Static method for creating ArraySet instances from an existing array.
2706 */
2707 ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
2708 var set = new ArraySet();
2709 for (var i = 0, len = aArray.length; i < len; i++) {
2710 set.add(aArray[i], aAllowDuplicates);
2711 }
2712 return set;
2713 };
2714
2715 /**
2716 * Add the given string to this set.
2717 *
2718 * @param String aStr
2719 */
2720 ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
2721 var isDuplicate = this.has(aStr);
2722 var idx = this._array.length;
2723 if (!isDuplicate || aAllowDuplicates) {
2724 this._array.push(aStr);
2725 }
2726 if (!isDuplicate) {
2727 this._set[util.toSetString(aStr)] = idx;
2728 }
2729 };
2730
2731 /**
2732 * Is the given string a member of this set?
2733 *
2734 * @param String aStr
2735 */
2736 ArraySet.prototype.has = function ArraySet_has(aStr) {
2737 return Object.prototype.hasOwnProperty.call(this._set,
2738 util.toSetString(aStr));
2739 };
2740
2741 /**
2742 * What is the index of the given string in the array?
2743 *
2744 * @param String aStr
2745 */
2746 ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
2747 if (this.has(aStr)) {
2748 return this._set[util.toSetString(aStr)];
2749 }
2750 throw new Error('"' + aStr + '" is not in the set.');
2751 };
2752
2753 /**
2754 * What is the element at the given index?
2755 *
2756 * @param Number aIdx
2757 */
2758 ArraySet.prototype.at = function ArraySet_at(aIdx) {
2759 if (aIdx >= 0 && aIdx < this._array.length) {
2760 return this._array[aIdx];
2761 }
2762 throw new Error('No element indexed by ' + aIdx);
2763 };
2764
2765 /**
2766 * Returns the array representation of this set (which has the proper indices
2767 * indicated by indexOf). Note that this is a copy of the internal array used
2768 * for storing the members so that no one can mess with internal state.
2769 */
2770 ArraySet.prototype.toArray = function ArraySet_toArray() {
2771 return this._array.slice();
2772 };
2773
2774 exports.ArraySet = ArraySet;
2775
2776});
2777}, {"amdefine":7,"./util":11}],13: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
2778/*
2779 * Copyright 2011 Mozilla Foundation and contributors
2780 * Licensed under the New BSD license. See LICENSE or:
2781 * http://opensource.org/licenses/BSD-3-Clause
2782 */
2783if (typeof define !== 'function') {
2784 var define = require('amdefine')(module, require);
2785}
2786define(function (require, exports, module) {
2787
2788 var util = require('./util');
2789 var binarySearch = require('./binary-search');
2790 var ArraySet = require('./array-set').ArraySet;
2791 var base64VLQ = require('./base64-vlq');
2792
2793 /**
2794 * A SourceMapConsumer instance represents a parsed source map which we can
2795 * query for information about the original file positions by giving it a file
2796 * position in the generated source.
2797 *
2798 * The only parameter is the raw source map (either as a JSON string, or
2799 * already parsed to an object). According to the spec, source maps have the
2800 * following attributes:
2801 *
2802 * - version: Which version of the source map spec this map is following.
2803 * - sources: An array of URLs to the original source files.
2804 * - names: An array of identifiers which can be referrenced by individual mappings.
2805 * - sourceRoot: Optional. The URL root from which all sources are relative.
2806 * - sourcesContent: Optional. An array of contents of the original source files.
2807 * - mappings: A string of base64 VLQs which contain the actual mappings.
2808 * - file: The generated file this source map is associated with.
2809 *
2810 * Here is an example source map, taken from the source map spec[0]:
2811 *
2812 * {
2813 * version : 3,
2814 * file: "out.js",
2815 * sourceRoot : "",
2816 * sources: ["foo.js", "bar.js"],
2817 * names: ["src", "maps", "are", "fun"],
2818 * mappings: "AA,AB;;ABCDE;"
2819 * }
2820 *
2821 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
2822 */
2823 function SourceMapConsumer(aSourceMap) {
2824 var sourceMap = aSourceMap;
2825 if (typeof aSourceMap === 'string') {
2826 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
2827 }
2828
2829 var version = util.getArg(sourceMap, 'version');
2830 var sources = util.getArg(sourceMap, 'sources');
2831 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
2832 // requires the array) to play nice here.
2833 var names = util.getArg(sourceMap, 'names', []);
2834 var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
2835 var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
2836 var mappings = util.getArg(sourceMap, 'mappings');
2837 var file = util.getArg(sourceMap, 'file', null);
2838
2839 // Once again, Sass deviates from the spec and supplies the version as a
2840 // string rather than a number, so we use loose equality checking here.
2841 if (version != this._version) {
2842 throw new Error('Unsupported version: ' + version);
2843 }
2844
2845 // Pass `true` below to allow duplicate names and sources. While source maps
2846 // are intended to be compressed and deduplicated, the TypeScript compiler
2847 // sometimes generates source maps with duplicates in them. See Github issue
2848 // #72 and bugzil.la/889492.
2849 this._names = ArraySet.fromArray(names, true);
2850 this._sources = ArraySet.fromArray(sources, true);
2851
2852 this.sourceRoot = sourceRoot;
2853 this.sourcesContent = sourcesContent;
2854 this._mappings = mappings;
2855 this.file = file;
2856 }
2857
2858 /**
2859 * Create a SourceMapConsumer from a SourceMapGenerator.
2860 *
2861 * @param SourceMapGenerator aSourceMap
2862 * The source map that will be consumed.
2863 * @returns SourceMapConsumer
2864 */
2865 SourceMapConsumer.fromSourceMap =
2866 function SourceMapConsumer_fromSourceMap(aSourceMap) {
2867 var smc = Object.create(SourceMapConsumer.prototype);
2868
2869 smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
2870 smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
2871 smc.sourceRoot = aSourceMap._sourceRoot;
2872 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
2873 smc.sourceRoot);
2874 smc.file = aSourceMap._file;
2875
2876 smc.__generatedMappings = aSourceMap._mappings.slice()
2877 .sort(util.compareByGeneratedPositions);
2878 smc.__originalMappings = aSourceMap._mappings.slice()
2879 .sort(util.compareByOriginalPositions);
2880
2881 return smc;
2882 };
2883
2884 /**
2885 * The version of the source mapping spec that we are consuming.
2886 */
2887 SourceMapConsumer.prototype._version = 3;
2888
2889 /**
2890 * The list of original sources.
2891 */
2892 Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
2893 get: function () {
2894 return this._sources.toArray().map(function (s) {
2895 return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
2896 }, this);
2897 }
2898 });
2899
2900 // `__generatedMappings` and `__originalMappings` are arrays that hold the
2901 // parsed mapping coordinates from the source map's "mappings" attribute. They
2902 // are lazily instantiated, accessed via the `_generatedMappings` and
2903 // `_originalMappings` getters respectively, and we only parse the mappings
2904 // and create these arrays once queried for a source location. We jump through
2905 // these hoops because there can be many thousands of mappings, and parsing
2906 // them is expensive, so we only want to do it if we must.
2907 //
2908 // Each object in the arrays is of the form:
2909 //
2910 // {
2911 // generatedLine: The line number in the generated code,
2912 // generatedColumn: The column number in the generated code,
2913 // source: The path to the original source file that generated this
2914 // chunk of code,
2915 // originalLine: The line number in the original source that
2916 // corresponds to this chunk of generated code,
2917 // originalColumn: The column number in the original source that
2918 // corresponds to this chunk of generated code,
2919 // name: The name of the original symbol which generated this chunk of
2920 // code.
2921 // }
2922 //
2923 // All properties except for `generatedLine` and `generatedColumn` can be
2924 // `null`.
2925 //
2926 // `_generatedMappings` is ordered by the generated positions.
2927 //
2928 // `_originalMappings` is ordered by the original positions.
2929
2930 SourceMapConsumer.prototype.__generatedMappings = null;
2931 Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
2932 get: function () {
2933 if (!this.__generatedMappings) {
2934 this.__generatedMappings = [];
2935 this.__originalMappings = [];
2936 this._parseMappings(this._mappings, this.sourceRoot);
2937 }
2938
2939 return this.__generatedMappings;
2940 }
2941 });
2942
2943 SourceMapConsumer.prototype.__originalMappings = null;
2944 Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
2945 get: function () {
2946 if (!this.__originalMappings) {
2947 this.__generatedMappings = [];
2948 this.__originalMappings = [];
2949 this._parseMappings(this._mappings, this.sourceRoot);
2950 }
2951
2952 return this.__originalMappings;
2953 }
2954 });
2955
2956 /**
2957 * Parse the mappings in a string in to a data structure which we can easily
2958 * query (the ordered arrays in the `this.__generatedMappings` and
2959 * `this.__originalMappings` properties).
2960 */
2961 SourceMapConsumer.prototype._parseMappings =
2962 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
2963 var generatedLine = 1;
2964 var previousGeneratedColumn = 0;
2965 var previousOriginalLine = 0;
2966 var previousOriginalColumn = 0;
2967 var previousSource = 0;
2968 var previousName = 0;
2969 var mappingSeparator = /^[,;]/;
2970 var str = aStr;
2971 var mapping;
2972 var temp;
2973
2974 while (str.length > 0) {
2975 if (str.charAt(0) === ';') {
2976 generatedLine++;
2977 str = str.slice(1);
2978 previousGeneratedColumn = 0;
2979 }
2980 else if (str.charAt(0) === ',') {
2981 str = str.slice(1);
2982 }
2983 else {
2984 mapping = {};
2985 mapping.generatedLine = generatedLine;
2986
2987 // Generated column.
2988 temp = base64VLQ.decode(str);
2989 mapping.generatedColumn = previousGeneratedColumn + temp.value;
2990 previousGeneratedColumn = mapping.generatedColumn;
2991 str = temp.rest;
2992
2993 if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
2994 // Original source.
2995 temp = base64VLQ.decode(str);
2996 mapping.source = this._sources.at(previousSource + temp.value);
2997 previousSource += temp.value;
2998 str = temp.rest;
2999 if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
3000 throw new Error('Found a source, but no line and column');
3001 }
3002
3003 // Original line.
3004 temp = base64VLQ.decode(str);
3005 mapping.originalLine = previousOriginalLine + temp.value;
3006 previousOriginalLine = mapping.originalLine;
3007 // Lines are stored 0-based
3008 mapping.originalLine += 1;
3009 str = temp.rest;
3010 if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
3011 throw new Error('Found a source and line, but no column');
3012 }
3013
3014 // Original column.
3015 temp = base64VLQ.decode(str);
3016 mapping.originalColumn = previousOriginalColumn + temp.value;
3017 previousOriginalColumn = mapping.originalColumn;
3018 str = temp.rest;
3019
3020 if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
3021 // Original name.
3022 temp = base64VLQ.decode(str);
3023 mapping.name = this._names.at(previousName + temp.value);
3024 previousName += temp.value;
3025 str = temp.rest;
3026 }
3027 }
3028
3029 this.__generatedMappings.push(mapping);
3030 if (typeof mapping.originalLine === 'number') {
3031 this.__originalMappings.push(mapping);
3032 }
3033 }
3034 }
3035
3036 this.__generatedMappings.sort(util.compareByGeneratedPositions);
3037 this.__originalMappings.sort(util.compareByOriginalPositions);
3038 };
3039
3040 /**
3041 * Find the mapping that best matches the hypothetical "needle" mapping that
3042 * we are searching for in the given "haystack" of mappings.
3043 */
3044 SourceMapConsumer.prototype._findMapping =
3045 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
3046 aColumnName, aComparator) {
3047 // To return the position we are searching for, we must first find the
3048 // mapping for the given position and then return the opposite position it
3049 // points to. Because the mappings are sorted, we can use binary search to
3050 // find the best mapping.
3051
3052 if (aNeedle[aLineName] <= 0) {
3053 throw new TypeError('Line must be greater than or equal to 1, got '
3054 + aNeedle[aLineName]);
3055 }
3056 if (aNeedle[aColumnName] < 0) {
3057 throw new TypeError('Column must be greater than or equal to 0, got '
3058 + aNeedle[aColumnName]);
3059 }
3060
3061 return binarySearch.search(aNeedle, aMappings, aComparator);
3062 };
3063
3064 /**
3065 * Returns the original source, line, and column information for the generated
3066 * source's line and column positions provided. The only argument is an object
3067 * with the following properties:
3068 *
3069 * - line: The line number in the generated source.
3070 * - column: The column number in the generated source.
3071 *
3072 * and an object is returned with the following properties:
3073 *
3074 * - source: The original source file, or null.
3075 * - line: The line number in the original source, or null.
3076 * - column: The column number in the original source, or null.
3077 * - name: The original identifier, or null.
3078 */
3079 SourceMapConsumer.prototype.originalPositionFor =
3080 function SourceMapConsumer_originalPositionFor(aArgs) {
3081 var needle = {
3082 generatedLine: util.getArg(aArgs, 'line'),
3083 generatedColumn: util.getArg(aArgs, 'column')
3084 };
3085
3086 var mapping = this._findMapping(needle,
3087 this._generatedMappings,
3088 "generatedLine",
3089 "generatedColumn",
3090 util.compareByGeneratedPositions);
3091
3092 if (mapping) {
3093 var source = util.getArg(mapping, 'source', null);
3094 if (source && this.sourceRoot) {
3095 source = util.join(this.sourceRoot, source);
3096 }
3097 return {
3098 source: source,
3099 line: util.getArg(mapping, 'originalLine', null),
3100 column: util.getArg(mapping, 'originalColumn', null),
3101 name: util.getArg(mapping, 'name', null)
3102 };
3103 }
3104
3105 return {
3106 source: null,
3107 line: null,
3108 column: null,
3109 name: null
3110 };
3111 };
3112
3113 /**
3114 * Returns the original source content. The only argument is the url of the
3115 * original source file. Returns null if no original source content is
3116 * availible.
3117 */
3118 SourceMapConsumer.prototype.sourceContentFor =
3119 function SourceMapConsumer_sourceContentFor(aSource) {
3120 if (!this.sourcesContent) {
3121 return null;
3122 }
3123
3124 if (this.sourceRoot) {
3125 aSource = util.relative(this.sourceRoot, aSource);
3126 }
3127
3128 if (this._sources.has(aSource)) {
3129 return this.sourcesContent[this._sources.indexOf(aSource)];
3130 }
3131
3132 var url;
3133 if (this.sourceRoot
3134 && (url = util.urlParse(this.sourceRoot))) {
3135 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
3136 // many users. We can help them out when they expect file:// URIs to
3137 // behave like it would if they were running a local HTTP server. See
3138 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
3139 var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
3140 if (url.scheme == "file"
3141 && this._sources.has(fileUriAbsPath)) {
3142 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
3143 }
3144
3145 if ((!url.path || url.path == "/")
3146 && this._sources.has("/" + aSource)) {
3147 return this.sourcesContent[this._sources.indexOf("/" + aSource)];
3148 }
3149 }
3150
3151 throw new Error('"' + aSource + '" is not in the SourceMap.');
3152 };
3153
3154 /**
3155 * Returns the generated line and column information for the original source,
3156 * line, and column positions provided. The only argument is an object with
3157 * the following properties:
3158 *
3159 * - source: The filename of the original source.
3160 * - line: The line number in the original source.
3161 * - column: The column number in the original source.
3162 *
3163 * and an object is returned with the following properties:
3164 *
3165 * - line: The line number in the generated source, or null.
3166 * - column: The column number in the generated source, or null.
3167 */
3168 SourceMapConsumer.prototype.generatedPositionFor =
3169 function SourceMapConsumer_generatedPositionFor(aArgs) {
3170 var needle = {
3171 source: util.getArg(aArgs, 'source'),
3172 originalLine: util.getArg(aArgs, 'line'),
3173 originalColumn: util.getArg(aArgs, 'column')
3174 };
3175
3176 if (this.sourceRoot) {
3177 needle.source = util.relative(this.sourceRoot, needle.source);
3178 }
3179
3180 var mapping = this._findMapping(needle,
3181 this._originalMappings,
3182 "originalLine",
3183 "originalColumn",
3184 util.compareByOriginalPositions);
3185
3186 if (mapping) {
3187 return {
3188 line: util.getArg(mapping, 'generatedLine', null),
3189 column: util.getArg(mapping, 'generatedColumn', null)
3190 };
3191 }
3192
3193 return {
3194 line: null,
3195 column: null
3196 };
3197 };
3198
3199 SourceMapConsumer.GENERATED_ORDER = 1;
3200 SourceMapConsumer.ORIGINAL_ORDER = 2;
3201
3202 /**
3203 * Iterate over each mapping between an original source/line/column and a
3204 * generated line/column in this source map.
3205 *
3206 * @param Function aCallback
3207 * The function that is called with each mapping.
3208 * @param Object aContext
3209 * Optional. If specified, this object will be the value of `this` every
3210 * time that `aCallback` is called.
3211 * @param aOrder
3212 * Either `SourceMapConsumer.GENERATED_ORDER` or
3213 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
3214 * iterate over the mappings sorted by the generated file's line/column
3215 * order or the original's source/line/column order, respectively. Defaults to
3216 * `SourceMapConsumer.GENERATED_ORDER`.
3217 */
3218 SourceMapConsumer.prototype.eachMapping =
3219 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
3220 var context = aContext || null;
3221 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
3222
3223 var mappings;
3224 switch (order) {
3225 case SourceMapConsumer.GENERATED_ORDER:
3226 mappings = this._generatedMappings;
3227 break;
3228 case SourceMapConsumer.ORIGINAL_ORDER:
3229 mappings = this._originalMappings;
3230 break;
3231 default:
3232 throw new Error("Unknown order of iteration.");
3233 }
3234
3235 var sourceRoot = this.sourceRoot;
3236 mappings.map(function (mapping) {
3237 var source = mapping.source;
3238 if (source && sourceRoot) {
3239 source = util.join(sourceRoot, source);
3240 }
3241 return {
3242 source: source,
3243 generatedLine: mapping.generatedLine,
3244 generatedColumn: mapping.generatedColumn,
3245 originalLine: mapping.originalLine,
3246 originalColumn: mapping.originalColumn,
3247 name: mapping.name
3248 };
3249 }).forEach(aCallback, context);
3250 };
3251
3252 exports.SourceMapConsumer = SourceMapConsumer;
3253
3254});
3255}, {"amdefine":7,"./util":11,"./binary-search":14,"./array-set":12,"./base64-vlq":9}],14: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
3256/*
3257 * Copyright 2011 Mozilla Foundation and contributors
3258 * Licensed under the New BSD license. See LICENSE or:
3259 * http://opensource.org/licenses/BSD-3-Clause
3260 */
3261if (typeof define !== 'function') {
3262 var define = require('amdefine')(module, require);
3263}
3264define(function (require, exports, module) {
3265
3266 /**
3267 * Recursive implementation of binary search.
3268 *
3269 * @param aLow Indices here and lower do not contain the needle.
3270 * @param aHigh Indices here and higher do not contain the needle.
3271 * @param aNeedle The element being searched for.
3272 * @param aHaystack The non-empty array being searched.
3273 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
3274 */
3275 function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
3276 // This function terminates when one of the following is true:
3277 //
3278 // 1. We find the exact element we are looking for.
3279 //
3280 // 2. We did not find the exact element, but we can return the next
3281 // closest element that is less than that element.
3282 //
3283 // 3. We did not find the exact element, and there is no next-closest
3284 // element which is less than the one we are searching for, so we
3285 // return null.
3286 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
3287 var cmp = aCompare(aNeedle, aHaystack[mid], true);
3288 if (cmp === 0) {
3289 // Found the element we are looking for.
3290 return aHaystack[mid];
3291 }
3292 else if (cmp > 0) {
3293 // aHaystack[mid] is greater than our needle.
3294 if (aHigh - mid > 1) {
3295 // The element is in the upper half.
3296 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
3297 }
3298 // We did not find an exact match, return the next closest one
3299 // (termination case 2).
3300 return aHaystack[mid];
3301 }
3302 else {
3303 // aHaystack[mid] is less than our needle.
3304 if (mid - aLow > 1) {
3305 // The element is in the lower half.
3306 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
3307 }
3308 // The exact needle element was not found in this haystack. Determine if
3309 // we are in termination case (2) or (3) and return the appropriate thing.
3310 return aLow < 0
3311 ? null
3312 : aHaystack[aLow];
3313 }
3314 }
3315
3316 /**
3317 * This is an implementation of binary search which will always try and return
3318 * the next lowest value checked if there is no exact hit. This is because
3319 * mappings between original and generated line/col pairs are single points,
3320 * and there is an implicit region between each of them, so a miss just means
3321 * that you aren't on the very start of a region.
3322 *
3323 * @param aNeedle The element you are looking for.
3324 * @param aHaystack The array that is being searched.
3325 * @param aCompare A function which takes the needle and an element in the
3326 * array and returns -1, 0, or 1 depending on whether the needle is less
3327 * than, equal to, or greater than the element, respectively.
3328 */
3329 exports.search = function search(aNeedle, aHaystack, aCompare) {
3330 return aHaystack.length > 0
3331 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
3332 : null;
3333 };
3334
3335});
3336}, {"amdefine":7}],15: [function (exports, require, module, global) {/* -*- Mode: js; js-indent-level: 2; -*- */
3337/*
3338 * Copyright 2011 Mozilla Foundation and contributors
3339 * Licensed under the New BSD license. See LICENSE or:
3340 * http://opensource.org/licenses/BSD-3-Clause
3341 */
3342if (typeof define !== 'function') {
3343 var define = require('amdefine')(module, require);
3344}
3345define(function (require, exports, module) {
3346
3347 var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
3348 var util = require('./util');
3349
3350 /**
3351 * SourceNodes provide a way to abstract over interpolating/concatenating
3352 * snippets of generated JavaScript source code while maintaining the line and
3353 * column information associated with the original source code.
3354 *
3355 * @param aLine The original line number.
3356 * @param aColumn The original column number.
3357 * @param aSource The original source's filename.
3358 * @param aChunks Optional. An array of strings which are snippets of
3359 * generated JS, or other SourceNodes.
3360 * @param aName The original identifier.
3361 */
3362 function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
3363 this.children = [];
3364 this.sourceContents = {};
3365 this.line = aLine === undefined ? null : aLine;
3366 this.column = aColumn === undefined ? null : aColumn;
3367 this.source = aSource === undefined ? null : aSource;
3368 this.name = aName === undefined ? null : aName;
3369 if (aChunks != null) this.add(aChunks);
3370 }
3371
3372 /**
3373 * Creates a SourceNode from generated code and a SourceMapConsumer.
3374 *
3375 * @param aGeneratedCode The generated code
3376 * @param aSourceMapConsumer The SourceMap for the generated code
3377 */
3378 SourceNode.fromStringWithSourceMap =
3379 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
3380 // The SourceNode we want to fill with the generated code
3381 // and the SourceMap
3382 var node = new SourceNode();
3383
3384 // The generated code
3385 // Processed fragments are removed from this array.
3386 var remainingLines = aGeneratedCode.split('\n');
3387
3388 // We need to remember the position of "remainingLines"
3389 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
3390
3391 // The generate SourceNodes we need a code range.
3392 // To extract it current and last mapping is used.
3393 // Here we store the last mapping.
3394 var lastMapping = null;
3395
3396 aSourceMapConsumer.eachMapping(function (mapping) {
3397 if (lastMapping === null) {
3398 // We add the generated code until the first mapping
3399 // to the SourceNode without any mapping.
3400 // Each line is added as separate string.
3401 while (lastGeneratedLine < mapping.generatedLine) {
3402 node.add(remainingLines.shift() + "\n");
3403 lastGeneratedLine++;
3404 }
3405 if (lastGeneratedColumn < mapping.generatedColumn) {
3406 var nextLine = remainingLines[0];
3407 node.add(nextLine.substr(0, mapping.generatedColumn));
3408 remainingLines[0] = nextLine.substr(mapping.generatedColumn);
3409 lastGeneratedColumn = mapping.generatedColumn;
3410 }
3411 } else {
3412 // We add the code from "lastMapping" to "mapping":
3413 // First check if there is a new line in between.
3414 if (lastGeneratedLine < mapping.generatedLine) {
3415 var code = "";
3416 // Associate full lines with "lastMapping"
3417 do {
3418 code += remainingLines.shift() + "\n";
3419 lastGeneratedLine++;
3420 lastGeneratedColumn = 0;
3421 } while (lastGeneratedLine < mapping.generatedLine);
3422 // When we reached the correct line, we add code until we
3423 // reach the correct column too.
3424 if (lastGeneratedColumn < mapping.generatedColumn) {
3425 var nextLine = remainingLines[0];
3426 code += nextLine.substr(0, mapping.generatedColumn);
3427 remainingLines[0] = nextLine.substr(mapping.generatedColumn);
3428 lastGeneratedColumn = mapping.generatedColumn;
3429 }
3430 // Create the SourceNode.
3431 addMappingWithCode(lastMapping, code);
3432 } else {
3433 // There is no new line in between.
3434 // Associate the code between "lastGeneratedColumn" and
3435 // "mapping.generatedColumn" with "lastMapping"
3436 var nextLine = remainingLines[0];
3437 var code = nextLine.substr(0, mapping.generatedColumn -
3438 lastGeneratedColumn);
3439 remainingLines[0] = nextLine.substr(mapping.generatedColumn -
3440 lastGeneratedColumn);
3441 lastGeneratedColumn = mapping.generatedColumn;
3442 addMappingWithCode(lastMapping, code);
3443 }
3444 }
3445 lastMapping = mapping;
3446 }, this);
3447 // We have processed all mappings.
3448 // Associate the remaining code in the current line with "lastMapping"
3449 // and add the remaining lines without any mapping
3450 addMappingWithCode(lastMapping, remainingLines.join("\n"));
3451
3452 // Copy sourcesContent into SourceNode
3453 aSourceMapConsumer.sources.forEach(function (sourceFile) {
3454 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
3455 if (content) {
3456 node.setSourceContent(sourceFile, content);
3457 }
3458 });
3459
3460 return node;
3461
3462 function addMappingWithCode(mapping, code) {
3463 if (mapping === null || mapping.source === undefined) {
3464 node.add(code);
3465 } else {
3466 node.add(new SourceNode(mapping.originalLine,
3467 mapping.originalColumn,
3468 mapping.source,
3469 code,
3470 mapping.name));
3471 }
3472 }
3473 };
3474
3475 /**
3476 * Add a chunk of generated JS to this source node.
3477 *
3478 * @param aChunk A string snippet of generated JS code, another instance of
3479 * SourceNode, or an array where each member is one of those things.
3480 */
3481 SourceNode.prototype.add = function SourceNode_add(aChunk) {
3482 if (Array.isArray(aChunk)) {
3483 aChunk.forEach(function (chunk) {
3484 this.add(chunk);
3485 }, this);
3486 }
3487 else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
3488 if (aChunk) {
3489 this.children.push(aChunk);
3490 }
3491 }
3492 else {
3493 throw new TypeError(
3494 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
3495 );
3496 }
3497 return this;
3498 };
3499
3500 /**
3501 * Add a chunk of generated JS to the beginning of this source node.
3502 *
3503 * @param aChunk A string snippet of generated JS code, another instance of
3504 * SourceNode, or an array where each member is one of those things.
3505 */
3506 SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
3507 if (Array.isArray(aChunk)) {
3508 for (var i = aChunk.length-1; i >= 0; i--) {
3509 this.prepend(aChunk[i]);
3510 }
3511 }
3512 else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
3513 this.children.unshift(aChunk);
3514 }
3515 else {
3516 throw new TypeError(
3517 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
3518 );
3519 }
3520 return this;
3521 };
3522
3523 /**
3524 * Walk over the tree of JS snippets in this node and its children. The
3525 * walking function is called once for each snippet of JS and is passed that
3526 * snippet and the its original associated source's line/column location.
3527 *
3528 * @param aFn The traversal function.
3529 */
3530 SourceNode.prototype.walk = function SourceNode_walk(aFn) {
3531 var chunk;
3532 for (var i = 0, len = this.children.length; i < len; i++) {
3533 chunk = this.children[i];
3534 if (chunk instanceof SourceNode) {
3535 chunk.walk(aFn);
3536 }
3537 else {
3538 if (chunk !== '') {
3539 aFn(chunk, { source: this.source,
3540 line: this.line,
3541 column: this.column,
3542 name: this.name });
3543 }
3544 }
3545 }
3546 };
3547
3548 /**
3549 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
3550 * each of `this.children`.
3551 *
3552 * @param aSep The separator.
3553 */
3554 SourceNode.prototype.join = function SourceNode_join(aSep) {
3555 var newChildren;
3556 var i;
3557 var len = this.children.length;
3558 if (len > 0) {
3559 newChildren = [];
3560 for (i = 0; i < len-1; i++) {
3561 newChildren.push(this.children[i]);
3562 newChildren.push(aSep);
3563 }
3564 newChildren.push(this.children[i]);
3565 this.children = newChildren;
3566 }
3567 return this;
3568 };
3569
3570 /**
3571 * Call String.prototype.replace on the very right-most source snippet. Useful
3572 * for trimming whitespace from the end of a source node, etc.
3573 *
3574 * @param aPattern The pattern to replace.
3575 * @param aReplacement The thing to replace the pattern with.
3576 */
3577 SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
3578 var lastChild = this.children[this.children.length - 1];
3579 if (lastChild instanceof SourceNode) {
3580 lastChild.replaceRight(aPattern, aReplacement);
3581 }
3582 else if (typeof lastChild === 'string') {
3583 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
3584 }
3585 else {
3586 this.children.push(''.replace(aPattern, aReplacement));
3587 }
3588 return this;
3589 };
3590
3591 /**
3592 * Set the source content for a source file. This will be added to the SourceMapGenerator
3593 * in the sourcesContent field.
3594 *
3595 * @param aSourceFile The filename of the source file
3596 * @param aSourceContent The content of the source file
3597 */
3598 SourceNode.prototype.setSourceContent =
3599 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
3600 this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
3601 };
3602
3603 /**
3604 * Walk over the tree of SourceNodes. The walking function is called for each
3605 * source file content and is passed the filename and source content.
3606 *
3607 * @param aFn The traversal function.
3608 */
3609 SourceNode.prototype.walkSourceContents =
3610 function SourceNode_walkSourceContents(aFn) {
3611 for (var i = 0, len = this.children.length; i < len; i++) {
3612 if (this.children[i] instanceof SourceNode) {
3613 this.children[i].walkSourceContents(aFn);
3614 }
3615 }
3616
3617 var sources = Object.keys(this.sourceContents);
3618 for (var i = 0, len = sources.length; i < len; i++) {
3619 aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
3620 }
3621 };
3622
3623 /**
3624 * Return the string representation of this source node. Walks over the tree
3625 * and concatenates all the various snippets together to one string.
3626 */
3627 SourceNode.prototype.toString = function SourceNode_toString() {
3628 var str = "";
3629 this.walk(function (chunk) {
3630 str += chunk;
3631 });
3632 return str;
3633 };
3634
3635 /**
3636 * Returns the string representation of this source node along with a source
3637 * map.
3638 */
3639 SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
3640 var generated = {
3641 code: "",
3642 line: 1,
3643 column: 0
3644 };
3645 var map = new SourceMapGenerator(aArgs);
3646 var sourceMappingActive = false;
3647 var lastOriginalSource = null;
3648 var lastOriginalLine = null;
3649 var lastOriginalColumn = null;
3650 var lastOriginalName = null;
3651 this.walk(function (chunk, original) {
3652 generated.code += chunk;
3653 if (original.source !== null
3654 && original.line !== null
3655 && original.column !== null) {
3656 if(lastOriginalSource !== original.source
3657 || lastOriginalLine !== original.line
3658 || lastOriginalColumn !== original.column
3659 || lastOriginalName !== original.name) {
3660 map.addMapping({
3661 source: original.source,
3662 original: {
3663 line: original.line,
3664 column: original.column
3665 },
3666 generated: {
3667 line: generated.line,
3668 column: generated.column
3669 },
3670 name: original.name
3671 });
3672 }
3673 lastOriginalSource = original.source;
3674 lastOriginalLine = original.line;
3675 lastOriginalColumn = original.column;
3676 lastOriginalName = original.name;
3677 sourceMappingActive = true;
3678 } else if (sourceMappingActive) {
3679 map.addMapping({
3680 generated: {
3681 line: generated.line,
3682 column: generated.column
3683 }
3684 });
3685 lastOriginalSource = null;
3686 sourceMappingActive = false;
3687 }
3688 chunk.split('').forEach(function (ch) {
3689 if (ch === '\n') {
3690 generated.line++;
3691 generated.column = 0;
3692 } else {
3693 generated.column++;
3694 }
3695 });
3696 });
3697 this.walkSourceContents(function (sourceFile, sourceContent) {
3698 map.setSourceContent(sourceFile, sourceContent);
3699 });
3700
3701 return { code: generated.code, map: map };
3702 };
3703
3704 exports.SourceNode = SourceNode;
3705
3706});
3707}, {"amdefine":7,"./source-map-generator":6,"./util":11}],16: [function (exports, require, module, global) {var leveljs = require('level-js');
3708var levelup = require('levelup');
3709var fs = require('level-filesystem');
3710
3711var db = levelup('level-filesystem', {db:leveljs});
3712module.exports = fs(db);}, {"level-js":17,"levelup":40,"level-filesystem":83}],17: [function (exports, require, module, global) {module.exports = Level
3713
3714var IDB = require('idb-wrapper')
3715var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
3716var util = require('util')
3717var Iterator = require('./iterator')
3718var isBuffer = require('isbuffer')
3719var xtend = require('xtend')
3720var toBuffer = require('typedarray-to-buffer')
3721
3722function Level(location) {
3723 if (!(this instanceof Level)) return new Level(location)
3724 if (!location) throw new Error("constructor requires at least a location argument")
3725 this.IDBOptions = {}
3726 this.location = location
3727}
3728
3729util.inherits(Level, AbstractLevelDOWN)
3730
3731Level.prototype._open = function(options, callback) {
3732 var self = this
3733
3734 var idbOpts = {
3735 storeName: this.location,
3736 autoIncrement: false,
3737 keyPath: null,
3738 onStoreReady: function () {
3739 callback && callback(null, self.idb)
3740 },
3741 onError: function(err) {
3742 callback && callback(err)
3743 }
3744 }
3745
3746 xtend(idbOpts, options)
3747 this.IDBOptions = idbOpts
3748 this.idb = new IDB(idbOpts)
3749}
3750
3751Level.prototype._get = function (key, options, callback) {
3752 this.idb.get(key, function (value) {
3753 if (value === undefined) {
3754 // 'NotFound' error, consistent with LevelDOWN API
3755 return callback(new Error('NotFound'))
3756 }
3757 // by default return buffers, unless explicitly told not to
3758 var asBuffer = true
3759 if (options.asBuffer === false) asBuffer = false
3760 if (options.raw) asBuffer = false
3761 if (asBuffer) {
3762 if (value instanceof Uint8Array) value = toBuffer(value)
3763 else value = new Buffer(String(value))
3764 }
3765 return callback(null, value, key)
3766 }, callback)
3767}
3768
3769Level.prototype._del = function(id, options, callback) {
3770 this.idb.remove(id, callback, callback)
3771}
3772
3773Level.prototype._put = function (key, value, options, callback) {
3774 if (value instanceof ArrayBuffer) {
3775 value = toBuffer(new Uint8Array(value))
3776 }
3777 var obj = this.convertEncoding(key, value, options)
3778 if (Buffer.isBuffer(obj.value)) {
3779 obj.value = new Uint8Array(value.toArrayBuffer())
3780 }
3781 this.idb.put(obj.key, obj.value, function() { callback() }, callback)
3782}
3783
3784Level.prototype.convertEncoding = function(key, value, options) {
3785 if (options.raw) return {key: key, value: value}
3786 if (value) {
3787 var stringed = value.toString()
3788 if (stringed === 'NaN') value = 'NaN'
3789 }
3790 var valEnc = options.valueEncoding
3791 var obj = {key: key, value: value}
3792 if (value && (!valEnc || valEnc !== 'binary')) {
3793 if (typeof obj.value !== 'object') {
3794 obj.value = stringed
3795 }
3796 }
3797 return obj
3798}
3799
3800Level.prototype.iterator = function (options) {
3801 if (typeof options !== 'object') options = {}
3802 return new Iterator(this.idb, options)
3803}
3804
3805Level.prototype._batch = function (array, options, callback) {
3806 var op
3807 var i
3808 var k
3809 var copiedOp
3810 var currentOp
3811 var modified = []
3812
3813 if (array.length === 0) return setTimeout(callback, 0)
3814
3815 for (i = 0; i < array.length; i++) {
3816 copiedOp = {}
3817 currentOp = array[i]
3818 modified[i] = copiedOp
3819
3820 var converted = this.convertEncoding(currentOp.key, currentOp.value, options)
3821 currentOp.key = converted.key
3822 currentOp.value = converted.value
3823
3824 for (k in currentOp) {
3825 if (k === 'type' && currentOp[k] == 'del') {
3826 copiedOp[k] = 'remove'
3827 } else {
3828 copiedOp[k] = currentOp[k]
3829 }
3830 }
3831 }
3832
3833 return this.idb.batch(modified, function(){ callback() }, callback)
3834}
3835
3836Level.prototype._close = function (callback) {
3837 this.idb.db.close()
3838 callback()
3839}
3840
3841Level.prototype._approximateSize = function (start, end, callback) {
3842 var err = new Error('Not implemented')
3843 if (callback)
3844 return callback(err)
3845
3846 throw err
3847}
3848
3849Level.prototype._isBuffer = function (obj) {
3850 return Buffer.isBuffer(obj)
3851}
3852
3853Level.destroy = function (db, callback) {
3854 if (typeof db === 'object') {
3855 var prefix = db.IDBOptions.storePrefix || 'IDBWrapper-'
3856 var dbname = db.location
3857 } else {
3858 var prefix = 'IDBWrapper-'
3859 var dbname = db
3860 }
3861 var request = indexedDB.deleteDatabase(prefix + dbname)
3862 request.onsuccess = function() {
3863 callback()
3864 }
3865 request.onerror = function(err) {
3866 callback(err)
3867 }
3868}
3869
3870var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) {
3871 if (obj === null || obj === undefined)
3872 return new Error(type + ' cannot be `null` or `undefined`')
3873 if (obj === null || obj === undefined)
3874 return new Error(type + ' cannot be `null` or `undefined`')
3875 if (isBuffer(obj) && obj.byteLength === 0)
3876 return new Error(type + ' cannot be an empty ArrayBuffer')
3877 if (String(obj) === '')
3878 return new Error(type + ' cannot be an empty String')
3879 if (obj.length === 0)
3880 return new Error(type + ' cannot be an empty Array')
3881}
3882}, {"idb-wrapper":18,"abstract-leveldown":19,"util":23,"./iterator":26,"isbuffer":28,"xtend":33,"typedarray-to-buffer":39}],18: [function (exports, require, module, global) {/*global window:false, self:false, define:false, module:false */
3883
3884/**
3885 * @license IDBWrapper - A cross-browser wrapper for IndexedDB
3886 * Version 1.6.0
3887 * Copyright (c) 2011 - 2015 Jens Arps
3888 * http://jensarps.de/
3889 *
3890 * Licensed under the MIT (X11) license
3891 */
3892
3893(function (name, definition, global) {
3894 if (typeof define === 'function') {
3895 define(definition);
3896 } else if (typeof module !== 'undefined' && module.exports) {
3897 module.exports = definition();
3898 } else {
3899 global[name] = definition();
3900 }
3901})('IDBStore', function () {
3902
3903 'use strict';
3904
3905 var defaultErrorHandler = function (error) {
3906 throw error;
3907 };
3908 var defaultSuccessHandler = function () {};
3909
3910 var defaults = {
3911 storeName: 'Store',
3912 storePrefix: 'IDBWrapper-',
3913 dbVersion: 1,
3914 keyPath: 'id',
3915 autoIncrement: true,
3916 onStoreReady: function () {
3917 },
3918 onError: defaultErrorHandler,
3919 indexes: []
3920 };
3921
3922 /**
3923 *
3924 * The IDBStore constructor
3925 *
3926 * @constructor
3927 * @name IDBStore
3928 * @version 1.6.0
3929 *
3930 * @param {Object} [kwArgs] An options object used to configure the store and
3931 * set callbacks
3932 * @param {String} [kwArgs.storeName='Store'] The name of the store
3933 * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is
3934 * internally used to construct the name of the database, which will be
3935 * kwArgs.storePrefix + kwArgs.storeName
3936 * @param {Number} [kwArgs.dbVersion=1] The version of the store
3937 * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to
3938 * setup IDBWrapper to work with out-of-line keys, you need to set this to
3939 * `null`
3940 * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will
3941 * automatically make sure a unique keyPath value is present on each object
3942 * that is stored.
3943 * @param {Function} [kwArgs.onStoreReady] A callback to be called when the
3944 * store is ready to be used.
3945 * @param {Function} [kwArgs.onError=throw] A callback to be called when an
3946 * error occurred during instantiation of the store.
3947 * @param {Array} [kwArgs.indexes=[]] An array of indexData objects
3948 * defining the indexes to use with the store. For every index to be used
3949 * one indexData object needs to be passed in the array.
3950 * An indexData object is defined as follows:
3951 * @param {Object} [kwArgs.indexes.indexData] An object defining the index to
3952 * use
3953 * @param {String} kwArgs.indexes.indexData.name The name of the index
3954 * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index
3955 * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique
3956 * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry
3957 * @param {Function} [onStoreReady] A callback to be called when the store
3958 * is ready to be used.
3959 * @example
3960 // create a store for customers with an additional index over the
3961 // `lastname` property.
3962 var myCustomerStore = new IDBStore({
3963 dbVersion: 1,
3964 storeName: 'customer-index',
3965 keyPath: 'customerid',
3966 autoIncrement: true,
3967 onStoreReady: populateTable,
3968 indexes: [
3969 { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false }
3970 ]
3971 });
3972 * @example
3973 // create a generic store
3974 var myCustomerStore = new IDBStore({
3975 storeName: 'my-data-store',
3976 onStoreReady: function(){
3977 // start working with the store.
3978 }
3979 });
3980 */
3981 var IDBStore = function (kwArgs, onStoreReady) {
3982
3983 if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') {
3984 onStoreReady = kwArgs;
3985 }
3986 if (Object.prototype.toString.call(kwArgs) != '[object Object]') {
3987 kwArgs = {};
3988 }
3989
3990 for (var key in defaults) {
3991 this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key];
3992 }
3993
3994 this.dbName = this.storePrefix + this.storeName;
3995 this.dbVersion = parseInt(this.dbVersion, 10) || 1;
3996
3997 onStoreReady && (this.onStoreReady = onStoreReady);
3998
3999 var env = typeof window == 'object' ? window : self;
4000 this.idb = env.shimIndexedDB || env.indexedDB || env.webkitIndexedDB || env.mozIndexedDB;
4001 this.keyRange = env.IDBKeyRange || env.webkitIDBKeyRange || env.mozIDBKeyRange;
4002
4003 this.consts = {
4004 'READ_ONLY': 'readonly',
4005 'READ_WRITE': 'readwrite',
4006 'VERSION_CHANGE': 'versionchange',
4007 'NEXT': 'next',
4008 'NEXT_NO_DUPLICATE': 'nextunique',
4009 'PREV': 'prev',
4010 'PREV_NO_DUPLICATE': 'prevunique'
4011 };
4012
4013 this.openDB();
4014 };
4015
4016 IDBStore.prototype = /** @lends IDBStore */ {
4017
4018 /**
4019 * A pointer to the IDBStore ctor
4020 *
4021 * @type IDBStore
4022 */
4023 constructor: IDBStore,
4024
4025 /**
4026 * The version of IDBStore
4027 *
4028 * @type String
4029 */
4030 version: '1.6.0',
4031
4032 /**
4033 * A reference to the IndexedDB object
4034 *
4035 * @type Object
4036 */
4037 db: null,
4038
4039 /**
4040 * The full name of the IndexedDB used by IDBStore, composed of
4041 * this.storePrefix + this.storeName
4042 *
4043 * @type String
4044 */
4045 dbName: null,
4046
4047 /**
4048 * The version of the IndexedDB used by IDBStore
4049 *
4050 * @type Number
4051 */
4052 dbVersion: null,
4053
4054 /**
4055 * A reference to the objectStore used by IDBStore
4056 *
4057 * @type Object
4058 */
4059 store: null,
4060
4061 /**
4062 * The store name
4063 *
4064 * @type String
4065 */
4066 storeName: null,
4067
4068 /**
4069 * The prefix to prepend to the store name
4070 *
4071 * @type String
4072 */
4073 storePrefix: null,
4074
4075 /**
4076 * The key path
4077 *
4078 * @type String
4079 */
4080 keyPath: null,
4081
4082 /**
4083 * Whether IDBStore uses autoIncrement
4084 *
4085 * @type Boolean
4086 */
4087 autoIncrement: null,
4088
4089 /**
4090 * The indexes used by IDBStore
4091 *
4092 * @type Array
4093 */
4094 indexes: null,
4095
4096 /**
4097 * The callback to be called when the store is ready to be used
4098 *
4099 * @type Function
4100 */
4101 onStoreReady: null,
4102
4103 /**
4104 * The callback to be called if an error occurred during instantiation
4105 * of the store
4106 *
4107 * @type Function
4108 */
4109 onError: null,
4110
4111 /**
4112 * The internal insertID counter
4113 *
4114 * @type Number
4115 * @private
4116 */
4117 _insertIdCount: 0,
4118
4119 /**
4120 * Opens an IndexedDB; called by the constructor.
4121 *
4122 * Will check if versions match and compare provided index configuration
4123 * with existing ones, and update indexes if necessary.
4124 *
4125 * Will call this.onStoreReady() if everything went well and the store
4126 * is ready to use, and this.onError() is something went wrong.
4127 *
4128 * @private
4129 *
4130 */
4131 openDB: function () {
4132
4133 var openRequest = this.idb.open(this.dbName, this.dbVersion);
4134 var preventSuccessCallback = false;
4135
4136 openRequest.onerror = function (error) {
4137
4138 var gotVersionErr = false;
4139 if ('error' in error.target) {
4140 gotVersionErr = error.target.error.name == 'VersionError';
4141 } else if ('errorCode' in error.target) {
4142 gotVersionErr = error.target.errorCode == 12;
4143 }
4144
4145 if (gotVersionErr) {
4146 this.onError(new Error('The version number provided is lower than the existing one.'));
4147 } else {
4148 this.onError(error);
4149 }
4150 }.bind(this);
4151
4152 openRequest.onsuccess = function (event) {
4153
4154 if (preventSuccessCallback) {
4155 return;
4156 }
4157
4158 if(this.db){
4159 this.onStoreReady();
4160 return;
4161 }
4162
4163 this.db = event.target.result;
4164
4165 if(typeof this.db.version == 'string'){
4166 this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.'));
4167 return;
4168 }
4169
4170 if(!this.db.objectStoreNames.contains(this.storeName)){
4171 // We should never ever get here.
4172 // Lets notify the user anyway.
4173 this.onError(new Error('Something is wrong with the IndexedDB implementation in this browser. Please upgrade your browser.'));
4174 return;
4175 }
4176
4177 var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
4178 this.store = emptyTransaction.objectStore(this.storeName);
4179
4180 // check indexes
4181 var existingIndexes = Array.prototype.slice.call(this.getIndexList());
4182 this.indexes.forEach(function(indexData){
4183 var indexName = indexData.name;
4184
4185 if(!indexName){
4186 preventSuccessCallback = true;
4187 this.onError(new Error('Cannot create index: No index name given.'));
4188 return;
4189 }
4190
4191 this.normalizeIndexData(indexData);
4192
4193 if(this.hasIndex(indexName)){
4194 // check if it complies
4195 var actualIndex = this.store.index(indexName);
4196 var complies = this.indexComplies(actualIndex, indexData);
4197 if(!complies){
4198 preventSuccessCallback = true;
4199 this.onError(new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
4200 }
4201
4202 existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
4203 } else {
4204 preventSuccessCallback = true;
4205 this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
4206 }
4207
4208 }, this);
4209
4210 if (existingIndexes.length) {
4211 preventSuccessCallback = true;
4212 this.onError(new Error('Cannot delete index(es) "' + existingIndexes.toString() + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
4213 }
4214
4215 preventSuccessCallback || this.onStoreReady();
4216 }.bind(this);
4217
4218 openRequest.onupgradeneeded = function(/* IDBVersionChangeEvent */ event){
4219
4220 this.db = event.target.result;
4221
4222 if(this.db.objectStoreNames.contains(this.storeName)){
4223 this.store = event.target.transaction.objectStore(this.storeName);
4224 } else {
4225 var optionalParameters = { autoIncrement: this.autoIncrement };
4226 if (this.keyPath !== null) {
4227 optionalParameters.keyPath = this.keyPath;
4228 }
4229 this.store = this.db.createObjectStore(this.storeName, optionalParameters);
4230 }
4231
4232 var existingIndexes = Array.prototype.slice.call(this.getIndexList());
4233 this.indexes.forEach(function(indexData){
4234 var indexName = indexData.name;
4235
4236 if(!indexName){
4237 preventSuccessCallback = true;
4238 this.onError(new Error('Cannot create index: No index name given.'));
4239 }
4240
4241 this.normalizeIndexData(indexData);
4242
4243 if(this.hasIndex(indexName)){
4244 // check if it complies
4245 var actualIndex = this.store.index(indexName);
4246 var complies = this.indexComplies(actualIndex, indexData);
4247 if(!complies){
4248 // index differs, need to delete and re-create
4249 this.store.deleteIndex(indexName);
4250 this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry });
4251 }
4252
4253 existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
4254 } else {
4255 this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry });
4256 }
4257
4258 }, this);
4259
4260 if (existingIndexes.length) {
4261 existingIndexes.forEach(function(_indexName){
4262 this.store.deleteIndex(_indexName);
4263 }, this);
4264 }
4265
4266 }.bind(this);
4267 },
4268
4269 /**
4270 * Deletes the database used for this store if the IDB implementations
4271 * provides that functionality.
4272 *
4273 * @param {Function} [onSuccess] A callback that is called if deletion
4274 * was successful.
4275 * @param {Function} [onError] A callback that is called if deletion
4276 * failed.
4277 */
4278 deleteDatabase: function (onSuccess, onError) {
4279 if (this.idb.deleteDatabase) {
4280 this.db.close();
4281 var deleteRequest = this.idb.deleteDatabase(this.dbName);
4282 deleteRequest.onsuccess = onSuccess;
4283 deleteRequest.onerror = onError;
4284 } else {
4285 onError(new Error('Browser does not support IndexedDB deleteDatabase!'));
4286 }
4287 },
4288
4289 /*********************
4290 * data manipulation *
4291 *********************/
4292
4293 /**
4294 * Puts an object into the store. If an entry with the given id exists,
4295 * it will be overwritten. This method has a different signature for inline
4296 * keys and out-of-line keys; please see the examples below.
4297 *
4298 * @param {*} [key] The key to store. This is only needed if IDBWrapper
4299 * is set to use out-of-line keys. For inline keys - the default scenario -
4300 * this can be omitted.
4301 * @param {Object} value The data object to store.
4302 * @param {Function} [onSuccess] A callback that is called if insertion
4303 * was successful.
4304 * @param {Function} [onError] A callback that is called if insertion
4305 * failed.
4306 * @returns {IDBTransaction} The transaction used for this operation.
4307 * @example
4308 // Storing an object, using inline keys (the default scenario):
4309 var myCustomer = {
4310 customerid: 2346223,
4311 lastname: 'Doe',
4312 firstname: 'John'
4313 };
4314 myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler);
4315 // Note that passing success- and error-handlers is optional.
4316 * @example
4317 // Storing an object, using out-of-line keys:
4318 var myCustomer = {
4319 lastname: 'Doe',
4320 firstname: 'John'
4321 };
4322 myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler);
4323 // Note that passing success- and error-handlers is optional.
4324 */
4325 put: function (key, value, onSuccess, onError) {
4326 if (this.keyPath !== null) {
4327 onError = onSuccess;
4328 onSuccess = value;
4329 value = key;
4330 }
4331 onError || (onError = defaultErrorHandler);
4332 onSuccess || (onSuccess = defaultSuccessHandler);
4333
4334 var hasSuccess = false,
4335 result = null,
4336 putRequest;
4337
4338 var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
4339 putTransaction.oncomplete = function () {
4340 var callback = hasSuccess ? onSuccess : onError;
4341 callback(result);
4342 };
4343 putTransaction.onabort = onError;
4344 putTransaction.onerror = onError;
4345
4346 if (this.keyPath !== null) { // in-line keys
4347 this._addIdPropertyIfNeeded(value);
4348 putRequest = putTransaction.objectStore(this.storeName).put(value);
4349 } else { // out-of-line keys
4350 putRequest = putTransaction.objectStore(this.storeName).put(value, key);
4351 }
4352 putRequest.onsuccess = function (event) {
4353 hasSuccess = true;
4354 result = event.target.result;
4355 };
4356 putRequest.onerror = onError;
4357
4358 return putTransaction;
4359 },
4360
4361 /**
4362 * Retrieves an object from the store. If no entry exists with the given id,
4363 * the success handler will be called with null as first and only argument.
4364 *
4365 * @param {*} key The id of the object to fetch.
4366 * @param {Function} [onSuccess] A callback that is called if fetching
4367 * was successful. Will receive the object as only argument.
4368 * @param {Function} [onError] A callback that will be called if an error
4369 * occurred during the operation.
4370 * @returns {IDBTransaction} The transaction used for this operation.
4371 */
4372 get: function (key, onSuccess, onError) {
4373 onError || (onError = defaultErrorHandler);
4374 onSuccess || (onSuccess = defaultSuccessHandler);
4375
4376 var hasSuccess = false,
4377 result = null;
4378
4379 var getTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
4380 getTransaction.oncomplete = function () {
4381 var callback = hasSuccess ? onSuccess : onError;
4382 callback(result);
4383 };
4384 getTransaction.onabort = onError;
4385 getTransaction.onerror = onError;
4386 var getRequest = getTransaction.objectStore(this.storeName).get(key);
4387 getRequest.onsuccess = function (event) {
4388 hasSuccess = true;
4389 result = event.target.result;
4390 };
4391 getRequest.onerror = onError;
4392
4393 return getTransaction;
4394 },
4395
4396 /**
4397 * Removes an object from the store.
4398 *
4399 * @param {*} key The id of the object to remove.
4400 * @param {Function} [onSuccess] A callback that is called if the removal
4401 * was successful.
4402 * @param {Function} [onError] A callback that will be called if an error
4403 * occurred during the operation.
4404 * @returns {IDBTransaction} The transaction used for this operation.
4405 */
4406 remove: function (key, onSuccess, onError) {
4407 onError || (onError = defaultErrorHandler);
4408 onSuccess || (onSuccess = defaultSuccessHandler);
4409
4410 var hasSuccess = false,
4411 result = null;
4412
4413 var removeTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
4414 removeTransaction.oncomplete = function () {
4415 var callback = hasSuccess ? onSuccess : onError;
4416 callback(result);
4417 };
4418 removeTransaction.onabort = onError;
4419 removeTransaction.onerror = onError;
4420
4421 var deleteRequest = removeTransaction.objectStore(this.storeName)['delete'](key);
4422 deleteRequest.onsuccess = function (event) {
4423 hasSuccess = true;
4424 result = event.target.result;
4425 };
4426 deleteRequest.onerror = onError;
4427
4428 return removeTransaction;
4429 },
4430
4431 /**
4432 * Runs a batch of put and/or remove operations on the store.
4433 *
4434 * @param {Array} dataArray An array of objects containing the operation to run
4435 * and the data object (for put operations).
4436 * @param {Function} [onSuccess] A callback that is called if all operations
4437 * were successful.
4438 * @param {Function} [onError] A callback that is called if an error
4439 * occurred during one of the operations.
4440 * @returns {IDBTransaction} The transaction used for this operation.
4441 */
4442 batch: function (dataArray, onSuccess, onError) {
4443 onError || (onError = defaultErrorHandler);
4444 onSuccess || (onSuccess = defaultSuccessHandler);
4445
4446 if(Object.prototype.toString.call(dataArray) != '[object Array]'){
4447 onError(new Error('dataArray argument must be of type Array.'));
4448 } else if (dataArray.length === 0) {
4449 return onSuccess(true);
4450 }
4451 var batchTransaction = this.db.transaction([this.storeName] , this.consts.READ_WRITE);
4452 batchTransaction.oncomplete = function () {
4453 var callback = hasSuccess ? onSuccess : onError;
4454 callback(hasSuccess);
4455 };
4456 batchTransaction.onabort = onError;
4457 batchTransaction.onerror = onError;
4458
4459 var count = dataArray.length;
4460 var called = false;
4461 var hasSuccess = false;
4462
4463 var onItemSuccess = function () {
4464 count--;
4465 if (count === 0 && !called) {
4466 called = true;
4467 hasSuccess = true;
4468 }
4469 };
4470
4471 dataArray.forEach(function (operation) {
4472 var type = operation.type;
4473 var key = operation.key;
4474 var value = operation.value;
4475
4476 var onItemError = function (err) {
4477 batchTransaction.abort();
4478 if (!called) {
4479 called = true;
4480 onError(err, type, key);
4481 }
4482 };
4483
4484 if (type == 'remove') {
4485 var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key);
4486 deleteRequest.onsuccess = onItemSuccess;
4487 deleteRequest.onerror = onItemError;
4488 } else if (type == 'put') {
4489 var putRequest;
4490 if (this.keyPath !== null) { // in-line keys
4491 this._addIdPropertyIfNeeded(value);
4492 putRequest = batchTransaction.objectStore(this.storeName).put(value);
4493 } else { // out-of-line keys
4494 putRequest = batchTransaction.objectStore(this.storeName).put(value, key);
4495 }
4496 putRequest.onsuccess = onItemSuccess;
4497 putRequest.onerror = onItemError;
4498 }
4499 }, this);
4500
4501 return batchTransaction;
4502 },
4503
4504 /**
4505 * Takes an array of objects and stores them in a single transaction.
4506 *
4507 * @param {Array} dataArray An array of objects to store
4508 * @param {Function} [onSuccess] A callback that is called if all operations
4509 * were successful.
4510 * @param {Function} [onError] A callback that is called if an error
4511 * occurred during one of the operations.
4512 * @returns {IDBTransaction} The transaction used for this operation.
4513 */
4514 putBatch: function (dataArray, onSuccess, onError) {
4515 var batchData = dataArray.map(function(item){
4516 return { type: 'put', value: item };
4517 });
4518
4519 return this.batch(batchData, onSuccess, onError);
4520 },
4521
4522 /**
4523 * Like putBatch, takes an array of objects and stores them in a single
4524 * transaction, but allows processing of the result values. Returns the
4525 * processed records containing the key for newly created records to the
4526 * onSuccess calllback instead of only returning true or false for success.
4527 * In addition, added the option for the caller to specify a key field that
4528 * should be set to the newly created key.
4529 *
4530 * @param {Array} dataArray An array of objects to store
4531 * @param {Object} [options] An object containing optional options
4532 * @param {String} [options.keyField=this.keyPath] Specifies a field in the record to update
4533 * with the auto-incrementing key. Defaults to the store's keyPath.
4534 * @param {Function} [onSuccess] A callback that is called if all operations
4535 * were successful.
4536 * @param {Function} [onError] A callback that is called if an error
4537 * occurred during one of the operations.
4538 * @returns {IDBTransaction} The transaction used for this operation.
4539 *
4540 */
4541 upsertBatch: function (dataArray, options, onSuccess, onError) {
4542 // handle `dataArray, onSuccess, onError` signature
4543 if (typeof options == 'function') {
4544 onSuccess = options;
4545 onError = onSuccess;
4546 options = {};
4547 }
4548
4549 onError || (onError = defaultErrorHandler);
4550 onSuccess || (onSuccess = defaultSuccessHandler);
4551 options || (options = {});
4552
4553 if (Object.prototype.toString.call(dataArray) != '[object Array]') {
4554 onError(new Error('dataArray argument must be of type Array.'));
4555 }
4556 var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
4557 batchTransaction.oncomplete = function () {
4558 if (hasSuccess) {
4559 onSuccess(dataArray);
4560 } else {
4561 onError(false);
4562 }
4563 };
4564 batchTransaction.onabort = onError;
4565 batchTransaction.onerror = onError;
4566
4567 var keyField = options.keyField || this.keyPath;
4568 var count = dataArray.length;
4569 var called = false;
4570 var hasSuccess = false;
4571 var index = 0; // assume success callbacks are executed in order
4572
4573 var onItemSuccess = function (event) {
4574 var record = dataArray[index++];
4575 record[keyField] = event.target.result;
4576
4577 count--;
4578 if (count === 0 && !called) {
4579 called = true;
4580 hasSuccess = true;
4581 }
4582 };
4583
4584 dataArray.forEach(function (record) {
4585 var key = record.key;
4586
4587 var onItemError = function (err) {
4588 batchTransaction.abort();
4589 if (!called) {
4590 called = true;
4591 onError(err);
4592 }
4593 };
4594
4595 var putRequest;
4596 if (this.keyPath !== null) { // in-line keys
4597 this._addIdPropertyIfNeeded(record);
4598 putRequest = batchTransaction.objectStore(this.storeName).put(record);
4599 } else { // out-of-line keys
4600 putRequest = batchTransaction.objectStore(this.storeName).put(record, key);
4601 }
4602 putRequest.onsuccess = onItemSuccess;
4603 putRequest.onerror = onItemError;
4604 }, this);
4605
4606 return batchTransaction;
4607 },
4608
4609 /**
4610 * Takes an array of keys and removes matching objects in a single
4611 * transaction.
4612 *
4613 * @param {Array} keyArray An array of keys to remove
4614 * @param {Function} [onSuccess] A callback that is called if all operations
4615 * were successful.
4616 * @param {Function} [onError] A callback that is called if an error
4617 * occurred during one of the operations.
4618 * @returns {IDBTransaction} The transaction used for this operation.
4619 */
4620 removeBatch: function (keyArray, onSuccess, onError) {
4621 var batchData = keyArray.map(function(key){
4622 return { type: 'remove', key: key };
4623 });
4624
4625 return this.batch(batchData, onSuccess, onError);
4626 },
4627
4628 /**
4629 * Takes an array of keys and fetches matching objects
4630 *
4631 * @param {Array} keyArray An array of keys identifying the objects to fetch
4632 * @param {Function} [onSuccess] A callback that is called if all operations
4633 * were successful.
4634 * @param {Function} [onError] A callback that is called if an error
4635 * occurred during one of the operations.
4636 * @param {String} [arrayType='sparse'] The type of array to pass to the
4637 * success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to
4638 * 'sparse'. This parameter specifies how to handle the situation if a get
4639 * operation did not throw an error, but there was no matching object in
4640 * the database. In most cases, 'sparse' provides the most desired
4641 * behavior. See the examples for details.
4642 * @returns {IDBTransaction} The transaction used for this operation.
4643 * @example
4644 // given that there are two objects in the database with the keypath
4645 // values 1 and 2, and the call looks like this:
4646 myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType);
4647
4648 // this is what the `data` array will be like:
4649
4650 // arrayType == 'sparse':
4651 // data is a sparse array containing two entries and having a length of 3:
4652 [Object, 2: Object]
4653 0: Object
4654 2: Object
4655 length: 3
4656 __proto__: Array[0]
4657 // calling forEach on data will result in the callback being called two
4658 // times, with the index parameter matching the index of the key in the
4659 // keyArray.
4660
4661 // arrayType == 'dense':
4662 // data is a dense array containing three entries and having a length of 3,
4663 // where data[1] is of type undefined:
4664 [Object, undefined, Object]
4665 0: Object
4666 1: undefined
4667 2: Object
4668 length: 3
4669 __proto__: Array[0]
4670 // calling forEach on data will result in the callback being called three
4671 // times, with the index parameter matching the index of the key in the
4672 // keyArray, but the second call will have undefined as first argument.
4673
4674 // arrayType == 'skip':
4675 // data is a dense array containing two entries and having a length of 2:
4676 [Object, Object]
4677 0: Object
4678 1: Object
4679 length: 2
4680 __proto__: Array[0]
4681 // calling forEach on data will result in the callback being called two
4682 // times, with the index parameter not matching the index of the key in the
4683 // keyArray.
4684 */
4685 getBatch: function (keyArray, onSuccess, onError, arrayType) {
4686 onError || (onError = defaultErrorHandler);
4687 onSuccess || (onSuccess = defaultSuccessHandler);
4688 arrayType || (arrayType = 'sparse');
4689
4690 if (Object.prototype.toString.call(keyArray) != '[object Array]'){
4691 onError(new Error('keyArray argument must be of type Array.'));
4692 } else if (keyArray.length === 0) {
4693 return onSuccess([]);
4694 }
4695 var batchTransaction = this.db.transaction([this.storeName] , this.consts.READ_ONLY);
4696 batchTransaction.oncomplete = function () {
4697 var callback = hasSuccess ? onSuccess : onError;
4698 callback(result);
4699 };
4700 batchTransaction.onabort = onError;
4701 batchTransaction.onerror = onError;
4702
4703 var data = [];
4704 var count = keyArray.length;
4705 var called = false;
4706 var hasSuccess = false;
4707 var result = null;
4708
4709 var onItemSuccess = function (event) {
4710 if (event.target.result || arrayType == 'dense') {
4711 data.push(event.target.result);
4712 } else if (arrayType == 'sparse') {
4713 data.length++;
4714 }
4715 count--;
4716 if (count === 0) {
4717 called = true;
4718 hasSuccess = true;
4719 result = data;
4720 }
4721 };
4722
4723 keyArray.forEach(function (key) {
4724
4725 var onItemError = function (err) {
4726 called = true;
4727 result = err;
4728 onError(err);
4729 batchTransaction.abort();
4730 };
4731
4732 var getRequest = batchTransaction.objectStore(this.storeName).get(key);
4733 getRequest.onsuccess = onItemSuccess;
4734 getRequest.onerror = onItemError;
4735
4736 }, this);
4737
4738 return batchTransaction;
4739 },
4740
4741 /**
4742 * Fetches all entries in the store.
4743 *
4744 * @param {Function} [onSuccess] A callback that is called if the operation
4745 * was successful. Will receive an array of objects.
4746 * @param {Function} [onError] A callback that will be called if an error
4747 * occurred during the operation.
4748 * @returns {IDBTransaction} The transaction used for this operation.
4749 */
4750 getAll: function (onSuccess, onError) {
4751 onError || (onError = defaultErrorHandler);
4752 onSuccess || (onSuccess = defaultSuccessHandler);
4753 var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
4754 var store = getAllTransaction.objectStore(this.storeName);
4755 if (store.getAll) {
4756 this._getAllNative(getAllTransaction, store, onSuccess, onError);
4757 } else {
4758 this._getAllCursor(getAllTransaction, store, onSuccess, onError);
4759 }
4760
4761 return getAllTransaction;
4762 },
4763
4764 /**
4765 * Implements getAll for IDB implementations that have a non-standard
4766 * getAll() method.
4767 *
4768 * @param {Object} getAllTransaction An open READ transaction.
4769 * @param {Object} store A reference to the store.
4770 * @param {Function} onSuccess A callback that will be called if the
4771 * operation was successful.
4772 * @param {Function} onError A callback that will be called if an
4773 * error occurred during the operation.
4774 * @private
4775 */
4776 _getAllNative: function (getAllTransaction, store, onSuccess, onError) {
4777 var hasSuccess = false,
4778 result = null;
4779
4780 getAllTransaction.oncomplete = function () {
4781 var callback = hasSuccess ? onSuccess : onError;
4782 callback(result);
4783 };
4784 getAllTransaction.onabort = onError;
4785 getAllTransaction.onerror = onError;
4786
4787 var getAllRequest = store.getAll();
4788 getAllRequest.onsuccess = function (event) {
4789 hasSuccess = true;
4790 result = event.target.result;
4791 };
4792 getAllRequest.onerror = onError;
4793 },
4794
4795 /**
4796 * Implements getAll for IDB implementations that do not have a getAll()
4797 * method.
4798 *
4799 * @param {Object} getAllTransaction An open READ transaction.
4800 * @param {Object} store A reference to the store.
4801 * @param {Function} onSuccess A callback that will be called if the
4802 * operation was successful.
4803 * @param {Function} onError A callback that will be called if an
4804 * error occurred during the operation.
4805 * @private
4806 */
4807 _getAllCursor: function (getAllTransaction, store, onSuccess, onError) {
4808 var all = [],
4809 hasSuccess = false,
4810 result = null;
4811
4812 getAllTransaction.oncomplete = function () {
4813 var callback = hasSuccess ? onSuccess : onError;
4814 callback(result);
4815 };
4816 getAllTransaction.onabort = onError;
4817 getAllTransaction.onerror = onError;
4818
4819 var cursorRequest = store.openCursor();
4820 cursorRequest.onsuccess = function (event) {
4821 var cursor = event.target.result;
4822 if (cursor) {
4823 all.push(cursor.value);
4824 cursor['continue']();
4825 }
4826 else {
4827 hasSuccess = true;
4828 result = all;
4829 }
4830 };
4831 cursorRequest.onError = onError;
4832 },
4833
4834 /**
4835 * Clears the store, i.e. deletes all entries in the store.
4836 *
4837 * @param {Function} [onSuccess] A callback that will be called if the
4838 * operation was successful.
4839 * @param {Function} [onError] A callback that will be called if an
4840 * error occurred during the operation.
4841 * @returns {IDBTransaction} The transaction used for this operation.
4842 */
4843 clear: function (onSuccess, onError) {
4844 onError || (onError = defaultErrorHandler);
4845 onSuccess || (onSuccess = defaultSuccessHandler);
4846
4847 var hasSuccess = false,
4848 result = null;
4849
4850 var clearTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
4851 clearTransaction.oncomplete = function () {
4852 var callback = hasSuccess ? onSuccess : onError;
4853 callback(result);
4854 };
4855 clearTransaction.onabort = onError;
4856 clearTransaction.onerror = onError;
4857
4858 var clearRequest = clearTransaction.objectStore(this.storeName).clear();
4859 clearRequest.onsuccess = function (event) {
4860 hasSuccess = true;
4861 result = event.target.result;
4862 };
4863 clearRequest.onerror = onError;
4864
4865 return clearTransaction;
4866 },
4867
4868 /**
4869 * Checks if an id property needs to present on a object and adds one if
4870 * necessary.
4871 *
4872 * @param {Object} dataObj The data object that is about to be stored
4873 * @private
4874 */
4875 _addIdPropertyIfNeeded: function (dataObj) {
4876 if (typeof dataObj[this.keyPath] == 'undefined') {
4877 dataObj[this.keyPath] = this._insertIdCount++ + Date.now();
4878 }
4879 },
4880
4881 /************
4882 * indexing *
4883 ************/
4884
4885 /**
4886 * Returns a DOMStringList of index names of the store.
4887 *
4888 * @return {DOMStringList} The list of index names
4889 */
4890 getIndexList: function () {
4891 return this.store.indexNames;
4892 },
4893
4894 /**
4895 * Checks if an index with the given name exists in the store.
4896 *
4897 * @param {String} indexName The name of the index to look for
4898 * @return {Boolean} Whether the store contains an index with the given name
4899 */
4900 hasIndex: function (indexName) {
4901 return this.store.indexNames.contains(indexName);
4902 },
4903
4904 /**
4905 * Normalizes an object containing index data and assures that all
4906 * properties are set.
4907 *
4908 * @param {Object} indexData The index data object to normalize
4909 * @param {String} indexData.name The name of the index
4910 * @param {String} [indexData.keyPath] The key path of the index
4911 * @param {Boolean} [indexData.unique] Whether the index is unique
4912 * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry
4913 */
4914 normalizeIndexData: function (indexData) {
4915 indexData.keyPath = indexData.keyPath || indexData.name;
4916 indexData.unique = !!indexData.unique;
4917 indexData.multiEntry = !!indexData.multiEntry;
4918 },
4919
4920 /**
4921 * Checks if an actual index complies with an expected index.
4922 *
4923 * @param {Object} actual The actual index found in the store
4924 * @param {Object} expected An Object describing an expected index
4925 * @return {Boolean} Whether both index definitions are identical
4926 */
4927 indexComplies: function (actual, expected) {
4928 var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) {
4929 // IE10 returns undefined for no multiEntry
4930 if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) {
4931 return true;
4932 }
4933 // Compound keys
4934 if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') {
4935 var exp = expected.keyPath;
4936 var act = actual.keyPath;
4937
4938 // IE10 can't handle keyPath sequences and stores them as a string.
4939 // The index will be unusable there, but let's still return true if
4940 // the keyPath sequence matches.
4941 if (typeof act == 'string') {
4942 return exp.toString() == act;
4943 }
4944
4945 // Chrome/Opera stores keyPath squences as DOMStringList, Firefox
4946 // as Array
4947 if ( ! (typeof act.contains == 'function' || typeof act.indexOf == 'function') ) {
4948 return false;
4949 }
4950
4951 if (act.length !== exp.length) {
4952 return false;
4953 }
4954
4955 for (var i = 0, m = exp.length; i<m; i++) {
4956 if ( ! ( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) {
4957 return false;
4958 }
4959 }
4960 return true;
4961 }
4962 return expected[key] == actual[key];
4963 });
4964 return complies;
4965 },
4966
4967 /**********
4968 * cursor *
4969 **********/
4970
4971 /**
4972 * Iterates over the store using the given options and calling onItem
4973 * for each entry matching the options.
4974 *
4975 * @param {Function} onItem A callback to be called for each match
4976 * @param {Object} [options] An object defining specific options
4977 * @param {Object} [options.index=null] An IDBIndex to operate on
4978 * @param {String} [options.order=ASC] The order in which to provide the
4979 * results, can be 'DESC' or 'ASC'
4980 * @param {Boolean} [options.autoContinue=true] Whether to automatically
4981 * iterate the cursor to the next result
4982 * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
4983 * duplicate matches
4984 * @param {Object} [options.keyRange=null] An IDBKeyRange to use
4985 * @param {Boolean} [options.writeAccess=false] Whether grant write access
4986 * to the store in the onItem callback
4987 * @param {Function} [options.onEnd=null] A callback to be called after
4988 * iteration has ended
4989 * @param {Function} [options.onError=throw] A callback to be called
4990 * if an error occurred during the operation.
4991 * @param {Number} [options.limit=Infinity] Limit the number of returned
4992 * results to this number
4993 * @param {Number} [options.offset=0] Skip the provided number of results
4994 * in the resultset
4995 * @returns {IDBTransaction} The transaction used for this operation.
4996 */
4997 iterate: function (onItem, options) {
4998 options = mixin({
4999 index: null,
5000 order: 'ASC',
5001 autoContinue: true,
5002 filterDuplicates: false,
5003 keyRange: null,
5004 writeAccess: false,
5005 onEnd: null,
5006 onError: defaultErrorHandler,
5007 limit: Infinity,
5008 offset: 0
5009 }, options || {});
5010
5011 var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT';
5012 if (options.filterDuplicates) {
5013 directionType += '_NO_DUPLICATE';
5014 }
5015
5016 var hasSuccess = false;
5017 var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']);
5018 var cursorTarget = cursorTransaction.objectStore(this.storeName);
5019 if (options.index) {
5020 cursorTarget = cursorTarget.index(options.index);
5021 }
5022 var recordCount = 0;
5023
5024 cursorTransaction.oncomplete = function () {
5025 if (!hasSuccess) {
5026 options.onError(null);
5027 return;
5028 }
5029 if (options.onEnd) {
5030 options.onEnd();
5031 } else {
5032 onItem(null);
5033 }
5034 };
5035 cursorTransaction.onabort = options.onError;
5036 cursorTransaction.onerror = options.onError;
5037
5038 var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]);
5039 cursorRequest.onerror = options.onError;
5040 cursorRequest.onsuccess = function (event) {
5041 var cursor = event.target.result;
5042 if (cursor) {
5043 if (options.offset) {
5044 cursor.advance(options.offset);
5045 options.offset = 0;
5046 } else {
5047 onItem(cursor.value, cursor, cursorTransaction);
5048 recordCount++;
5049 if (options.autoContinue) {
5050 if (recordCount + options.offset < options.limit) {
5051 cursor['continue']();
5052 } else {
5053 hasSuccess = true;
5054 }
5055 }
5056 }
5057 } else {
5058 hasSuccess = true;
5059 }
5060 };
5061
5062 return cursorTransaction;
5063 },
5064
5065 /**
5066 * Runs a query against the store and passes an array containing matched
5067 * objects to the success handler.
5068 *
5069 * @param {Function} onSuccess A callback to be called when the operation
5070 * was successful.
5071 * @param {Object} [options] An object defining specific options
5072 * @param {Object} [options.index=null] An IDBIndex to operate on
5073 * @param {String} [options.order=ASC] The order in which to provide the
5074 * results, can be 'DESC' or 'ASC'
5075 * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
5076 * duplicate matches
5077 * @param {Object} [options.keyRange=null] An IDBKeyRange to use
5078 * @param {Function} [options.onError=throw] A callback to be called
5079 * if an error occurred during the operation.
5080 * @param {Number} [options.limit=Infinity] Limit the number of returned
5081 * results to this number
5082 * @param {Number} [options.offset=0] Skip the provided number of results
5083 * in the resultset
5084 * @returns {IDBTransaction} The transaction used for this operation.
5085 */
5086 query: function (onSuccess, options) {
5087 var result = [];
5088 options = options || {};
5089 options.autoContinue = true;
5090 options.writeAccess = false;
5091 options.onEnd = function () {
5092 onSuccess(result);
5093 };
5094 return this.iterate(function (item) {
5095 result.push(item);
5096 }, options);
5097 },
5098
5099 /**
5100 *
5101 * Runs a query against the store, but only returns the number of matches
5102 * instead of the matches itself.
5103 *
5104 * @param {Function} onSuccess A callback to be called if the opration
5105 * was successful.
5106 * @param {Object} [options] An object defining specific options
5107 * @param {Object} [options.index=null] An IDBIndex to operate on
5108 * @param {Object} [options.keyRange=null] An IDBKeyRange to use
5109 * @param {Function} [options.onError=throw] A callback to be called if an error
5110 * occurred during the operation.
5111 * @returns {IDBTransaction} The transaction used for this operation.
5112 */
5113 count: function (onSuccess, options) {
5114
5115 options = mixin({
5116 index: null,
5117 keyRange: null
5118 }, options || {});
5119
5120 var onError = options.onError || defaultErrorHandler;
5121
5122 var hasSuccess = false,
5123 result = null;
5124
5125 var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
5126 cursorTransaction.oncomplete = function () {
5127 var callback = hasSuccess ? onSuccess : onError;
5128 callback(result);
5129 };
5130 cursorTransaction.onabort = onError;
5131 cursorTransaction.onerror = onError;
5132
5133 var cursorTarget = cursorTransaction.objectStore(this.storeName);
5134 if (options.index) {
5135 cursorTarget = cursorTarget.index(options.index);
5136 }
5137 var countRequest = cursorTarget.count(options.keyRange);
5138 countRequest.onsuccess = function (evt) {
5139 hasSuccess = true;
5140 result = evt.target.result;
5141 };
5142 countRequest.onError = onError;
5143
5144 return cursorTransaction;
5145 },
5146
5147 /**************/
5148 /* key ranges */
5149 /**************/
5150
5151 /**
5152 * Creates a key range using specified options. This key range can be
5153 * handed over to the count() and iterate() methods.
5154 *
5155 * Note: You must provide at least one or both of "lower" or "upper" value.
5156 *
5157 * @param {Object} options The options for the key range to create
5158 * @param {*} [options.lower] The lower bound
5159 * @param {Boolean} [options.excludeLower] Whether to exclude the lower
5160 * bound passed in options.lower from the key range
5161 * @param {*} [options.upper] The upper bound
5162 * @param {Boolean} [options.excludeUpper] Whether to exclude the upper
5163 * bound passed in options.upper from the key range
5164 * @param {*} [options.only] A single key value. Use this if you need a key
5165 * range that only includes one value for a key. Providing this
5166 * property invalidates all other properties.
5167 * @return {Object} The IDBKeyRange representing the specified options
5168 */
5169 makeKeyRange: function(options){
5170 /*jshint onecase:true */
5171 var keyRange,
5172 hasLower = typeof options.lower != 'undefined',
5173 hasUpper = typeof options.upper != 'undefined',
5174 isOnly = typeof options.only != 'undefined';
5175
5176 switch(true){
5177 case isOnly:
5178 keyRange = this.keyRange.only(options.only);
5179 break;
5180 case hasLower && hasUpper:
5181 keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper);
5182 break;
5183 case hasLower:
5184 keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower);
5185 break;
5186 case hasUpper:
5187 keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper);
5188 break;
5189 default:
5190 throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.');
5191 }
5192
5193 return keyRange;
5194
5195 }
5196
5197 };
5198
5199 /** helpers **/
5200 var empty = {};
5201 var mixin = function (target, source) {
5202 var name, s;
5203 for (name in source) {
5204 s = source[name];
5205 if (s !== empty[name] && s !== target[name]) {
5206 target[name] = s;
5207 }
5208 }
5209 return target;
5210 };
5211
5212 IDBStore.version = IDBStore.prototype.version;
5213
5214 return IDBStore;
5215
5216}, this);
5217}, {}],19: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
5218
5219var xtend = require('xtend')
5220 , AbstractIterator = require('./abstract-iterator')
5221 , AbstractChainedBatch = require('./abstract-chained-batch')
5222
5223function AbstractLevelDOWN (location) {
5224 if (!arguments.length || location === undefined)
5225 throw new Error('constructor requires at least a location argument')
5226
5227 if (typeof location != 'string')
5228 throw new Error('constructor requires a location string argument')
5229
5230 this.location = location
5231}
5232
5233AbstractLevelDOWN.prototype.open = function (options, callback) {
5234 if (typeof options == 'function')
5235 callback = options
5236
5237 if (typeof callback != 'function')
5238 throw new Error('open() requires a callback argument')
5239
5240 if (typeof options != 'object')
5241 options = {}
5242
5243 if (typeof this._open == 'function')
5244 return this._open(options, callback)
5245
5246 process.nextTick(callback)
5247}
5248
5249AbstractLevelDOWN.prototype.close = function (callback) {
5250 if (typeof callback != 'function')
5251 throw new Error('close() requires a callback argument')
5252
5253 if (typeof this._close == 'function')
5254 return this._close(callback)
5255
5256 process.nextTick(callback)
5257}
5258
5259AbstractLevelDOWN.prototype.get = function (key, options, callback) {
5260 var err
5261
5262 if (typeof options == 'function')
5263 callback = options
5264
5265 if (typeof callback != 'function')
5266 throw new Error('get() requires a callback argument')
5267
5268 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
5269 return callback(err)
5270
5271 if (!this._isBuffer(key))
5272 key = String(key)
5273
5274 if (typeof options != 'object')
5275 options = {}
5276
5277 if (typeof this._get == 'function')
5278 return this._get(key, options, callback)
5279
5280 process.nextTick(function () { callback(new Error('NotFound')) })
5281}
5282
5283AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
5284 var err
5285
5286 if (typeof options == 'function')
5287 callback = options
5288
5289 if (typeof callback != 'function')
5290 throw new Error('put() requires a callback argument')
5291
5292 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
5293 return callback(err)
5294
5295 if (err = this._checkKeyValue(value, 'value', this._isBuffer))
5296 return callback(err)
5297
5298 if (!this._isBuffer(key))
5299 key = String(key)
5300
5301 // coerce value to string in node, don't touch it in browser
5302 // (indexeddb can store any JS type)
5303 if (!this._isBuffer(value) && !process.browser)
5304 value = String(value)
5305
5306 if (typeof options != 'object')
5307 options = {}
5308
5309 if (typeof this._put == 'function')
5310 return this._put(key, value, options, callback)
5311
5312 process.nextTick(callback)
5313}
5314
5315AbstractLevelDOWN.prototype.del = function (key, options, callback) {
5316 var err
5317
5318 if (typeof options == 'function')
5319 callback = options
5320
5321 if (typeof callback != 'function')
5322 throw new Error('del() requires a callback argument')
5323
5324 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
5325 return callback(err)
5326
5327 if (!this._isBuffer(key))
5328 key = String(key)
5329
5330 if (typeof options != 'object')
5331 options = {}
5332
5333 if (typeof this._del == 'function')
5334 return this._del(key, options, callback)
5335
5336 process.nextTick(callback)
5337}
5338
5339AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
5340 if (!arguments.length)
5341 return this._chainedBatch()
5342
5343 if (typeof options == 'function')
5344 callback = options
5345
5346 if (typeof callback != 'function')
5347 throw new Error('batch(array) requires a callback argument')
5348
5349 if (!Array.isArray(array))
5350 return callback(new Error('batch(array) requires an array argument'))
5351
5352 if (typeof options != 'object')
5353 options = {}
5354
5355 var i = 0
5356 , l = array.length
5357 , e
5358 , err
5359
5360 for (; i < l; i++) {
5361 e = array[i]
5362 if (typeof e != 'object')
5363 continue
5364
5365 if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
5366 return callback(err)
5367
5368 if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
5369 return callback(err)
5370
5371 if (e.type == 'put') {
5372 if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
5373 return callback(err)
5374 }
5375 }
5376
5377 if (typeof this._batch == 'function')
5378 return this._batch(array, options, callback)
5379
5380 process.nextTick(callback)
5381}
5382
5383//TODO: remove from here, not a necessary primitive
5384AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
5385 if ( start == null
5386 || end == null
5387 || typeof start == 'function'
5388 || typeof end == 'function') {
5389 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
5390 }
5391
5392 if (typeof callback != 'function')
5393 throw new Error('approximateSize() requires a callback argument')
5394
5395 if (!this._isBuffer(start))
5396 start = String(start)
5397
5398 if (!this._isBuffer(end))
5399 end = String(end)
5400
5401 if (typeof this._approximateSize == 'function')
5402 return this._approximateSize(start, end, callback)
5403
5404 process.nextTick(function () {
5405 callback(null, 0)
5406 })
5407}
5408
5409AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
5410 var self = this
5411
5412 options = xtend(options)
5413
5414 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
5415 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
5416 delete options[o]
5417 })
5418
5419 options.reverse = !!options.reverse
5420
5421 // fix `start` so it takes into account gt, gte, lt, lte as appropriate
5422 if (options.reverse && options.lt)
5423 options.start = options.lt
5424 if (options.reverse && options.lte)
5425 options.start = options.lte
5426 if (!options.reverse && options.gt)
5427 options.start = options.gt
5428 if (!options.reverse && options.gte)
5429 options.start = options.gte
5430
5431 if ((options.reverse && options.lt && !options.lte)
5432 || (!options.reverse && options.gt && !options.gte))
5433 options.exclusiveStart = true // start should *not* include matching key
5434
5435 return options
5436}
5437
5438AbstractLevelDOWN.prototype.iterator = function (options) {
5439 if (typeof options != 'object')
5440 options = {}
5441
5442 options = this._setupIteratorOptions(options)
5443
5444 if (typeof this._iterator == 'function')
5445 return this._iterator(options)
5446
5447 return new AbstractIterator(this)
5448}
5449
5450AbstractLevelDOWN.prototype._chainedBatch = function () {
5451 return new AbstractChainedBatch(this)
5452}
5453
5454AbstractLevelDOWN.prototype._isBuffer = function (obj) {
5455 return Buffer.isBuffer(obj)
5456}
5457
5458AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {
5459
5460 if (obj === null || obj === undefined)
5461 return new Error(type + ' cannot be `null` or `undefined`')
5462
5463 if (this._isBuffer(obj)) {
5464 if (obj.length === 0)
5465 return new Error(type + ' cannot be an empty Buffer')
5466 } else if (String(obj) === '')
5467 return new Error(type + ' cannot be an empty String')
5468}
5469
5470module.exports.AbstractLevelDOWN = AbstractLevelDOWN
5471module.exports.AbstractIterator = AbstractIterator
5472module.exports.AbstractChainedBatch = AbstractChainedBatch
5473}, {"xtend":20,"./abstract-iterator":21,"./abstract-chained-batch":22}],20: [function (exports, require, module, global) {module.exports = extend
5474
5475function extend() {
5476 var target = {}
5477
5478 for (var i = 0; i < arguments.length; i++) {
5479 var source = arguments[i]
5480
5481 for (var key in source) {
5482 if (source.hasOwnProperty(key)) {
5483 target[key] = source[key]
5484 }
5485 }
5486 }
5487
5488 return target
5489}
5490}, {}],21: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
5491
5492function AbstractIterator (db) {
5493 this.db = db
5494 this._ended = false
5495 this._nexting = false
5496}
5497
5498AbstractIterator.prototype.next = function (callback) {
5499 var self = this
5500
5501 if (typeof callback != 'function')
5502 throw new Error('next() requires a callback argument')
5503
5504 if (self._ended)
5505 return callback(new Error('cannot call next() after end()'))
5506 if (self._nexting)
5507 return callback(new Error('cannot call next() before previous next() has completed'))
5508
5509 self._nexting = true
5510 if (typeof self._next == 'function') {
5511 return self._next(function () {
5512 self._nexting = false
5513 callback.apply(null, arguments)
5514 })
5515 }
5516
5517 process.nextTick(function () {
5518 self._nexting = false
5519 callback()
5520 })
5521}
5522
5523AbstractIterator.prototype.end = function (callback) {
5524 if (typeof callback != 'function')
5525 throw new Error('end() requires a callback argument')
5526
5527 if (this._ended)
5528 return callback(new Error('end() already called on iterator'))
5529
5530 this._ended = true
5531
5532 if (typeof this._end == 'function')
5533 return this._end(callback)
5534
5535 process.nextTick(callback)
5536}
5537
5538module.exports = AbstractIterator
5539}, {}],22: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
5540
5541function AbstractChainedBatch (db) {
5542 this._db = db
5543 this._operations = []
5544 this._written = false
5545}
5546
5547AbstractChainedBatch.prototype._checkWritten = function () {
5548 if (this._written)
5549 throw new Error('write() already called on this batch')
5550}
5551
5552AbstractChainedBatch.prototype.put = function (key, value) {
5553 this._checkWritten()
5554
5555 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
5556 if (err) throw err
5557 err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
5558 if (err) throw err
5559
5560 if (!this._db._isBuffer(key)) key = String(key)
5561 if (!this._db._isBuffer(value)) value = String(value)
5562
5563 if (typeof this._put == 'function' )
5564 this._put(key, value)
5565 else
5566 this._operations.push({ type: 'put', key: key, value: value })
5567
5568 return this
5569}
5570
5571AbstractChainedBatch.prototype.del = function (key) {
5572 this._checkWritten()
5573
5574 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
5575 if (err) throw err
5576
5577 if (!this._db._isBuffer(key)) key = String(key)
5578
5579 if (typeof this._del == 'function' )
5580 this._del(key)
5581 else
5582 this._operations.push({ type: 'del', key: key })
5583
5584 return this
5585}
5586
5587AbstractChainedBatch.prototype.clear = function () {
5588 this._checkWritten()
5589
5590 this._operations = []
5591
5592 if (typeof this._clear == 'function' )
5593 this._clear()
5594
5595 return this
5596}
5597
5598AbstractChainedBatch.prototype.write = function (options, callback) {
5599 this._checkWritten()
5600
5601 if (typeof options == 'function')
5602 callback = options
5603 if (typeof callback != 'function')
5604 throw new Error('write() requires a callback argument')
5605 if (typeof options != 'object')
5606 options = {}
5607
5608 this._written = true
5609
5610 if (typeof this._write == 'function' )
5611 return this._write(callback)
5612
5613 if (typeof this._db._batch == 'function')
5614 return this._db._batch(this._operations, options, callback)
5615
5616 process.nextTick(callback)
5617}
5618
5619module.exports = AbstractChainedBatch}, {}],23: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
5620//
5621// Permission is hereby granted, free of charge, to any person obtaining a
5622// copy of this software and associated documentation files (the
5623// "Software"), to deal in the Software without restriction, including
5624// without limitation the rights to use, copy, modify, merge, publish,
5625// distribute, sublicense, and/or sell copies of the Software, and to permit
5626// persons to whom the Software is furnished to do so, subject to the
5627// following conditions:
5628//
5629// The above copyright notice and this permission notice shall be included
5630// in all copies or substantial portions of the Software.
5631//
5632// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5633// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5634// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5635// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5636// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5637// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5638// USE OR OTHER DEALINGS IN THE SOFTWARE.
5639
5640var formatRegExp = /%[sdj%]/g;
5641exports.format = function(f) {
5642 if (!isString(f)) {
5643 var objects = [];
5644 for (var i = 0; i < arguments.length; i++) {
5645 objects.push(inspect(arguments[i]));
5646 }
5647 return objects.join(' ');
5648 }
5649
5650 var i = 1;
5651 var args = arguments;
5652 var len = args.length;
5653 var str = String(f).replace(formatRegExp, function(x) {
5654 if (x === '%%') return '%';
5655 if (i >= len) return x;
5656 switch (x) {
5657 case '%s': return String(args[i++]);
5658 case '%d': return Number(args[i++]);
5659 case '%j':
5660 try {
5661 return JSON.stringify(args[i++]);
5662 } catch (_) {
5663 return '[Circular]';
5664 }
5665 default:
5666 return x;
5667 }
5668 });
5669 for (var x = args[i]; i < len; x = args[++i]) {
5670 if (isNull(x) || !isObject(x)) {
5671 str += ' ' + x;
5672 } else {
5673 str += ' ' + inspect(x);
5674 }
5675 }
5676 return str;
5677};
5678
5679
5680// Mark that a method should not be used.
5681// Returns a modified function which warns once by default.
5682// If --no-deprecation is set, then it is a no-op.
5683exports.deprecate = function(fn, msg) {
5684 // Allow for deprecating things in the process of starting up.
5685 if (isUndefined(global.process)) {
5686 return function() {
5687 return exports.deprecate(fn, msg).apply(this, arguments);
5688 };
5689 }
5690
5691 if (process.noDeprecation === true) {
5692 return fn;
5693 }
5694
5695 var warned = false;
5696 function deprecated() {
5697 if (!warned) {
5698 if (process.throwDeprecation) {
5699 throw new Error(msg);
5700 } else if (process.traceDeprecation) {
5701 console.trace(msg);
5702 } else {
5703 console.error(msg);
5704 }
5705 warned = true;
5706 }
5707 return fn.apply(this, arguments);
5708 }
5709
5710 return deprecated;
5711};
5712
5713
5714var debugs = {};
5715var debugEnviron;
5716exports.debuglog = function(set) {
5717 if (isUndefined(debugEnviron))
5718 debugEnviron = process.env.NODE_DEBUG || '';
5719 set = set.toUpperCase();
5720 if (!debugs[set]) {
5721 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
5722 var pid = process.pid;
5723 debugs[set] = function() {
5724 var msg = exports.format.apply(exports, arguments);
5725 console.error('%s %d: %s', set, pid, msg);
5726 };
5727 } else {
5728 debugs[set] = function() {};
5729 }
5730 }
5731 return debugs[set];
5732};
5733
5734
5735/**
5736 * Echos the value of a value. Trys to print the value out
5737 * in the best way possible given the different types.
5738 *
5739 * @param {Object} obj The object to print out.
5740 * @param {Object} opts Optional options object that alters the output.
5741 */
5742/* legacy: obj, showHidden, depth, colors*/
5743function inspect(obj, opts) {
5744 // default options
5745 var ctx = {
5746 seen: [],
5747 stylize: stylizeNoColor
5748 };
5749 // legacy...
5750 if (arguments.length >= 3) ctx.depth = arguments[2];
5751 if (arguments.length >= 4) ctx.colors = arguments[3];
5752 if (isBoolean(opts)) {
5753 // legacy...
5754 ctx.showHidden = opts;
5755 } else if (opts) {
5756 // got an "options" object
5757 exports._extend(ctx, opts);
5758 }
5759 // set default options
5760 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
5761 if (isUndefined(ctx.depth)) ctx.depth = 2;
5762 if (isUndefined(ctx.colors)) ctx.colors = false;
5763 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
5764 if (ctx.colors) ctx.stylize = stylizeWithColor;
5765 return formatValue(ctx, obj, ctx.depth);
5766}
5767exports.inspect = inspect;
5768
5769
5770// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
5771inspect.colors = {
5772 'bold' : [1, 22],
5773 'italic' : [3, 23],
5774 'underline' : [4, 24],
5775 'inverse' : [7, 27],
5776 'white' : [37, 39],
5777 'grey' : [90, 39],
5778 'black' : [30, 39],
5779 'blue' : [34, 39],
5780 'cyan' : [36, 39],
5781 'green' : [32, 39],
5782 'magenta' : [35, 39],
5783 'red' : [31, 39],
5784 'yellow' : [33, 39]
5785};
5786
5787// Don't use 'blue' not visible on cmd.exe
5788inspect.styles = {
5789 'special': 'cyan',
5790 'number': 'yellow',
5791 'boolean': 'yellow',
5792 'undefined': 'grey',
5793 'null': 'bold',
5794 'string': 'green',
5795 'date': 'magenta',
5796 // "name": intentionally not styling
5797 'regexp': 'red'
5798};
5799
5800
5801function stylizeWithColor(str, styleType) {
5802 var style = inspect.styles[styleType];
5803
5804 if (style) {
5805 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
5806 '\u001b[' + inspect.colors[style][1] + 'm';
5807 } else {
5808 return str;
5809 }
5810}
5811
5812
5813function stylizeNoColor(str, styleType) {
5814 return str;
5815}
5816
5817
5818function arrayToHash(array) {
5819 var hash = {};
5820
5821 array.forEach(function(val, idx) {
5822 hash[val] = true;
5823 });
5824
5825 return hash;
5826}
5827
5828
5829function formatValue(ctx, value, recurseTimes) {
5830 // Provide a hook for user-specified inspect functions.
5831 // Check that value is an object with an inspect function on it
5832 if (ctx.customInspect &&
5833 value &&
5834 isFunction(value.inspect) &&
5835 // Filter out the util module, it's inspect function is special
5836 value.inspect !== exports.inspect &&
5837 // Also filter out any prototype objects using the circular check.
5838 !(value.constructor && value.constructor.prototype === value)) {
5839 var ret = value.inspect(recurseTimes, ctx);
5840 if (!isString(ret)) {
5841 ret = formatValue(ctx, ret, recurseTimes);
5842 }
5843 return ret;
5844 }
5845
5846 // Primitive types cannot have properties
5847 var primitive = formatPrimitive(ctx, value);
5848 if (primitive) {
5849 return primitive;
5850 }
5851
5852 // Look up the keys of the object.
5853 var keys = Object.keys(value);
5854 var visibleKeys = arrayToHash(keys);
5855
5856 if (ctx.showHidden) {
5857 keys = Object.getOwnPropertyNames(value);
5858 }
5859
5860 // IE doesn't make error fields non-enumerable
5861 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
5862 if (isError(value)
5863 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
5864 return formatError(value);
5865 }
5866
5867 // Some type of object without properties can be shortcutted.
5868 if (keys.length === 0) {
5869 if (isFunction(value)) {
5870 var name = value.name ? ': ' + value.name : '';
5871 return ctx.stylize('[Function' + name + ']', 'special');
5872 }
5873 if (isRegExp(value)) {
5874 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
5875 }
5876 if (isDate(value)) {
5877 return ctx.stylize(Date.prototype.toString.call(value), 'date');
5878 }
5879 if (isError(value)) {
5880 return formatError(value);
5881 }
5882 }
5883
5884 var base = '', array = false, braces = ['{', '}'];
5885
5886 // Make Array say that they are Array
5887 if (isArray(value)) {
5888 array = true;
5889 braces = ['[', ']'];
5890 }
5891
5892 // Make functions say that they are functions
5893 if (isFunction(value)) {
5894 var n = value.name ? ': ' + value.name : '';
5895 base = ' [Function' + n + ']';
5896 }
5897
5898 // Make RegExps say that they are RegExps
5899 if (isRegExp(value)) {
5900 base = ' ' + RegExp.prototype.toString.call(value);
5901 }
5902
5903 // Make dates with properties first say the date
5904 if (isDate(value)) {
5905 base = ' ' + Date.prototype.toUTCString.call(value);
5906 }
5907
5908 // Make error with message first say the error
5909 if (isError(value)) {
5910 base = ' ' + formatError(value);
5911 }
5912
5913 if (keys.length === 0 && (!array || value.length == 0)) {
5914 return braces[0] + base + braces[1];
5915 }
5916
5917 if (recurseTimes < 0) {
5918 if (isRegExp(value)) {
5919 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
5920 } else {
5921 return ctx.stylize('[Object]', 'special');
5922 }
5923 }
5924
5925 ctx.seen.push(value);
5926
5927 var output;
5928 if (array) {
5929 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
5930 } else {
5931 output = keys.map(function(key) {
5932 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
5933 });
5934 }
5935
5936 ctx.seen.pop();
5937
5938 return reduceToSingleString(output, base, braces);
5939}
5940
5941
5942function formatPrimitive(ctx, value) {
5943 if (isUndefined(value))
5944 return ctx.stylize('undefined', 'undefined');
5945 if (isString(value)) {
5946 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
5947 .replace(/'/g, "\\'")
5948 .replace(/\\"/g, '"') + '\'';
5949 return ctx.stylize(simple, 'string');
5950 }
5951 if (isNumber(value))
5952 return ctx.stylize('' + value, 'number');
5953 if (isBoolean(value))
5954 return ctx.stylize('' + value, 'boolean');
5955 // For some reason typeof null is "object", so special case here.
5956 if (isNull(value))
5957 return ctx.stylize('null', 'null');
5958}
5959
5960
5961function formatError(value) {
5962 return '[' + Error.prototype.toString.call(value) + ']';
5963}
5964
5965
5966function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
5967 var output = [];
5968 for (var i = 0, l = value.length; i < l; ++i) {
5969 if (hasOwnProperty(value, String(i))) {
5970 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
5971 String(i), true));
5972 } else {
5973 output.push('');
5974 }
5975 }
5976 keys.forEach(function(key) {
5977 if (!key.match(/^\d+$/)) {
5978 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
5979 key, true));
5980 }
5981 });
5982 return output;
5983}
5984
5985
5986function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
5987 var name, str, desc;
5988 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
5989 if (desc.get) {
5990 if (desc.set) {
5991 str = ctx.stylize('[Getter/Setter]', 'special');
5992 } else {
5993 str = ctx.stylize('[Getter]', 'special');
5994 }
5995 } else {
5996 if (desc.set) {
5997 str = ctx.stylize('[Setter]', 'special');
5998 }
5999 }
6000 if (!hasOwnProperty(visibleKeys, key)) {
6001 name = '[' + key + ']';
6002 }
6003 if (!str) {
6004 if (ctx.seen.indexOf(desc.value) < 0) {
6005 if (isNull(recurseTimes)) {
6006 str = formatValue(ctx, desc.value, null);
6007 } else {
6008 str = formatValue(ctx, desc.value, recurseTimes - 1);
6009 }
6010 if (str.indexOf('\n') > -1) {
6011 if (array) {
6012 str = str.split('\n').map(function(line) {
6013 return ' ' + line;
6014 }).join('\n').substr(2);
6015 } else {
6016 str = '\n' + str.split('\n').map(function(line) {
6017 return ' ' + line;
6018 }).join('\n');
6019 }
6020 }
6021 } else {
6022 str = ctx.stylize('[Circular]', 'special');
6023 }
6024 }
6025 if (isUndefined(name)) {
6026 if (array && key.match(/^\d+$/)) {
6027 return str;
6028 }
6029 name = JSON.stringify('' + key);
6030 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
6031 name = name.substr(1, name.length - 2);
6032 name = ctx.stylize(name, 'name');
6033 } else {
6034 name = name.replace(/'/g, "\\'")
6035 .replace(/\\"/g, '"')
6036 .replace(/(^"|"$)/g, "'");
6037 name = ctx.stylize(name, 'string');
6038 }
6039 }
6040
6041 return name + ': ' + str;
6042}
6043
6044
6045function reduceToSingleString(output, base, braces) {
6046 var numLinesEst = 0;
6047 var length = output.reduce(function(prev, cur) {
6048 numLinesEst++;
6049 if (cur.indexOf('\n') >= 0) numLinesEst++;
6050 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
6051 }, 0);
6052
6053 if (length > 60) {
6054 return braces[0] +
6055 (base === '' ? '' : base + '\n ') +
6056 ' ' +
6057 output.join(',\n ') +
6058 ' ' +
6059 braces[1];
6060 }
6061
6062 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
6063}
6064
6065
6066// NOTE: These type checking functions intentionally don't use `instanceof`
6067// because it is fragile and can be easily faked with `Object.create()`.
6068function isArray(ar) {
6069 return Array.isArray(ar);
6070}
6071exports.isArray = isArray;
6072
6073function isBoolean(arg) {
6074 return typeof arg === 'boolean';
6075}
6076exports.isBoolean = isBoolean;
6077
6078function isNull(arg) {
6079 return arg === null;
6080}
6081exports.isNull = isNull;
6082
6083function isNullOrUndefined(arg) {
6084 return arg == null;
6085}
6086exports.isNullOrUndefined = isNullOrUndefined;
6087
6088function isNumber(arg) {
6089 return typeof arg === 'number';
6090}
6091exports.isNumber = isNumber;
6092
6093function isString(arg) {
6094 return typeof arg === 'string';
6095}
6096exports.isString = isString;
6097
6098function isSymbol(arg) {
6099 return typeof arg === 'symbol';
6100}
6101exports.isSymbol = isSymbol;
6102
6103function isUndefined(arg) {
6104 return arg === void 0;
6105}
6106exports.isUndefined = isUndefined;
6107
6108function isRegExp(re) {
6109 return isObject(re) && objectToString(re) === '[object RegExp]';
6110}
6111exports.isRegExp = isRegExp;
6112
6113function isObject(arg) {
6114 return typeof arg === 'object' && arg !== null;
6115}
6116exports.isObject = isObject;
6117
6118function isDate(d) {
6119 return isObject(d) && objectToString(d) === '[object Date]';
6120}
6121exports.isDate = isDate;
6122
6123function isError(e) {
6124 return isObject(e) &&
6125 (objectToString(e) === '[object Error]' || e instanceof Error);
6126}
6127exports.isError = isError;
6128
6129function isFunction(arg) {
6130 return typeof arg === 'function';
6131}
6132exports.isFunction = isFunction;
6133
6134function isPrimitive(arg) {
6135 return arg === null ||
6136 typeof arg === 'boolean' ||
6137 typeof arg === 'number' ||
6138 typeof arg === 'string' ||
6139 typeof arg === 'symbol' || // ES6 symbol
6140 typeof arg === 'undefined';
6141}
6142exports.isPrimitive = isPrimitive;
6143
6144exports.isBuffer = require('./support/isBuffer');
6145
6146function objectToString(o) {
6147 return Object.prototype.toString.call(o);
6148}
6149
6150
6151function pad(n) {
6152 return n < 10 ? '0' + n.toString(10) : n.toString(10);
6153}
6154
6155
6156var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6157 'Oct', 'Nov', 'Dec'];
6158
6159// 26 Feb 16:19:34
6160function timestamp() {
6161 var d = new Date();
6162 var time = [pad(d.getHours()),
6163 pad(d.getMinutes()),
6164 pad(d.getSeconds())].join(':');
6165 return [d.getDate(), months[d.getMonth()], time].join(' ');
6166}
6167
6168
6169// log is just a thin wrapper to console.log that prepends a timestamp
6170exports.log = function() {
6171 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
6172};
6173
6174
6175/**
6176 * Inherit the prototype methods from one constructor into another.
6177 *
6178 * The Function.prototype.inherits from lang.js rewritten as a standalone
6179 * function (not on Function.prototype). NOTE: If this file is to be loaded
6180 * during bootstrapping this function needs to be rewritten using some native
6181 * functions as prototype setup using normal JavaScript does not work as
6182 * expected during bootstrapping (see mirror.js in r114903).
6183 *
6184 * @param {function} ctor Constructor function which needs to inherit the
6185 * prototype.
6186 * @param {function} superCtor Constructor function to inherit prototype from.
6187 */
6188exports.inherits = require('inherits');
6189
6190exports._extend = function(origin, add) {
6191 // Don't do anything if add isn't an object
6192 if (!add || !isObject(add)) return origin;
6193
6194 var keys = Object.keys(add);
6195 var i = keys.length;
6196 while (i--) {
6197 origin[keys[i]] = add[keys[i]];
6198 }
6199 return origin;
6200};
6201
6202function hasOwnProperty(obj, prop) {
6203 return Object.prototype.hasOwnProperty.call(obj, prop);
6204}
6205}, {"./support/isBuffer":24,"inherits":25}],24: [function (exports, require, module, global) {module.exports = function isBuffer(arg) {
6206 return arg && typeof arg === 'object'
6207 && typeof arg.copy === 'function'
6208 && typeof arg.fill === 'function'
6209 && typeof arg.readUInt8 === 'function';
6210}}, {}],25: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
6211 // implementation from standard node.js 'util' module
6212 module.exports = function inherits(ctor, superCtor) {
6213 ctor.super_ = superCtor
6214 ctor.prototype = Object.create(superCtor.prototype, {
6215 constructor: {
6216 value: ctor,
6217 enumerable: false,
6218 writable: true,
6219 configurable: true
6220 }
6221 });
6222 };
6223} else {
6224 // old school shim for old browsers
6225 module.exports = function inherits(ctor, superCtor) {
6226 ctor.super_ = superCtor
6227 var TempCtor = function () {}
6228 TempCtor.prototype = superCtor.prototype
6229 ctor.prototype = new TempCtor()
6230 ctor.prototype.constructor = ctor
6231 }
6232}
6233}, {}],26: [function (exports, require, module, global) {var util = require('util')
6234var AbstractIterator = require('abstract-leveldown').AbstractIterator
6235var ltgt = require('ltgt')
6236
6237module.exports = Iterator
6238
6239function Iterator (db, options) {
6240 if (!options) options = {}
6241 this.options = options
6242 AbstractIterator.call(this, db)
6243 this._order = options.reverse ? 'DESC': 'ASC'
6244 this._limit = options.limit
6245 this._count = 0
6246 this._done = false
6247 var lower = ltgt.lowerBound(options)
6248 var upper = ltgt.upperBound(options)
6249 try {
6250 this._keyRange = lower || upper ? this.db.makeKeyRange({
6251 lower: lower,
6252 upper: upper,
6253 excludeLower: ltgt.lowerBoundExclusive(options),
6254 excludeUpper: ltgt.upperBoundExclusive(options)
6255 }) : null
6256 } catch (e) {
6257 // The lower key is greater than the upper key.
6258 // IndexedDB throws an error, but we'll just return 0 results.
6259 this._keyRangeError = true
6260 }
6261 this.callback = null
6262}
6263
6264util.inherits(Iterator, AbstractIterator)
6265
6266Iterator.prototype.createIterator = function() {
6267 var self = this
6268
6269 self.iterator = self.db.iterate(function () {
6270 self.onItem.apply(self, arguments)
6271 }, {
6272 keyRange: self._keyRange,
6273 autoContinue: false,
6274 order: self._order,
6275 onError: function(err) { console.log('horrible error', err) },
6276 })
6277}
6278
6279// TODO the limit implementation here just ignores all reads after limit has been reached
6280// it should cancel the iterator instead but I don't know how
6281Iterator.prototype.onItem = function (value, cursor, cursorTransaction) {
6282 if (!cursor && this.callback) {
6283 this.callback()
6284 this.callback = false
6285 return
6286 }
6287 var shouldCall = true
6288
6289 if (!!this._limit && this._limit > 0 && this._count++ >= this._limit)
6290 shouldCall = false
6291
6292 if (shouldCall) this.callback(false, cursor.key, cursor.value)
6293 if (cursor) cursor['continue']()
6294}
6295
6296Iterator.prototype._next = function (callback) {
6297 if (!callback) return new Error('next() requires a callback argument')
6298 if (this._keyRangeError) return callback()
6299 if (!this._started) {
6300 this.createIterator()
6301 this._started = true
6302 }
6303 this.callback = callback
6304}
6305}, {"util":23,"abstract-leveldown":19,"ltgt":27}],27: [function (exports, require, module, global) {
6306exports.compare = function (a, b) {
6307
6308 if(Buffer.isBuffer(a)) {
6309 var l = Math.min(a.length, b.length)
6310 for(var i = 0; i < l; i++) {
6311 var cmp = a[i] - b[i]
6312 if(cmp) return cmp
6313 }
6314 return a.length - b.length
6315 }
6316
6317 return a < b ? -1 : a > b ? 1 : 0
6318}
6319
6320function has(obj, key) {
6321 return Object.hasOwnProperty.call(obj, key)
6322}
6323
6324// to be compatible with the current abstract-leveldown tests
6325// nullish or empty strings.
6326// I could use !!val but I want to permit numbers and booleans,
6327// if possible.
6328
6329function isDef (val) {
6330 return val !== undefined && val !== ''
6331}
6332
6333function has (range, name) {
6334 return Object.hasOwnProperty.call(range, name)
6335}
6336
6337function hasKey(range, name) {
6338 return Object.hasOwnProperty.call(range, name) && name
6339}
6340
6341var lowerBoundKey = exports.lowerBoundKey = function (range) {
6342 return (
6343 hasKey(range, 'gt')
6344 || hasKey(range, 'gte')
6345 || hasKey(range, 'min')
6346 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
6347 || undefined
6348 )
6349}
6350
6351var lowerBound = exports.lowerBound = function (range) {
6352 var k = lowerBoundKey(range)
6353 return k && range[k]
6354 return (
6355 has(range, 'gt') ? range.gt
6356 : has(range, 'gte') ? range.gte
6357 : has(range, 'min') ? range.min
6358 : has(range, 'start') && !range.reverse ? range.start
6359 : has(range, 'end') && range.reverse ? range.end
6360 : undefined
6361 )
6362}
6363
6364exports.lowerBoundInclusive = function (range) {
6365 return has(range, 'gt') ? false : true
6366}
6367
6368exports.upperBoundInclusive =
6369 function (range) {
6370 return has(range, 'lt') || !range.minEx ? false : true
6371 }
6372
6373var lowerBoundExclusive = exports.lowerBoundExclusive =
6374 function (range) {
6375 return has(range, 'gt') || range.minEx ? true : false
6376 }
6377
6378var upperBoundExclusive = exports.upperBoundExclusive =
6379 function (range) {
6380 return has(range, 'lt') ? true : false
6381 }
6382
6383var upperBoundKey = exports.upperBoundKey = function (range) {
6384 return (
6385 hasKey(range, 'lt')
6386 || hasKey(range, 'lte')
6387 || hasKey(range, 'max')
6388 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
6389 || undefined
6390 )
6391}
6392
6393var upperBound = exports.upperBound = function (range) {
6394 var k = upperBoundKey(range)
6395 return k && range[k]
6396}
6397
6398function id (e) { return e }
6399
6400exports.toLtgt = function (range, _range, map, lower, upper) {
6401 _range = _range || {}
6402 map = map || id
6403 var defaults = arguments.length > 3
6404 var lb = exports.lowerBoundKey(range)
6405 var ub = exports.upperBoundKey(range)
6406 if(lb) {
6407 if(lb === 'gt') _range.gt = map(range.gt)
6408 else _range.gte = map(range[lb])
6409 }
6410 else if(defaults)
6411 _range.gte = lower
6412
6413 if(ub) {
6414 if(ub === 'lt') _range.lt = map(range.lt)
6415 else _range.lte = map(range[ub])
6416 }
6417 else if(defaults)
6418 _range.lte = upper
6419
6420 _range.reverse = !!range.reverse
6421
6422 return _range
6423}
6424
6425exports.contains = function (range, key, compare) {
6426 compare = compare || exports.compare
6427
6428 var lb = lowerBound(range)
6429 if(isDef(lb)) {
6430 var cmp = compare(key, lb)
6431 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
6432 return false
6433 }
6434
6435 var ub = upperBound(range)
6436 if(isDef(ub)) {
6437 var cmp = compare(key, ub)
6438 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
6439 return false
6440 }
6441
6442 return true
6443}
6444
6445exports.filter = function (range, compare) {
6446 return function (key) {
6447 return exports.contains(range, key, compare)
6448 }
6449}
6450}, {}],28: [function (exports, require, module, global) {var Buffer = require('buffer').Buffer;
6451
6452module.exports = isBuffer;
6453
6454function isBuffer (o) {
6455 return Buffer.isBuffer(o)
6456 || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o));
6457}
6458}, {"buffer":29}],29: [function (exports, require, module, global) {var assert;
6459exports.Buffer = Buffer;
6460exports.SlowBuffer = Buffer;
6461Buffer.poolSize = 8192;
6462exports.INSPECT_MAX_BYTES = 50;
6463
6464function stringtrim(str) {
6465 if (str.trim) return str.trim();
6466 return str.replace(/^\s+|\s+$/g, '');
6467}
6468
6469function Buffer(subject, encoding, offset) {
6470 if(!assert) assert= require('assert');
6471 if (!(this instanceof Buffer)) {
6472 return new Buffer(subject, encoding, offset);
6473 }
6474 this.parent = this;
6475 this.offset = 0;
6476
6477 // Work-around: node's base64 implementation
6478 // allows for non-padded strings while base64-js
6479 // does not..
6480 if (encoding == "base64" && typeof subject == "string") {
6481 subject = stringtrim(subject);
6482 while (subject.length % 4 != 0) {
6483 subject = subject + "=";
6484 }
6485 }
6486
6487 var type;
6488
6489 // Are we slicing?
6490 if (typeof offset === 'number') {
6491 this.length = coerce(encoding);
6492 // slicing works, with limitations (no parent tracking/update)
6493 // check https://github.com/toots/buffer-browserify/issues/19
6494 for (var i = 0; i < this.length; i++) {
6495 this[i] = subject.get(i+offset);
6496 }
6497 } else {
6498 // Find the length
6499 switch (type = typeof subject) {
6500 case 'number':
6501 this.length = coerce(subject);
6502 break;
6503
6504 case 'string':
6505 this.length = Buffer.byteLength(subject, encoding);
6506 break;
6507
6508 case 'object': // Assume object is an array
6509 this.length = coerce(subject.length);
6510 break;
6511
6512 default:
6513 throw new TypeError('First argument needs to be a number, ' +
6514 'array or string.');
6515 }
6516
6517 // Treat array-ish objects as a byte array.
6518 if (isArrayIsh(subject)) {
6519 for (var i = 0; i < this.length; i++) {
6520 if (subject instanceof Buffer) {
6521 this[i] = subject.readUInt8(i);
6522 }
6523 else {
6524 // Round-up subject[i] to a UInt8.
6525 // e.g.: ((-432 % 256) + 256) % 256 = (-176 + 256) % 256
6526 // = 80
6527 this[i] = ((subject[i] % 256) + 256) % 256;
6528 }
6529 }
6530 } else if (type == 'string') {
6531 // We are a string
6532 this.length = this.write(subject, 0, encoding);
6533 } else if (type === 'number') {
6534 for (var i = 0; i < this.length; i++) {
6535 this[i] = 0;
6536 }
6537 }
6538 }
6539}
6540
6541Buffer.prototype.get = function get(i) {
6542 if (i < 0 || i >= this.length) throw new Error('oob');
6543 return this[i];
6544};
6545
6546Buffer.prototype.set = function set(i, v) {
6547 if (i < 0 || i >= this.length) throw new Error('oob');
6548 return this[i] = v;
6549};
6550
6551Buffer.byteLength = function (str, encoding) {
6552 switch (encoding || "utf8") {
6553 case 'hex':
6554 return str.length / 2;
6555
6556 case 'utf8':
6557 case 'utf-8':
6558 return utf8ToBytes(str).length;
6559
6560 case 'ascii':
6561 case 'binary':
6562 return str.length;
6563
6564 case 'base64':
6565 return base64ToBytes(str).length;
6566
6567 default:
6568 throw new Error('Unknown encoding');
6569 }
6570};
6571
6572Buffer.prototype.utf8Write = function (string, offset, length) {
6573 var bytes, pos;
6574 return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length);
6575};
6576
6577Buffer.prototype.asciiWrite = function (string, offset, length) {
6578 var bytes, pos;
6579 return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length);
6580};
6581
6582Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite;
6583
6584Buffer.prototype.base64Write = function (string, offset, length) {
6585 var bytes, pos;
6586 return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);
6587};
6588
6589Buffer.prototype.base64Slice = function (start, end) {
6590 var bytes = Array.prototype.slice.apply(this, arguments)
6591 return require("base64-js").fromByteArray(bytes);
6592};
6593
6594Buffer.prototype.utf8Slice = function () {
6595 var bytes = Array.prototype.slice.apply(this, arguments);
6596 var res = "";
6597 var tmp = "";
6598 var i = 0;
6599 while (i < bytes.length) {
6600 if (bytes[i] <= 0x7F) {
6601 res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);
6602 tmp = "";
6603 } else
6604 tmp += "%" + bytes[i].toString(16);
6605
6606 i++;
6607 }
6608
6609 return res + decodeUtf8Char(tmp);
6610}
6611
6612Buffer.prototype.asciiSlice = function () {
6613 var bytes = Array.prototype.slice.apply(this, arguments);
6614 var ret = "";
6615 for (var i = 0; i < bytes.length; i++)
6616 ret += String.fromCharCode(bytes[i]);
6617 return ret;
6618}
6619
6620Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice;
6621
6622Buffer.prototype.inspect = function() {
6623 var out = [],
6624 len = this.length;
6625 for (var i = 0; i < len; i++) {
6626 out[i] = toHex(this[i]);
6627 if (i == exports.INSPECT_MAX_BYTES) {
6628 out[i + 1] = '...';
6629 break;
6630 }
6631 }
6632 return '<Buffer ' + out.join(' ') + '>';
6633};
6634
6635
6636Buffer.prototype.hexSlice = function(start, end) {
6637 var len = this.length;
6638
6639 if (!start || start < 0) start = 0;
6640 if (!end || end < 0 || end > len) end = len;
6641
6642 var out = '';
6643 for (var i = start; i < end; i++) {
6644 out += toHex(this[i]);
6645 }
6646 return out;
6647};
6648
6649
6650Buffer.prototype.toString = function(encoding, start, end) {
6651 encoding = String(encoding || 'utf8').toLowerCase();
6652 start = +start || 0;
6653 if (typeof end == 'undefined') end = this.length;
6654
6655 // Fastpath empty strings
6656 if (+end == start) {
6657 return '';
6658 }
6659
6660 switch (encoding) {
6661 case 'hex':
6662 return this.hexSlice(start, end);
6663
6664 case 'utf8':
6665 case 'utf-8':
6666 return this.utf8Slice(start, end);
6667
6668 case 'ascii':
6669 return this.asciiSlice(start, end);
6670
6671 case 'binary':
6672 return this.binarySlice(start, end);
6673
6674 case 'base64':
6675 return this.base64Slice(start, end);
6676
6677 case 'ucs2':
6678 case 'ucs-2':
6679 return this.ucs2Slice(start, end);
6680
6681 default:
6682 throw new Error('Unknown encoding');
6683 }
6684};
6685
6686
6687Buffer.prototype.hexWrite = function(string, offset, length) {
6688 offset = +offset || 0;
6689 var remaining = this.length - offset;
6690 if (!length) {
6691 length = remaining;
6692 } else {
6693 length = +length;
6694 if (length > remaining) {
6695 length = remaining;
6696 }
6697 }
6698
6699 // must be an even number of digits
6700 var strLen = string.length;
6701 if (strLen % 2) {
6702 throw new Error('Invalid hex string');
6703 }
6704 if (length > strLen / 2) {
6705 length = strLen / 2;
6706 }
6707 for (var i = 0; i < length; i++) {
6708 var b = parseInt(string.substr(i * 2, 2), 16);
6709 if (isNaN(b)) throw new Error('Invalid hex string');
6710 this[offset + i] = b;
6711 }
6712 Buffer._charsWritten = i * 2;
6713 return i;
6714};
6715
6716
6717Buffer.prototype.write = function(string, offset, length, encoding) {
6718 // Support both (string, offset, length, encoding)
6719 // and the legacy (string, encoding, offset, length)
6720 if (isFinite(offset)) {
6721 if (!isFinite(length)) {
6722 encoding = length;
6723 length = undefined;
6724 }
6725 } else { // legacy
6726 var swap = encoding;
6727 encoding = offset;
6728 offset = length;
6729 length = swap;
6730 }
6731
6732 offset = +offset || 0;
6733 var remaining = this.length - offset;
6734 if (!length) {
6735 length = remaining;
6736 } else {
6737 length = +length;
6738 if (length > remaining) {
6739 length = remaining;
6740 }
6741 }
6742 encoding = String(encoding || 'utf8').toLowerCase();
6743
6744 switch (encoding) {
6745 case 'hex':
6746 return this.hexWrite(string, offset, length);
6747
6748 case 'utf8':
6749 case 'utf-8':
6750 return this.utf8Write(string, offset, length);
6751
6752 case 'ascii':
6753 return this.asciiWrite(string, offset, length);
6754
6755 case 'binary':
6756 return this.binaryWrite(string, offset, length);
6757
6758 case 'base64':
6759 return this.base64Write(string, offset, length);
6760
6761 case 'ucs2':
6762 case 'ucs-2':
6763 return this.ucs2Write(string, offset, length);
6764
6765 default:
6766 throw new Error('Unknown encoding');
6767 }
6768};
6769
6770// slice(start, end)
6771function clamp(index, len, defaultValue) {
6772 if (typeof index !== 'number') return defaultValue;
6773 index = ~~index; // Coerce to integer.
6774 if (index >= len) return len;
6775 if (index >= 0) return index;
6776 index += len;
6777 if (index >= 0) return index;
6778 return 0;
6779}
6780
6781Buffer.prototype.slice = function(start, end) {
6782 var len = this.length;
6783 start = clamp(start, len, 0);
6784 end = clamp(end, len, len);
6785 return new Buffer(this, end - start, +start);
6786};
6787
6788// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
6789Buffer.prototype.copy = function(target, target_start, start, end) {
6790 var source = this;
6791 start || (start = 0);
6792 if (end === undefined || isNaN(end)) {
6793 end = this.length;
6794 }
6795 target_start || (target_start = 0);
6796
6797 if (end < start) throw new Error('sourceEnd < sourceStart');
6798
6799 // Copy 0 bytes; we're done
6800 if (end === start) return 0;
6801 if (target.length == 0 || source.length == 0) return 0;
6802
6803 if (target_start < 0 || target_start >= target.length) {
6804 throw new Error('targetStart out of bounds');
6805 }
6806
6807 if (start < 0 || start >= source.length) {
6808 throw new Error('sourceStart out of bounds');
6809 }
6810
6811 if (end < 0 || end > source.length) {
6812 throw new Error('sourceEnd out of bounds');
6813 }
6814
6815 // Are we oob?
6816 if (end > this.length) {
6817 end = this.length;
6818 }
6819
6820 if (target.length - target_start < end - start) {
6821 end = target.length - target_start + start;
6822 }
6823
6824 var temp = [];
6825 for (var i=start; i<end; i++) {
6826 assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!");
6827 temp.push(this[i]);
6828 }
6829
6830 for (var i=target_start; i<target_start+temp.length; i++) {
6831 target[i] = temp[i-target_start];
6832 }
6833};
6834
6835// fill(value, start=0, end=buffer.length)
6836Buffer.prototype.fill = function fill(value, start, end) {
6837 value || (value = 0);
6838 start || (start = 0);
6839 end || (end = this.length);
6840
6841 if (typeof value === 'string') {
6842 value = value.charCodeAt(0);
6843 }
6844 if (!(typeof value === 'number') || isNaN(value)) {
6845 throw new Error('value is not a number');
6846 }
6847
6848 if (end < start) throw new Error('end < start');
6849
6850 // Fill 0 bytes; we're done
6851 if (end === start) return 0;
6852 if (this.length == 0) return 0;
6853
6854 if (start < 0 || start >= this.length) {
6855 throw new Error('start out of bounds');
6856 }
6857
6858 if (end < 0 || end > this.length) {
6859 throw new Error('end out of bounds');
6860 }
6861
6862 for (var i = start; i < end; i++) {
6863 this[i] = value;
6864 }
6865}
6866
6867// Static methods
6868Buffer.isBuffer = function isBuffer(b) {
6869 return b instanceof Buffer;
6870};
6871
6872Buffer.concat = function (list, totalLength) {
6873 if (!isArray(list)) {
6874 throw new Error("Usage: Buffer.concat(list, [totalLength])\n \
6875 list should be an Array.");
6876 }
6877
6878 if (list.length === 0) {
6879 return new Buffer(0);
6880 } else if (list.length === 1) {
6881 return list[0];
6882 }
6883
6884 if (typeof totalLength !== 'number') {
6885 totalLength = 0;
6886 for (var i = 0; i < list.length; i++) {
6887 var buf = list[i];
6888 totalLength += buf.length;
6889 }
6890 }
6891
6892 var buffer = new Buffer(totalLength);
6893 var pos = 0;
6894 for (var i = 0; i < list.length; i++) {
6895 var buf = list[i];
6896 buf.copy(buffer, pos);
6897 pos += buf.length;
6898 }
6899 return buffer;
6900};
6901
6902Buffer.isEncoding = function(encoding) {
6903 switch ((encoding + '').toLowerCase()) {
6904 case 'hex':
6905 case 'utf8':
6906 case 'utf-8':
6907 case 'ascii':
6908 case 'binary':
6909 case 'base64':
6910 case 'ucs2':
6911 case 'ucs-2':
6912 case 'utf16le':
6913 case 'utf-16le':
6914 case 'raw':
6915 return true;
6916
6917 default:
6918 return false;
6919 }
6920};
6921
6922// helpers
6923
6924function coerce(length) {
6925 // Coerce length to a number (possibly NaN), round up
6926 // in case it's fractional (e.g. 123.456) then do a
6927 // double negate to coerce a NaN to 0. Easy, right?
6928 length = ~~Math.ceil(+length);
6929 return length < 0 ? 0 : length;
6930}
6931
6932function isArray(subject) {
6933 return (Array.isArray ||
6934 function(subject){
6935 return {}.toString.apply(subject) == '[object Array]'
6936 })
6937 (subject)
6938}
6939
6940function isArrayIsh(subject) {
6941 return isArray(subject) || Buffer.isBuffer(subject) ||
6942 subject && typeof subject === 'object' &&
6943 typeof subject.length === 'number';
6944}
6945
6946function toHex(n) {
6947 if (n < 16) return '0' + n.toString(16);
6948 return n.toString(16);
6949}
6950
6951function utf8ToBytes(str) {
6952 var byteArray = [];
6953 for (var i = 0; i < str.length; i++)
6954 if (str.charCodeAt(i) <= 0x7F)
6955 byteArray.push(str.charCodeAt(i));
6956 else {
6957 var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
6958 for (var j = 0; j < h.length; j++)
6959 byteArray.push(parseInt(h[j], 16));
6960 }
6961
6962 return byteArray;
6963}
6964
6965function asciiToBytes(str) {
6966 var byteArray = []
6967 for (var i = 0; i < str.length; i++ )
6968 // Node's code seems to be doing this and not & 0x7F..
6969 byteArray.push( str.charCodeAt(i) & 0xFF );
6970
6971 return byteArray;
6972}
6973
6974function base64ToBytes(str) {
6975 return require("base64-js").toByteArray(str);
6976}
6977
6978function blitBuffer(src, dst, offset, length) {
6979 var pos, i = 0;
6980 while (i < length) {
6981 if ((i+offset >= dst.length) || (i >= src.length))
6982 break;
6983
6984 dst[i + offset] = src[i];
6985 i++;
6986 }
6987 return i;
6988}
6989
6990function decodeUtf8Char(str) {
6991 try {
6992 return decodeURIComponent(str);
6993 } catch (err) {
6994 return String.fromCharCode(0xFFFD); // UTF 8 invalid char
6995 }
6996}
6997
6998// read/write bit-twiddling
6999
7000Buffer.prototype.readUInt8 = function(offset, noAssert) {
7001 var buffer = this;
7002
7003 if (!noAssert) {
7004 assert.ok(offset !== undefined && offset !== null,
7005 'missing offset');
7006
7007 assert.ok(offset < buffer.length,
7008 'Trying to read beyond buffer length');
7009 }
7010
7011 if (offset >= buffer.length) return;
7012
7013 return buffer[offset];
7014};
7015
7016function readUInt16(buffer, offset, isBigEndian, noAssert) {
7017 var val = 0;
7018
7019
7020 if (!noAssert) {
7021 assert.ok(typeof (isBigEndian) === 'boolean',
7022 'missing or invalid endian');
7023
7024 assert.ok(offset !== undefined && offset !== null,
7025 'missing offset');
7026
7027 assert.ok(offset + 1 < buffer.length,
7028 'Trying to read beyond buffer length');
7029 }
7030
7031 if (offset >= buffer.length) return 0;
7032
7033 if (isBigEndian) {
7034 val = buffer[offset] << 8;
7035 if (offset + 1 < buffer.length) {
7036 val |= buffer[offset + 1];
7037 }
7038 } else {
7039 val = buffer[offset];
7040 if (offset + 1 < buffer.length) {
7041 val |= buffer[offset + 1] << 8;
7042 }
7043 }
7044
7045 return val;
7046}
7047
7048Buffer.prototype.readUInt16LE = function(offset, noAssert) {
7049 return readUInt16(this, offset, false, noAssert);
7050};
7051
7052Buffer.prototype.readUInt16BE = function(offset, noAssert) {
7053 return readUInt16(this, offset, true, noAssert);
7054};
7055
7056function readUInt32(buffer, offset, isBigEndian, noAssert) {
7057 var val = 0;
7058
7059 if (!noAssert) {
7060 assert.ok(typeof (isBigEndian) === 'boolean',
7061 'missing or invalid endian');
7062
7063 assert.ok(offset !== undefined && offset !== null,
7064 'missing offset');
7065
7066 assert.ok(offset + 3 < buffer.length,
7067 'Trying to read beyond buffer length');
7068 }
7069
7070 if (offset >= buffer.length) return 0;
7071
7072 if (isBigEndian) {
7073 if (offset + 1 < buffer.length)
7074 val = buffer[offset + 1] << 16;
7075 if (offset + 2 < buffer.length)
7076 val |= buffer[offset + 2] << 8;
7077 if (offset + 3 < buffer.length)
7078 val |= buffer[offset + 3];
7079 val = val + (buffer[offset] << 24 >>> 0);
7080 } else {
7081 if (offset + 2 < buffer.length)
7082 val = buffer[offset + 2] << 16;
7083 if (offset + 1 < buffer.length)
7084 val |= buffer[offset + 1] << 8;
7085 val |= buffer[offset];
7086 if (offset + 3 < buffer.length)
7087 val = val + (buffer[offset + 3] << 24 >>> 0);
7088 }
7089
7090 return val;
7091}
7092
7093Buffer.prototype.readUInt32LE = function(offset, noAssert) {
7094 return readUInt32(this, offset, false, noAssert);
7095};
7096
7097Buffer.prototype.readUInt32BE = function(offset, noAssert) {
7098 return readUInt32(this, offset, true, noAssert);
7099};
7100
7101
7102/*
7103 * Signed integer types, yay team! A reminder on how two's complement actually
7104 * works. The first bit is the signed bit, i.e. tells us whether or not the
7105 * number should be positive or negative. If the two's complement value is
7106 * positive, then we're done, as it's equivalent to the unsigned representation.
7107 *
7108 * Now if the number is positive, you're pretty much done, you can just leverage
7109 * the unsigned translations and return those. Unfortunately, negative numbers
7110 * aren't quite that straightforward.
7111 *
7112 * At first glance, one might be inclined to use the traditional formula to
7113 * translate binary numbers between the positive and negative values in two's
7114 * complement. (Though it doesn't quite work for the most negative value)
7115 * Mainly:
7116 * - invert all the bits
7117 * - add one to the result
7118 *
7119 * Of course, this doesn't quite work in Javascript. Take for example the value
7120 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
7121 * course, Javascript will do the following:
7122 *
7123 * > ~0xff80
7124 * -65409
7125 *
7126 * Whoh there, Javascript, that's not quite right. But wait, according to
7127 * Javascript that's perfectly correct. When Javascript ends up seeing the
7128 * constant 0xff80, it has no notion that it is actually a signed number. It
7129 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
7130 * binary negation, it casts it into a signed value, (positive 0xff80). Then
7131 * when you perform binary negation on that, it turns it into a negative number.
7132 *
7133 * Instead, we're going to have to use the following general formula, that works
7134 * in a rather Javascript friendly way. I'm glad we don't support this kind of
7135 * weird numbering scheme in the kernel.
7136 *
7137 * (BIT-MAX - (unsigned)val + 1) * -1
7138 *
7139 * The astute observer, may think that this doesn't make sense for 8-bit numbers
7140 * (really it isn't necessary for them). However, when you get 16-bit numbers,
7141 * you do. Let's go back to our prior example and see how this will look:
7142 *
7143 * (0xffff - 0xff80 + 1) * -1
7144 * (0x007f + 1) * -1
7145 * (0x0080) * -1
7146 */
7147Buffer.prototype.readInt8 = function(offset, noAssert) {
7148 var buffer = this;
7149 var neg;
7150
7151 if (!noAssert) {
7152 assert.ok(offset !== undefined && offset !== null,
7153 'missing offset');
7154
7155 assert.ok(offset < buffer.length,
7156 'Trying to read beyond buffer length');
7157 }
7158
7159 if (offset >= buffer.length) return;
7160
7161 neg = buffer[offset] & 0x80;
7162 if (!neg) {
7163 return (buffer[offset]);
7164 }
7165
7166 return ((0xff - buffer[offset] + 1) * -1);
7167};
7168
7169function readInt16(buffer, offset, isBigEndian, noAssert) {
7170 var neg, val;
7171
7172 if (!noAssert) {
7173 assert.ok(typeof (isBigEndian) === 'boolean',
7174 'missing or invalid endian');
7175
7176 assert.ok(offset !== undefined && offset !== null,
7177 'missing offset');
7178
7179 assert.ok(offset + 1 < buffer.length,
7180 'Trying to read beyond buffer length');
7181 }
7182
7183 val = readUInt16(buffer, offset, isBigEndian, noAssert);
7184 neg = val & 0x8000;
7185 if (!neg) {
7186 return val;
7187 }
7188
7189 return (0xffff - val + 1) * -1;
7190}
7191
7192Buffer.prototype.readInt16LE = function(offset, noAssert) {
7193 return readInt16(this, offset, false, noAssert);
7194};
7195
7196Buffer.prototype.readInt16BE = function(offset, noAssert) {
7197 return readInt16(this, offset, true, noAssert);
7198};
7199
7200function readInt32(buffer, offset, isBigEndian, noAssert) {
7201 var neg, val;
7202
7203 if (!noAssert) {
7204 assert.ok(typeof (isBigEndian) === 'boolean',
7205 'missing or invalid endian');
7206
7207 assert.ok(offset !== undefined && offset !== null,
7208 'missing offset');
7209
7210 assert.ok(offset + 3 < buffer.length,
7211 'Trying to read beyond buffer length');
7212 }
7213
7214 val = readUInt32(buffer, offset, isBigEndian, noAssert);
7215 neg = val & 0x80000000;
7216 if (!neg) {
7217 return (val);
7218 }
7219
7220 return (0xffffffff - val + 1) * -1;
7221}
7222
7223Buffer.prototype.readInt32LE = function(offset, noAssert) {
7224 return readInt32(this, offset, false, noAssert);
7225};
7226
7227Buffer.prototype.readInt32BE = function(offset, noAssert) {
7228 return readInt32(this, offset, true, noAssert);
7229};
7230
7231function readFloat(buffer, offset, isBigEndian, noAssert) {
7232 if (!noAssert) {
7233 assert.ok(typeof (isBigEndian) === 'boolean',
7234 'missing or invalid endian');
7235
7236 assert.ok(offset + 3 < buffer.length,
7237 'Trying to read beyond buffer length');
7238 }
7239
7240 return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
7241 23, 4);
7242}
7243
7244Buffer.prototype.readFloatLE = function(offset, noAssert) {
7245 return readFloat(this, offset, false, noAssert);
7246};
7247
7248Buffer.prototype.readFloatBE = function(offset, noAssert) {
7249 return readFloat(this, offset, true, noAssert);
7250};
7251
7252function readDouble(buffer, offset, isBigEndian, noAssert) {
7253 if (!noAssert) {
7254 assert.ok(typeof (isBigEndian) === 'boolean',
7255 'missing or invalid endian');
7256
7257 assert.ok(offset + 7 < buffer.length,
7258 'Trying to read beyond buffer length');
7259 }
7260
7261 return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
7262 52, 8);
7263}
7264
7265Buffer.prototype.readDoubleLE = function(offset, noAssert) {
7266 return readDouble(this, offset, false, noAssert);
7267};
7268
7269Buffer.prototype.readDoubleBE = function(offset, noAssert) {
7270 return readDouble(this, offset, true, noAssert);
7271};
7272
7273
7274/*
7275 * We have to make sure that the value is a valid integer. This means that it is
7276 * non-negative. It has no fractional component and that it does not exceed the
7277 * maximum allowed value.
7278 *
7279 * value The number to check for validity
7280 *
7281 * max The maximum value
7282 */
7283function verifuint(value, max) {
7284 assert.ok(typeof (value) == 'number',
7285 'cannot write a non-number as a number');
7286
7287 assert.ok(value >= 0,
7288 'specified a negative value for writing an unsigned value');
7289
7290 assert.ok(value <= max, 'value is larger than maximum value for type');
7291
7292 assert.ok(Math.floor(value) === value, 'value has a fractional component');
7293}
7294
7295Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
7296 var buffer = this;
7297
7298 if (!noAssert) {
7299 assert.ok(value !== undefined && value !== null,
7300 'missing value');
7301
7302 assert.ok(offset !== undefined && offset !== null,
7303 'missing offset');
7304
7305 assert.ok(offset < buffer.length,
7306 'trying to write beyond buffer length');
7307
7308 verifuint(value, 0xff);
7309 }
7310
7311 if (offset < buffer.length) {
7312 buffer[offset] = value;
7313 }
7314};
7315
7316function writeUInt16(buffer, value, offset, isBigEndian, noAssert) {
7317 if (!noAssert) {
7318 assert.ok(value !== undefined && value !== null,
7319 'missing value');
7320
7321 assert.ok(typeof (isBigEndian) === 'boolean',
7322 'missing or invalid endian');
7323
7324 assert.ok(offset !== undefined && offset !== null,
7325 'missing offset');
7326
7327 assert.ok(offset + 1 < buffer.length,
7328 'trying to write beyond buffer length');
7329
7330 verifuint(value, 0xffff);
7331 }
7332
7333 for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) {
7334 buffer[offset + i] =
7335 (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>>
7336 (isBigEndian ? 1 - i : i) * 8;
7337 }
7338
7339}
7340
7341Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
7342 writeUInt16(this, value, offset, false, noAssert);
7343};
7344
7345Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
7346 writeUInt16(this, value, offset, true, noAssert);
7347};
7348
7349function writeUInt32(buffer, value, offset, isBigEndian, noAssert) {
7350 if (!noAssert) {
7351 assert.ok(value !== undefined && value !== null,
7352 'missing value');
7353
7354 assert.ok(typeof (isBigEndian) === 'boolean',
7355 'missing or invalid endian');
7356
7357 assert.ok(offset !== undefined && offset !== null,
7358 'missing offset');
7359
7360 assert.ok(offset + 3 < buffer.length,
7361 'trying to write beyond buffer length');
7362
7363 verifuint(value, 0xffffffff);
7364 }
7365
7366 for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) {
7367 buffer[offset + i] =
7368 (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff;
7369 }
7370}
7371
7372Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
7373 writeUInt32(this, value, offset, false, noAssert);
7374};
7375
7376Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
7377 writeUInt32(this, value, offset, true, noAssert);
7378};
7379
7380
7381/*
7382 * We now move onto our friends in the signed number category. Unlike unsigned
7383 * numbers, we're going to have to worry a bit more about how we put values into
7384 * arrays. Since we are only worrying about signed 32-bit values, we're in
7385 * slightly better shape. Unfortunately, we really can't do our favorite binary
7386 * & in this system. It really seems to do the wrong thing. For example:
7387 *
7388 * > -32 & 0xff
7389 * 224
7390 *
7391 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
7392 * this aren't treated as a signed number. Ultimately a bad thing.
7393 *
7394 * What we're going to want to do is basically create the unsigned equivalent of
7395 * our representation and pass that off to the wuint* functions. To do that
7396 * we're going to do the following:
7397 *
7398 * - if the value is positive
7399 * we can pass it directly off to the equivalent wuint
7400 * - if the value is negative
7401 * we do the following computation:
7402 * mb + val + 1, where
7403 * mb is the maximum unsigned value in that byte size
7404 * val is the Javascript negative integer
7405 *
7406 *
7407 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
7408 * you do out the computations:
7409 *
7410 * 0xffff - 128 + 1
7411 * 0xffff - 127
7412 * 0xff80
7413 *
7414 * You can then encode this value as the signed version. This is really rather
7415 * hacky, but it should work and get the job done which is our goal here.
7416 */
7417
7418/*
7419 * A series of checks to make sure we actually have a signed 32-bit number
7420 */
7421function verifsint(value, max, min) {
7422 assert.ok(typeof (value) == 'number',
7423 'cannot write a non-number as a number');
7424
7425 assert.ok(value <= max, 'value larger than maximum allowed value');
7426
7427 assert.ok(value >= min, 'value smaller than minimum allowed value');
7428
7429 assert.ok(Math.floor(value) === value, 'value has a fractional component');
7430}
7431
7432function verifIEEE754(value, max, min) {
7433 assert.ok(typeof (value) == 'number',
7434 'cannot write a non-number as a number');
7435
7436 assert.ok(value <= max, 'value larger than maximum allowed value');
7437
7438 assert.ok(value >= min, 'value smaller than minimum allowed value');
7439}
7440
7441Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
7442 var buffer = this;
7443
7444 if (!noAssert) {
7445 assert.ok(value !== undefined && value !== null,
7446 'missing value');
7447
7448 assert.ok(offset !== undefined && offset !== null,
7449 'missing offset');
7450
7451 assert.ok(offset < buffer.length,
7452 'Trying to write beyond buffer length');
7453
7454 verifsint(value, 0x7f, -0x80);
7455 }
7456
7457 if (value >= 0) {
7458 buffer.writeUInt8(value, offset, noAssert);
7459 } else {
7460 buffer.writeUInt8(0xff + value + 1, offset, noAssert);
7461 }
7462};
7463
7464function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
7465 if (!noAssert) {
7466 assert.ok(value !== undefined && value !== null,
7467 'missing value');
7468
7469 assert.ok(typeof (isBigEndian) === 'boolean',
7470 'missing or invalid endian');
7471
7472 assert.ok(offset !== undefined && offset !== null,
7473 'missing offset');
7474
7475 assert.ok(offset + 1 < buffer.length,
7476 'Trying to write beyond buffer length');
7477
7478 verifsint(value, 0x7fff, -0x8000);
7479 }
7480
7481 if (value >= 0) {
7482 writeUInt16(buffer, value, offset, isBigEndian, noAssert);
7483 } else {
7484 writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);
7485 }
7486}
7487
7488Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
7489 writeInt16(this, value, offset, false, noAssert);
7490};
7491
7492Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
7493 writeInt16(this, value, offset, true, noAssert);
7494};
7495
7496function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
7497 if (!noAssert) {
7498 assert.ok(value !== undefined && value !== null,
7499 'missing value');
7500
7501 assert.ok(typeof (isBigEndian) === 'boolean',
7502 'missing or invalid endian');
7503
7504 assert.ok(offset !== undefined && offset !== null,
7505 'missing offset');
7506
7507 assert.ok(offset + 3 < buffer.length,
7508 'Trying to write beyond buffer length');
7509
7510 verifsint(value, 0x7fffffff, -0x80000000);
7511 }
7512
7513 if (value >= 0) {
7514 writeUInt32(buffer, value, offset, isBigEndian, noAssert);
7515 } else {
7516 writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);
7517 }
7518}
7519
7520Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
7521 writeInt32(this, value, offset, false, noAssert);
7522};
7523
7524Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
7525 writeInt32(this, value, offset, true, noAssert);
7526};
7527
7528function writeFloat(buffer, value, offset, isBigEndian, noAssert) {
7529 if (!noAssert) {
7530 assert.ok(value !== undefined && value !== null,
7531 'missing value');
7532
7533 assert.ok(typeof (isBigEndian) === 'boolean',
7534 'missing or invalid endian');
7535
7536 assert.ok(offset !== undefined && offset !== null,
7537 'missing offset');
7538
7539 assert.ok(offset + 3 < buffer.length,
7540 'Trying to write beyond buffer length');
7541
7542 verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);
7543 }
7544
7545 require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
7546 23, 4);
7547}
7548
7549Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
7550 writeFloat(this, value, offset, false, noAssert);
7551};
7552
7553Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
7554 writeFloat(this, value, offset, true, noAssert);
7555};
7556
7557function writeDouble(buffer, value, offset, isBigEndian, noAssert) {
7558 if (!noAssert) {
7559 assert.ok(value !== undefined && value !== null,
7560 'missing value');
7561
7562 assert.ok(typeof (isBigEndian) === 'boolean',
7563 'missing or invalid endian');
7564
7565 assert.ok(offset !== undefined && offset !== null,
7566 'missing offset');
7567
7568 assert.ok(offset + 7 < buffer.length,
7569 'Trying to write beyond buffer length');
7570
7571 verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);
7572 }
7573
7574 require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
7575 52, 8);
7576}
7577
7578Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
7579 writeDouble(this, value, offset, false, noAssert);
7580};
7581
7582Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
7583 writeDouble(this, value, offset, true, noAssert);
7584};
7585}, {"assert":30,"base64-js":31,"./buffer_ieee754":32}],30: [function (exports, require, module, global) {// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
7586//
7587// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
7588//
7589// Originally from narwhal.js (http://narwhaljs.org)
7590// Copyright (c) 2009 Thomas Robinson <280north.com>
7591//
7592// Permission is hereby granted, free of charge, to any person obtaining a copy
7593// of this software and associated documentation files (the 'Software'), to
7594// deal in the Software without restriction, including without limitation the
7595// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7596// sell copies of the Software, and to permit persons to whom the Software is
7597// furnished to do so, subject to the following conditions:
7598//
7599// The above copyright notice and this permission notice shall be included in
7600// all copies or substantial portions of the Software.
7601//
7602// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
7603// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
7604// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7605// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
7606// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
7607// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7608
7609// when used in node, this will actually load the util module we depend on
7610// versus loading the builtin util module as happens otherwise
7611// this is a bug in node module loading as far as I am concerned
7612var util = require('util/');
7613
7614var pSlice = Array.prototype.slice;
7615var hasOwn = Object.prototype.hasOwnProperty;
7616
7617// 1. The assert module provides functions that throw
7618// AssertionError's when particular conditions are not met. The
7619// assert module must conform to the following interface.
7620
7621var assert = module.exports = ok;
7622
7623// 2. The AssertionError is defined in assert.
7624// new assert.AssertionError({ message: message,
7625// actual: actual,
7626// expected: expected })
7627
7628assert.AssertionError = function AssertionError(options) {
7629 this.name = 'AssertionError';
7630 this.actual = options.actual;
7631 this.expected = options.expected;
7632 this.operator = options.operator;
7633 if (options.message) {
7634 this.message = options.message;
7635 this.generatedMessage = false;
7636 } else {
7637 this.message = getMessage(this);
7638 this.generatedMessage = true;
7639 }
7640 var stackStartFunction = options.stackStartFunction || fail;
7641
7642 if (Error.captureStackTrace) {
7643 Error.captureStackTrace(this, stackStartFunction);
7644 }
7645 else {
7646 // non v8 browsers so we can have a stacktrace
7647 var err = new Error();
7648 if (err.stack) {
7649 var out = err.stack;
7650
7651 // try to strip useless frames
7652 var fn_name = stackStartFunction.name;
7653 var idx = out.indexOf('\n' + fn_name);
7654 if (idx >= 0) {
7655 // once we have located the function frame
7656 // we need to strip out everything before it (and its line)
7657 var next_line = out.indexOf('\n', idx + 1);
7658 out = out.substring(next_line + 1);
7659 }
7660
7661 this.stack = out;
7662 }
7663 }
7664};
7665
7666// assert.AssertionError instanceof Error
7667util.inherits(assert.AssertionError, Error);
7668
7669function replacer(key, value) {
7670 if (util.isUndefined(value)) {
7671 return '' + value;
7672 }
7673 if (util.isNumber(value) && !isFinite(value)) {
7674 return value.toString();
7675 }
7676 if (util.isFunction(value) || util.isRegExp(value)) {
7677 return value.toString();
7678 }
7679 return value;
7680}
7681
7682function truncate(s, n) {
7683 if (util.isString(s)) {
7684 return s.length < n ? s : s.slice(0, n);
7685 } else {
7686 return s;
7687 }
7688}
7689
7690function getMessage(self) {
7691 return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
7692 self.operator + ' ' +
7693 truncate(JSON.stringify(self.expected, replacer), 128);
7694}
7695
7696// At present only the three keys mentioned above are used and
7697// understood by the spec. Implementations or sub modules can pass
7698// other keys to the AssertionError's constructor - they will be
7699// ignored.
7700
7701// 3. All of the following functions must throw an AssertionError
7702// when a corresponding condition is not met, with a message that
7703// may be undefined if not provided. All assertion methods provide
7704// both the actual and expected values to the assertion error for
7705// display purposes.
7706
7707function fail(actual, expected, message, operator, stackStartFunction) {
7708 throw new assert.AssertionError({
7709 message: message,
7710 actual: actual,
7711 expected: expected,
7712 operator: operator,
7713 stackStartFunction: stackStartFunction
7714 });
7715}
7716
7717// EXTENSION! allows for well behaved errors defined elsewhere.
7718assert.fail = fail;
7719
7720// 4. Pure assertion tests whether a value is truthy, as determined
7721// by !!guard.
7722// assert.ok(guard, message_opt);
7723// This statement is equivalent to assert.equal(true, !!guard,
7724// message_opt);. To test strictly for the value true, use
7725// assert.strictEqual(true, guard, message_opt);.
7726
7727function ok(value, message) {
7728 if (!value) fail(value, true, message, '==', assert.ok);
7729}
7730assert.ok = ok;
7731
7732// 5. The equality assertion tests shallow, coercive equality with
7733// ==.
7734// assert.equal(actual, expected, message_opt);
7735
7736assert.equal = function equal(actual, expected, message) {
7737 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
7738};
7739
7740// 6. The non-equality assertion tests for whether two objects are not equal
7741// with != assert.notEqual(actual, expected, message_opt);
7742
7743assert.notEqual = function notEqual(actual, expected, message) {
7744 if (actual == expected) {
7745 fail(actual, expected, message, '!=', assert.notEqual);
7746 }
7747};
7748
7749// 7. The equivalence assertion tests a deep equality relation.
7750// assert.deepEqual(actual, expected, message_opt);
7751
7752assert.deepEqual = function deepEqual(actual, expected, message) {
7753 if (!_deepEqual(actual, expected)) {
7754 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
7755 }
7756};
7757
7758function _deepEqual(actual, expected) {
7759 // 7.1. All identical values are equivalent, as determined by ===.
7760 if (actual === expected) {
7761 return true;
7762
7763 } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
7764 if (actual.length != expected.length) return false;
7765
7766 for (var i = 0; i < actual.length; i++) {
7767 if (actual[i] !== expected[i]) return false;
7768 }
7769
7770 return true;
7771
7772 // 7.2. If the expected value is a Date object, the actual value is
7773 // equivalent if it is also a Date object that refers to the same time.
7774 } else if (util.isDate(actual) && util.isDate(expected)) {
7775 return actual.getTime() === expected.getTime();
7776
7777 // 7.3 If the expected value is a RegExp object, the actual value is
7778 // equivalent if it is also a RegExp object with the same source and
7779 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
7780 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
7781 return actual.source === expected.source &&
7782 actual.global === expected.global &&
7783 actual.multiline === expected.multiline &&
7784 actual.lastIndex === expected.lastIndex &&
7785 actual.ignoreCase === expected.ignoreCase;
7786
7787 // 7.4. Other pairs that do not both pass typeof value == 'object',
7788 // equivalence is determined by ==.
7789 } else if (!util.isObject(actual) && !util.isObject(expected)) {
7790 return actual == expected;
7791
7792 // 7.5 For all other Object pairs, including Array objects, equivalence is
7793 // determined by having the same number of owned properties (as verified
7794 // with Object.prototype.hasOwnProperty.call), the same set of keys
7795 // (although not necessarily the same order), equivalent values for every
7796 // corresponding key, and an identical 'prototype' property. Note: this
7797 // accounts for both named and indexed properties on Arrays.
7798 } else {
7799 return objEquiv(actual, expected);
7800 }
7801}
7802
7803function isArguments(object) {
7804 return Object.prototype.toString.call(object) == '[object Arguments]';
7805}
7806
7807function objEquiv(a, b) {
7808 if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
7809 return false;
7810 // an identical 'prototype' property.
7811 if (a.prototype !== b.prototype) return false;
7812 // if one is a primitive, the other must be same
7813 if (util.isPrimitive(a) || util.isPrimitive(b)) {
7814 return a === b;
7815 }
7816 var aIsArgs = isArguments(a),
7817 bIsArgs = isArguments(b);
7818 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
7819 return false;
7820 if (aIsArgs) {
7821 a = pSlice.call(a);
7822 b = pSlice.call(b);
7823 return _deepEqual(a, b);
7824 }
7825 var ka = objectKeys(a),
7826 kb = objectKeys(b),
7827 key, i;
7828 // having the same number of owned properties (keys incorporates
7829 // hasOwnProperty)
7830 if (ka.length != kb.length)
7831 return false;
7832 //the same set of keys (although not necessarily the same order),
7833 ka.sort();
7834 kb.sort();
7835 //~~~cheap key test
7836 for (i = ka.length - 1; i >= 0; i--) {
7837 if (ka[i] != kb[i])
7838 return false;
7839 }
7840 //equivalent values for every corresponding key, and
7841 //~~~possibly expensive deep test
7842 for (i = ka.length - 1; i >= 0; i--) {
7843 key = ka[i];
7844 if (!_deepEqual(a[key], b[key])) return false;
7845 }
7846 return true;
7847}
7848
7849// 8. The non-equivalence assertion tests for any deep inequality.
7850// assert.notDeepEqual(actual, expected, message_opt);
7851
7852assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
7853 if (_deepEqual(actual, expected)) {
7854 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
7855 }
7856};
7857
7858// 9. The strict equality assertion tests strict equality, as determined by ===.
7859// assert.strictEqual(actual, expected, message_opt);
7860
7861assert.strictEqual = function strictEqual(actual, expected, message) {
7862 if (actual !== expected) {
7863 fail(actual, expected, message, '===', assert.strictEqual);
7864 }
7865};
7866
7867// 10. The strict non-equality assertion tests for strict inequality, as
7868// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
7869
7870assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
7871 if (actual === expected) {
7872 fail(actual, expected, message, '!==', assert.notStrictEqual);
7873 }
7874};
7875
7876function expectedException(actual, expected) {
7877 if (!actual || !expected) {
7878 return false;
7879 }
7880
7881 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
7882 return expected.test(actual);
7883 } else if (actual instanceof expected) {
7884 return true;
7885 } else if (expected.call({}, actual) === true) {
7886 return true;
7887 }
7888
7889 return false;
7890}
7891
7892function _throws(shouldThrow, block, expected, message) {
7893 var actual;
7894
7895 if (util.isString(expected)) {
7896 message = expected;
7897 expected = null;
7898 }
7899
7900 try {
7901 block();
7902 } catch (e) {
7903 actual = e;
7904 }
7905
7906 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
7907 (message ? ' ' + message : '.');
7908
7909 if (shouldThrow && !actual) {
7910 fail(actual, expected, 'Missing expected exception' + message);
7911 }
7912
7913 if (!shouldThrow && expectedException(actual, expected)) {
7914 fail(actual, expected, 'Got unwanted exception' + message);
7915 }
7916
7917 if ((shouldThrow && actual && expected &&
7918 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
7919 throw actual;
7920 }
7921}
7922
7923// 11. Expected to throw an error:
7924// assert.throws(block, Error_opt, message_opt);
7925
7926assert.throws = function(block, /*optional*/error, /*optional*/message) {
7927 _throws.apply(this, [true].concat(pSlice.call(arguments)));
7928};
7929
7930// EXTENSION! This is annoying to write outside this module.
7931assert.doesNotThrow = function(block, /*optional*/message) {
7932 _throws.apply(this, [false].concat(pSlice.call(arguments)));
7933};
7934
7935assert.ifError = function(err) { if (err) {throw err;}};
7936
7937var objectKeys = Object.keys || function (obj) {
7938 var keys = [];
7939 for (var key in obj) {
7940 if (hasOwn.call(obj, key)) keys.push(key);
7941 }
7942 return keys;
7943};
7944}, {"util/":23}],31: [function (exports, require, module, global) {var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
7945
7946;(function (exports) {
7947 'use strict';
7948
7949 var Arr = (typeof Uint8Array !== 'undefined')
7950 ? Uint8Array
7951 : Array
7952
7953 var PLUS = '+'.charCodeAt(0)
7954 var SLASH = '/'.charCodeAt(0)
7955 var NUMBER = '0'.charCodeAt(0)
7956 var LOWER = 'a'.charCodeAt(0)
7957 var UPPER = 'A'.charCodeAt(0)
7958 var PLUS_URL_SAFE = '-'.charCodeAt(0)
7959 var SLASH_URL_SAFE = '_'.charCodeAt(0)
7960
7961 function decode (elt) {
7962 var code = elt.charCodeAt(0)
7963 if (code === PLUS ||
7964 code === PLUS_URL_SAFE)
7965 return 62 // '+'
7966 if (code === SLASH ||
7967 code === SLASH_URL_SAFE)
7968 return 63 // '/'
7969 if (code < NUMBER)
7970 return -1 //no match
7971 if (code < NUMBER + 10)
7972 return code - NUMBER + 26 + 26
7973 if (code < UPPER + 26)
7974 return code - UPPER
7975 if (code < LOWER + 26)
7976 return code - LOWER + 26
7977 }
7978
7979 function b64ToByteArray (b64) {
7980 var i, j, l, tmp, placeHolders, arr
7981
7982 if (b64.length % 4 > 0) {
7983 throw new Error('Invalid string. Length must be a multiple of 4')
7984 }
7985
7986 // the number of equal signs (place holders)
7987 // if there are two placeholders, than the two characters before it
7988 // represent one byte
7989 // if there is only one, then the three characters before it represent 2 bytes
7990 // this is just a cheap hack to not do indexOf twice
7991 var len = b64.length
7992 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
7993
7994 // base64 is 4/3 + up to two characters of the original data
7995 arr = new Arr(b64.length * 3 / 4 - placeHolders)
7996
7997 // if there are placeholders, only get up to the last complete 4 chars
7998 l = placeHolders > 0 ? b64.length - 4 : b64.length
7999
8000 var L = 0
8001
8002 function push (v) {
8003 arr[L++] = v
8004 }
8005
8006 for (i = 0, j = 0; i < l; i += 4, j += 3) {
8007 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
8008 push((tmp & 0xFF0000) >> 16)
8009 push((tmp & 0xFF00) >> 8)
8010 push(tmp & 0xFF)
8011 }
8012
8013 if (placeHolders === 2) {
8014 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
8015 push(tmp & 0xFF)
8016 } else if (placeHolders === 1) {
8017 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
8018 push((tmp >> 8) & 0xFF)
8019 push(tmp & 0xFF)
8020 }
8021
8022 return arr
8023 }
8024
8025 function uint8ToBase64 (uint8) {
8026 var i,
8027 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
8028 output = "",
8029 temp, length
8030
8031 function encode (num) {
8032 return lookup.charAt(num)
8033 }
8034
8035 function tripletToBase64 (num) {
8036 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
8037 }
8038
8039 // go through the array every three bytes, we'll deal with trailing stuff later
8040 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
8041 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
8042 output += tripletToBase64(temp)
8043 }
8044
8045 // pad the end with zeros, but make sure to not forget the extra bytes
8046 switch (extraBytes) {
8047 case 1:
8048 temp = uint8[uint8.length - 1]
8049 output += encode(temp >> 2)
8050 output += encode((temp << 4) & 0x3F)
8051 output += '=='
8052 break
8053 case 2:
8054 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
8055 output += encode(temp >> 10)
8056 output += encode((temp >> 4) & 0x3F)
8057 output += encode((temp << 2) & 0x3F)
8058 output += '='
8059 break
8060 }
8061
8062 return output
8063 }
8064
8065 exports.toByteArray = b64ToByteArray
8066 exports.fromByteArray = uint8ToBase64
8067}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
8068}, {}],32: [function (exports, require, module, global) {exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {
8069 var e, m,
8070 eLen = nBytes * 8 - mLen - 1,
8071 eMax = (1 << eLen) - 1,
8072 eBias = eMax >> 1,
8073 nBits = -7,
8074 i = isBE ? 0 : (nBytes - 1),
8075 d = isBE ? 1 : -1,
8076 s = buffer[offset + i];
8077
8078 i += d;
8079
8080 e = s & ((1 << (-nBits)) - 1);
8081 s >>= (-nBits);
8082 nBits += eLen;
8083 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
8084
8085 m = e & ((1 << (-nBits)) - 1);
8086 e >>= (-nBits);
8087 nBits += mLen;
8088 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
8089
8090 if (e === 0) {
8091 e = 1 - eBias;
8092 } else if (e === eMax) {
8093 return m ? NaN : ((s ? -1 : 1) * Infinity);
8094 } else {
8095 m = m + Math.pow(2, mLen);
8096 e = e - eBias;
8097 }
8098 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
8099};
8100
8101exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {
8102 var e, m, c,
8103 eLen = nBytes * 8 - mLen - 1,
8104 eMax = (1 << eLen) - 1,
8105 eBias = eMax >> 1,
8106 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
8107 i = isBE ? (nBytes - 1) : 0,
8108 d = isBE ? -1 : 1,
8109 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
8110
8111 value = Math.abs(value);
8112
8113 if (isNaN(value) || value === Infinity) {
8114 m = isNaN(value) ? 1 : 0;
8115 e = eMax;
8116 } else {
8117 e = Math.floor(Math.log(value) / Math.LN2);
8118 if (value * (c = Math.pow(2, -e)) < 1) {
8119 e--;
8120 c *= 2;
8121 }
8122 if (e + eBias >= 1) {
8123 value += rt / c;
8124 } else {
8125 value += rt * Math.pow(2, 1 - eBias);
8126 }
8127 if (value * c >= 2) {
8128 e++;
8129 c /= 2;
8130 }
8131
8132 if (e + eBias >= eMax) {
8133 m = 0;
8134 e = eMax;
8135 } else if (e + eBias >= 1) {
8136 m = (value * c - 1) * Math.pow(2, mLen);
8137 e = e + eBias;
8138 } else {
8139 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
8140 e = 0;
8141 }
8142 }
8143
8144 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
8145
8146 e = (e << mLen) | m;
8147 eLen += mLen;
8148 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
8149
8150 buffer[offset + i - d] |= s * 128;
8151};
8152}, {}],33: [function (exports, require, module, global) {var Keys = require("object-keys")
8153var hasKeys = require("./has-keys")
8154
8155module.exports = extend
8156
8157function extend() {
8158 var target = {}
8159
8160 for (var i = 0; i < arguments.length; i++) {
8161 var source = arguments[i]
8162
8163 if (!hasKeys(source)) {
8164 continue
8165 }
8166
8167 var keys = Keys(source)
8168
8169 for (var j = 0; j < keys.length; j++) {
8170 var name = keys[j]
8171 target[name] = source[name]
8172 }
8173 }
8174
8175 return target
8176}
8177}, {"object-keys":34,"./has-keys":38}],34: [function (exports, require, module, global) {module.exports = Object.keys || require('./shim');
8178
8179}, {"./shim":35}],35: [function (exports, require, module, global) {(function () {
8180 "use strict";
8181
8182 // modified from https://github.com/kriskowal/es5-shim
8183 var has = Object.prototype.hasOwnProperty,
8184 toString = Object.prototype.toString,
8185 forEach = require('./foreach'),
8186 isArgs = require('./isArguments'),
8187 hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
8188 hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
8189 dontEnums = [
8190 "toString",
8191 "toLocaleString",
8192 "valueOf",
8193 "hasOwnProperty",
8194 "isPrototypeOf",
8195 "propertyIsEnumerable",
8196 "constructor"
8197 ],
8198 keysShim;
8199
8200 keysShim = function keys(object) {
8201 var isObject = object !== null && typeof object === 'object',
8202 isFunction = toString.call(object) === '[object Function]',
8203 isArguments = isArgs(object),
8204 theKeys = [];
8205
8206 if (!isObject && !isFunction && !isArguments) {
8207 throw new TypeError("Object.keys called on a non-object");
8208 }
8209
8210 if (isArguments) {
8211 forEach(object, function (value) {
8212 theKeys.push(value);
8213 });
8214 } else {
8215 var name,
8216 skipProto = hasProtoEnumBug && isFunction;
8217
8218 for (name in object) {
8219 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
8220 theKeys.push(name);
8221 }
8222 }
8223 }
8224
8225 if (hasDontEnumBug) {
8226 var ctor = object.constructor,
8227 skipConstructor = ctor && ctor.prototype === object;
8228
8229 forEach(dontEnums, function (dontEnum) {
8230 if (!(skipConstructor && dontEnum === 'constructor') && has.call(object, dontEnum)) {
8231 theKeys.push(dontEnum);
8232 }
8233 });
8234 }
8235 return theKeys;
8236 };
8237
8238 module.exports = keysShim;
8239}());
8240
8241}, {"./foreach":36,"./isArguments":37}],36: [function (exports, require, module, global) {var hasOwn = Object.prototype.hasOwnProperty;
8242var toString = Object.prototype.toString;
8243
8244var isFunction = function (fn) {
8245 var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]';
8246 if (!isFunc && typeof window !== 'undefined') {
8247 isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt;
8248 }
8249 return isFunc;
8250};
8251
8252module.exports = function forEach(obj, fn) {
8253 if (!isFunction(fn)) {
8254 throw new TypeError('iterator must be a function');
8255 }
8256 var i, k,
8257 isString = typeof obj === 'string',
8258 l = obj.length,
8259 context = arguments.length > 2 ? arguments[2] : null;
8260 if (l === +l) {
8261 for (i = 0; i < l; i++) {
8262 if (context === null) {
8263 fn(isString ? obj.charAt(i) : obj[i], i, obj);
8264 } else {
8265 fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj);
8266 }
8267 }
8268 } else {
8269 for (k in obj) {
8270 if (hasOwn.call(obj, k)) {
8271 if (context === null) {
8272 fn(obj[k], k, obj);
8273 } else {
8274 fn.call(context, obj[k], k, obj);
8275 }
8276 }
8277 }
8278 }
8279};
8280
8281}, {}],37: [function (exports, require, module, global) {var toString = Object.prototype.toString;
8282
8283module.exports = function isArguments(value) {
8284 var str = toString.call(value);
8285 var isArguments = str === '[object Arguments]';
8286 if (!isArguments) {
8287 isArguments = str !== '[object Array]'
8288 && value !== null
8289 && typeof value === 'object'
8290 && typeof value.length === 'number'
8291 && value.length >= 0
8292 && toString.call(value.callee) === '[object Function]';
8293 }
8294 return isArguments;
8295};
8296
8297}, {}],38: [function (exports, require, module, global) {module.exports = hasKeys
8298
8299function hasKeys(source) {
8300 return source !== null &&
8301 (typeof source === "object" ||
8302 typeof source === "function")
8303}
8304}, {}],39: [function (exports, require, module, global) {/**
8305 * Convert a typed array to a Buffer without a copy
8306 *
8307 * Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
8308 * License: MIT
8309 *
8310 * `npm install typedarray-to-buffer`
8311 */
8312
8313module.exports = function (arr) {
8314 if (typeof Buffer._augment === 'function' && Buffer.TYPED_ARRAY_SUPPORT) {
8315 // If `Buffer` is from the `buffer` module and this browser supports typed arrays,
8316 // then augment it with all the `Buffer` methods.
8317 return Buffer._augment(arr)
8318 } else {
8319 // Otherwise, fallback to creating a `Buffer` with a copy.
8320 return new Buffer(arr)
8321 }
8322}
8323}, {}],40: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
8324 * See list at <https://github.com/rvagg/node-levelup#contributing>
8325 * MIT License
8326 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
8327 */
8328
8329var EventEmitter = require('events').EventEmitter
8330 , inherits = require('util').inherits
8331 , extend = require('xtend')
8332 , prr = require('prr')
8333 , DeferredLevelDOWN = require('deferred-leveldown')
8334
8335 , WriteError = require('./errors').WriteError
8336 , ReadError = require('./errors').ReadError
8337 , NotFoundError = require('./errors').NotFoundError
8338 , OpenError = require('./errors').OpenError
8339 , EncodingError = require('./errors').EncodingError
8340 , InitializationError = require('./errors').InitializationError
8341
8342 , ReadStream = require('./read-stream')
8343 , WriteStream = require('./write-stream')
8344 , util = require('./util')
8345 , Batch = require('./batch')
8346
8347 , getOptions = util.getOptions
8348 , defaultOptions = util.defaultOptions
8349 , getLevelDOWN = util.getLevelDOWN
8350 , dispatchError = util.dispatchError
8351
8352function getCallback (options, callback) {
8353 return typeof options == 'function' ? options : callback
8354}
8355
8356// Possible LevelUP#_status values:
8357// - 'new' - newly created, not opened or closed
8358// - 'opening' - waiting for the database to be opened, post open()
8359// - 'open' - successfully opened the database, available for use
8360// - 'closing' - waiting for the database to be closed, post close()
8361// - 'closed' - database has been successfully closed, should not be
8362// used except for another open() operation
8363
8364function LevelUP (location, options, callback) {
8365 if (!(this instanceof LevelUP))
8366 return new LevelUP(location, options, callback)
8367
8368 var error
8369
8370 EventEmitter.call(this)
8371 this.setMaxListeners(Infinity)
8372
8373 if (typeof location == 'function') {
8374 options = typeof options == 'object' ? options : {}
8375 options.db = location
8376 location = null
8377 } else if (typeof location == 'object' && typeof location.db == 'function') {
8378 options = location
8379 location = null
8380 }
8381
8382 if (typeof options == 'function') {
8383 callback = options
8384 options = {}
8385 }
8386
8387 if ((!options || typeof options.db != 'function') && typeof location != 'string') {
8388 error = new InitializationError(
8389 'Must provide a location for the database')
8390 if (callback) {
8391 return process.nextTick(function () {
8392 callback(error)
8393 })
8394 }
8395 throw error
8396 }
8397
8398 options = getOptions(this, options)
8399 this.options = extend(defaultOptions, options)
8400 this._status = 'new'
8401 // set this.location as enumerable but not configurable or writable
8402 prr(this, 'location', location, 'e')
8403
8404 this.open(callback)
8405}
8406
8407inherits(LevelUP, EventEmitter)
8408
8409LevelUP.prototype.open = function (callback) {
8410 var self = this
8411 , dbFactory
8412 , db
8413
8414 if (this.isOpen()) {
8415 if (callback)
8416 process.nextTick(function () { callback(null, self) })
8417 return this
8418 }
8419
8420 if (this._isOpening()) {
8421 return callback && this.once(
8422 'open'
8423 , function () { callback(null, self) }
8424 )
8425 }
8426
8427 this.emit('opening')
8428
8429 this._status = 'opening'
8430 this.db = new DeferredLevelDOWN(this.location)
8431 dbFactory = this.options.db || getLevelDOWN()
8432 db = dbFactory(this.location)
8433
8434 db.open(this.options, function (err) {
8435 if (err) {
8436 return dispatchError(self, new OpenError(err), callback)
8437 } else {
8438 self.db.setDb(db)
8439 self.db = db
8440 self._status = 'open'
8441 if (callback)
8442 callback(null, self)
8443 self.emit('open')
8444 self.emit('ready')
8445 }
8446 })
8447}
8448
8449LevelUP.prototype.close = function (callback) {
8450 var self = this
8451
8452 if (this.isOpen()) {
8453 this._status = 'closing'
8454 this.db.close(function () {
8455 self._status = 'closed'
8456 self.emit('closed')
8457 if (callback)
8458 callback.apply(null, arguments)
8459 })
8460 this.emit('closing')
8461 this.db = null
8462 } else if (this._status == 'closed' && callback) {
8463 return process.nextTick(callback)
8464 } else if (this._status == 'closing' && callback) {
8465 this.once('closed', callback)
8466 } else if (this._isOpening()) {
8467 this.once('open', function () {
8468 self.close(callback)
8469 })
8470 }
8471}
8472
8473LevelUP.prototype.isOpen = function () {
8474 return this._status == 'open'
8475}
8476
8477LevelUP.prototype._isOpening = function () {
8478 return this._status == 'opening'
8479}
8480
8481LevelUP.prototype.isClosed = function () {
8482 return (/^clos/).test(this._status)
8483}
8484
8485LevelUP.prototype.get = function (key_, options, callback) {
8486 var self = this
8487 , key
8488
8489 callback = getCallback(options, callback)
8490
8491 if (typeof callback != 'function') {
8492 return dispatchError(
8493 this
8494 , new ReadError('get() requires key and callback arguments')
8495 )
8496 }
8497
8498 if (!this._isOpening() && !this.isOpen()) {
8499 return dispatchError(
8500 this
8501 , new ReadError('Database is not open')
8502 , callback
8503 )
8504 }
8505
8506 options = util.getOptions(this, options)
8507 key = util.encodeKey(key_, options)
8508
8509 options.asBuffer = util.isValueAsBuffer(options)
8510
8511 this.db.get(key, options, function (err, value) {
8512 if (err) {
8513 if ((/notfound/i).test(err)) {
8514 err = new NotFoundError(
8515 'Key not found in database [' + key_ + ']', err)
8516 } else {
8517 err = new ReadError(err)
8518 }
8519 return dispatchError(self, err, callback)
8520 }
8521 if (callback) {
8522 try {
8523 value = util.decodeValue(value, options)
8524 } catch (e) {
8525 return callback(new EncodingError(e))
8526 }
8527 callback(null, value)
8528 }
8529 })
8530}
8531
8532LevelUP.prototype.put = function (key_, value_, options, callback) {
8533 var self = this
8534 , key
8535 , value
8536
8537 callback = getCallback(options, callback)
8538
8539 if (key_ === null || key_ === undefined
8540 || value_ === null || value_ === undefined) {
8541 return dispatchError(
8542 this
8543 , new WriteError('put() requires key and value arguments')
8544 , callback
8545 )
8546 }
8547
8548 if (!this._isOpening() && !this.isOpen()) {
8549 return dispatchError(
8550 this
8551 , new WriteError('Database is not open')
8552 , callback
8553 )
8554 }
8555
8556 options = getOptions(this, options)
8557 key = util.encodeKey(key_, options)
8558 value = util.encodeValue(value_, options)
8559
8560 this.db.put(key, value, options, function (err) {
8561 if (err) {
8562 return dispatchError(self, new WriteError(err), callback)
8563 } else {
8564 self.emit('put', key_, value_)
8565 if (callback)
8566 callback()
8567 }
8568 })
8569}
8570
8571LevelUP.prototype.del = function (key_, options, callback) {
8572 var self = this
8573 , key
8574
8575 callback = getCallback(options, callback)
8576
8577 if (key_ === null || key_ === undefined) {
8578 return dispatchError(
8579 this
8580 , new WriteError('del() requires a key argument')
8581 , callback
8582 )
8583 }
8584
8585 if (!this._isOpening() && !this.isOpen()) {
8586 return dispatchError(
8587 this
8588 , new WriteError('Database is not open')
8589 , callback
8590 )
8591 }
8592
8593 options = getOptions(this, options)
8594 key = util.encodeKey(key_, options)
8595
8596 this.db.del(key, options, function (err) {
8597 if (err) {
8598 return dispatchError(self, new WriteError(err), callback)
8599 } else {
8600 self.emit('del', key_)
8601 if (callback)
8602 callback()
8603 }
8604 })
8605}
8606
8607LevelUP.prototype.batch = function (arr_, options, callback) {
8608 var self = this
8609 , keyEnc
8610 , valueEnc
8611 , arr
8612
8613 if (!arguments.length)
8614 return new Batch(this)
8615
8616 callback = getCallback(options, callback)
8617
8618 if (!Array.isArray(arr_)) {
8619 return dispatchError(
8620 this
8621 , new WriteError('batch() requires an array argument')
8622 , callback
8623 )
8624 }
8625
8626 if (!this._isOpening() && !this.isOpen()) {
8627 return dispatchError(
8628 this
8629 , new WriteError('Database is not open')
8630 , callback
8631 )
8632 }
8633
8634 options = getOptions(this, options)
8635 keyEnc = options.keyEncoding
8636 valueEnc = options.valueEncoding
8637
8638 arr = arr_.map(function (e) {
8639 if (e.type === undefined || e.key === undefined)
8640 return {}
8641
8642 // inherit encoding
8643 var kEnc = e.keyEncoding || keyEnc
8644 , vEnc = e.valueEncoding || e.encoding || valueEnc
8645 , o
8646
8647 // If we're not dealing with plain utf8 strings or plain
8648 // Buffers then we have to do some work on the array to
8649 // encode the keys and/or values. This includes JSON types.
8650
8651 if (kEnc != 'utf8' && kEnc != 'binary'
8652 || vEnc != 'utf8' && vEnc != 'binary') {
8653 o = {
8654 type: e.type
8655 , key: util.encodeKey(e.key, options, e)
8656 }
8657
8658 if (e.value !== undefined)
8659 o.value = util.encodeValue(e.value, options, e)
8660
8661 return o
8662 } else {
8663 return e
8664 }
8665 })
8666
8667 this.db.batch(arr, options, function (err) {
8668 if (err) {
8669 return dispatchError(self, new WriteError(err), callback)
8670 } else {
8671 self.emit('batch', arr_)
8672 if (callback)
8673 callback()
8674 }
8675 })
8676}
8677
8678// DEPRECATED: prefer accessing LevelDOWN for this: db.db.approximateSize()
8679LevelUP.prototype.approximateSize = function (start_, end_, callback) {
8680 var self = this
8681 , start
8682 , end
8683
8684 if (start_ === null || start_ === undefined
8685 || end_ === null || end_ === undefined
8686 || typeof callback != 'function') {
8687 return dispatchError(
8688 this
8689 , new ReadError('approximateSize() requires start, end and callback arguments')
8690 , callback
8691 )
8692 }
8693
8694 start = util.encodeKey(start_, this.options)
8695 end = util.encodeKey(end_, this.options)
8696
8697 if (!this._isOpening() && !this.isOpen()) {
8698 return dispatchError(
8699 this
8700 , new WriteError('Database is not open')
8701 , callback
8702 )
8703 }
8704
8705 this.db.approximateSize(start, end, function (err, size) {
8706 if (err) {
8707 return dispatchError(self, new OpenError(err), callback)
8708 } else if (callback) {
8709 callback(null, size)
8710 }
8711 })
8712}
8713
8714LevelUP.prototype.readStream =
8715LevelUP.prototype.createReadStream = function (options) {
8716 var self = this
8717 options = extend(this.options, options)
8718 return new ReadStream(
8719 options
8720 , this
8721 , function (options) {
8722 return self.db.iterator(options)
8723 }
8724 )
8725}
8726
8727LevelUP.prototype.keyStream =
8728LevelUP.prototype.createKeyStream = function (options) {
8729 return this.createReadStream(extend(options, { keys: true, values: false }))
8730}
8731
8732LevelUP.prototype.valueStream =
8733LevelUP.prototype.createValueStream = function (options) {
8734 return this.createReadStream(extend(options, { keys: false, values: true }))
8735}
8736
8737LevelUP.prototype.writeStream =
8738LevelUP.prototype.createWriteStream = function (options) {
8739 return new WriteStream(extend(options), this)
8740}
8741
8742LevelUP.prototype.toString = function () {
8743 return 'LevelUP'
8744}
8745
8746function utilStatic (name) {
8747 return function (location, callback) {
8748 getLevelDOWN()[name](location, callback || function () {})
8749 }
8750}
8751
8752module.exports = LevelUP
8753module.exports.copy = util.copy
8754// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').destroy()
8755module.exports.destroy = utilStatic('destroy')
8756// DEPRECATED: prefer accessing LevelDOWN for this: require('leveldown').repair()
8757module.exports.repair = utilStatic('repair')
8758}, {"events":3,"util":23,"xtend":41,"prr":42,"deferred-leveldown":43,"./errors":47,"./read-stream":50,"./write-stream":80,"./util":77,"./batch":82}],41: [function (exports, require, module, global) {module.exports = extend
8759
8760function extend() {
8761 var target = {}
8762
8763 for (var i = 0; i < arguments.length; i++) {
8764 var source = arguments[i]
8765
8766 for (var key in source) {
8767 if (source.hasOwnProperty(key)) {
8768 target[key] = source[key]
8769 }
8770 }
8771 }
8772
8773 return target
8774}
8775}, {}],42: [function (exports, require, module, global) {/*!
8776 * prr
8777 * (c) 2013 Rod Vagg <rod@vagg.org>
8778 * https://github.com/rvagg/prr
8779 * License: MIT
8780 */
8781
8782(function (name, context, definition) {
8783 if (typeof module != 'undefined' && module.exports)
8784 module.exports = definition()
8785 else
8786 context[name] = definition()
8787})('prr', this, function() {
8788
8789 var setProperty = typeof Object.defineProperty == 'function'
8790 ? function (obj, key, options) {
8791 Object.defineProperty(obj, key, options)
8792 return obj
8793 }
8794 : function (obj, key, options) { // < es5
8795 obj[key] = options.value
8796 return obj
8797 }
8798
8799 , makeOptions = function (value, options) {
8800 var oo = typeof options == 'object'
8801 , os = !oo && typeof options == 'string'
8802 , op = function (p) {
8803 return oo
8804 ? !!options[p]
8805 : os
8806 ? options.indexOf(p[0]) > -1
8807 : false
8808 }
8809
8810 return {
8811 enumerable : op('enumerable')
8812 , configurable : op('configurable')
8813 , writable : op('writable')
8814 , value : value
8815 }
8816 }
8817
8818 , prr = function (obj, key, value, options) {
8819 var k
8820
8821 options = makeOptions(value, options)
8822
8823 if (typeof key == 'object') {
8824 for (k in key) {
8825 if (Object.hasOwnProperty.call(key, k)) {
8826 options.value = key[k]
8827 setProperty(obj, k, options)
8828 }
8829 }
8830 return obj
8831 }
8832
8833 return setProperty(obj, key, options)
8834 }
8835
8836 return prr
8837})}, {}],43: [function (exports, require, module, global) {var util = require('util')
8838 , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
8839
8840function DeferredLevelDOWN (location) {
8841 AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares?
8842 this._db = undefined
8843 this._operations = []
8844}
8845
8846util.inherits(DeferredLevelDOWN, AbstractLevelDOWN)
8847
8848// called by LevelUP when we have a real DB to take its place
8849DeferredLevelDOWN.prototype.setDb = function (db) {
8850 this._db = db
8851 this._operations.forEach(function (op) {
8852 db[op.method].apply(db, op.args)
8853 })
8854}
8855
8856DeferredLevelDOWN.prototype._open = function (options, callback) {
8857 return process.nextTick(callback)
8858}
8859
8860// queue a new deferred operation
8861DeferredLevelDOWN.prototype._operation = function (method, args) {
8862 if (this._db)
8863 return this._db[method].apply(this._db, args)
8864 this._operations.push({ method: method, args: args })
8865}
8866
8867// deferrables
8868'put get del batch approximateSize'.split(' ').forEach(function (m) {
8869 DeferredLevelDOWN.prototype['_' + m] = function () {
8870 this._operation(m, arguments)
8871 }
8872})
8873
8874DeferredLevelDOWN.prototype._isBuffer = function (obj) {
8875 return Buffer.isBuffer(obj)
8876}
8877
8878// don't need to implement this as LevelUP's ReadStream checks for 'ready' state
8879DeferredLevelDOWN.prototype._iterator = function () {
8880 throw new TypeError('not implemented')
8881}
8882
8883module.exports = DeferredLevelDOWN
8884}, {"util":23,"abstract-leveldown":44}],44: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
8885
8886var xtend = require('xtend')
8887 , AbstractIterator = require('./abstract-iterator')
8888 , AbstractChainedBatch = require('./abstract-chained-batch')
8889
8890function AbstractLevelDOWN (location) {
8891 if (!arguments.length || location === undefined)
8892 throw new Error('constructor requires at least a location argument')
8893
8894 if (typeof location != 'string')
8895 throw new Error('constructor requires a location string argument')
8896
8897 this.location = location
8898}
8899
8900AbstractLevelDOWN.prototype.open = function (options, callback) {
8901 if (typeof options == 'function')
8902 callback = options
8903
8904 if (typeof callback != 'function')
8905 throw new Error('open() requires a callback argument')
8906
8907 if (typeof options != 'object')
8908 options = {}
8909
8910 if (typeof this._open == 'function')
8911 return this._open(options, callback)
8912
8913 process.nextTick(callback)
8914}
8915
8916AbstractLevelDOWN.prototype.close = function (callback) {
8917 if (typeof callback != 'function')
8918 throw new Error('close() requires a callback argument')
8919
8920 if (typeof this._close == 'function')
8921 return this._close(callback)
8922
8923 process.nextTick(callback)
8924}
8925
8926AbstractLevelDOWN.prototype.get = function (key, options, callback) {
8927 var err
8928
8929 if (typeof options == 'function')
8930 callback = options
8931
8932 if (typeof callback != 'function')
8933 throw new Error('get() requires a callback argument')
8934
8935 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
8936 return callback(err)
8937
8938 if (!this._isBuffer(key))
8939 key = String(key)
8940
8941 if (typeof options != 'object')
8942 options = {}
8943
8944 if (typeof this._get == 'function')
8945 return this._get(key, options, callback)
8946
8947 process.nextTick(function () { callback(new Error('NotFound')) })
8948}
8949
8950AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
8951 var err
8952
8953 if (typeof options == 'function')
8954 callback = options
8955
8956 if (typeof callback != 'function')
8957 throw new Error('put() requires a callback argument')
8958
8959 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
8960 return callback(err)
8961
8962 if (err = this._checkKeyValue(value, 'value', this._isBuffer))
8963 return callback(err)
8964
8965 if (!this._isBuffer(key))
8966 key = String(key)
8967
8968 // coerce value to string in node, don't touch it in browser
8969 // (indexeddb can store any JS type)
8970 if (!this._isBuffer(value) && !process.browser)
8971 value = String(value)
8972
8973 if (typeof options != 'object')
8974 options = {}
8975
8976 if (typeof this._put == 'function')
8977 return this._put(key, value, options, callback)
8978
8979 process.nextTick(callback)
8980}
8981
8982AbstractLevelDOWN.prototype.del = function (key, options, callback) {
8983 var err
8984
8985 if (typeof options == 'function')
8986 callback = options
8987
8988 if (typeof callback != 'function')
8989 throw new Error('del() requires a callback argument')
8990
8991 if (err = this._checkKeyValue(key, 'key', this._isBuffer))
8992 return callback(err)
8993
8994 if (!this._isBuffer(key))
8995 key = String(key)
8996
8997 if (typeof options != 'object')
8998 options = {}
8999
9000 if (typeof this._del == 'function')
9001 return this._del(key, options, callback)
9002
9003 process.nextTick(callback)
9004}
9005
9006AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
9007 if (!arguments.length)
9008 return this._chainedBatch()
9009
9010 if (typeof options == 'function')
9011 callback = options
9012
9013 if (typeof callback != 'function')
9014 throw new Error('batch(array) requires a callback argument')
9015
9016 if (!Array.isArray(array))
9017 return callback(new Error('batch(array) requires an array argument'))
9018
9019 if (typeof options != 'object')
9020 options = {}
9021
9022 var i = 0
9023 , l = array.length
9024 , e
9025 , err
9026
9027 for (; i < l; i++) {
9028 e = array[i]
9029 if (typeof e != 'object')
9030 continue
9031
9032 if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
9033 return callback(err)
9034
9035 if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
9036 return callback(err)
9037
9038 if (e.type == 'put') {
9039 if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
9040 return callback(err)
9041 }
9042 }
9043
9044 if (typeof this._batch == 'function')
9045 return this._batch(array, options, callback)
9046
9047 process.nextTick(callback)
9048}
9049
9050//TODO: remove from here, not a necessary primitive
9051AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
9052 if ( start == null
9053 || end == null
9054 || typeof start == 'function'
9055 || typeof end == 'function') {
9056 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
9057 }
9058
9059 if (typeof callback != 'function')
9060 throw new Error('approximateSize() requires a callback argument')
9061
9062 if (!this._isBuffer(start))
9063 start = String(start)
9064
9065 if (!this._isBuffer(end))
9066 end = String(end)
9067
9068 if (typeof this._approximateSize == 'function')
9069 return this._approximateSize(start, end, callback)
9070
9071 process.nextTick(function () {
9072 callback(null, 0)
9073 })
9074}
9075
9076AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
9077 var self = this
9078
9079 options = xtend(options)
9080
9081 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
9082 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
9083 delete options[o]
9084 })
9085
9086 options.reverse = !!options.reverse
9087
9088 // fix `start` so it takes into account gt, gte, lt, lte as appropriate
9089 if (options.reverse && options.lt)
9090 options.start = options.lt
9091 if (options.reverse && options.lte)
9092 options.start = options.lte
9093 if (!options.reverse && options.gt)
9094 options.start = options.gt
9095 if (!options.reverse && options.gte)
9096 options.start = options.gte
9097
9098 if ((options.reverse && options.lt && !options.lte)
9099 || (!options.reverse && options.gt && !options.gte))
9100 options.exclusiveStart = true // start should *not* include matching key
9101
9102 return options
9103}
9104
9105AbstractLevelDOWN.prototype.iterator = function (options) {
9106 if (typeof options != 'object')
9107 options = {}
9108
9109 options = this._setupIteratorOptions(options)
9110
9111 if (typeof this._iterator == 'function')
9112 return this._iterator(options)
9113
9114 return new AbstractIterator(this)
9115}
9116
9117AbstractLevelDOWN.prototype._chainedBatch = function () {
9118 return new AbstractChainedBatch(this)
9119}
9120
9121AbstractLevelDOWN.prototype._isBuffer = function (obj) {
9122 return Buffer.isBuffer(obj)
9123}
9124
9125AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {
9126
9127 if (obj === null || obj === undefined)
9128 return new Error(type + ' cannot be `null` or `undefined`')
9129
9130 if (this._isBuffer(obj)) {
9131 if (obj.length === 0)
9132 return new Error(type + ' cannot be an empty Buffer')
9133 } else if (String(obj) === '')
9134 return new Error(type + ' cannot be an empty String')
9135}
9136
9137module.exports.AbstractLevelDOWN = AbstractLevelDOWN
9138module.exports.AbstractIterator = AbstractIterator
9139module.exports.AbstractChainedBatch = AbstractChainedBatch
9140}, {"xtend":41,"./abstract-iterator":45,"./abstract-chained-batch":46}],45: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
9141
9142function AbstractIterator (db) {
9143 this.db = db
9144 this._ended = false
9145 this._nexting = false
9146}
9147
9148AbstractIterator.prototype.next = function (callback) {
9149 var self = this
9150
9151 if (typeof callback != 'function')
9152 throw new Error('next() requires a callback argument')
9153
9154 if (self._ended)
9155 return callback(new Error('cannot call next() after end()'))
9156 if (self._nexting)
9157 return callback(new Error('cannot call next() before previous next() has completed'))
9158
9159 self._nexting = true
9160 if (typeof self._next == 'function') {
9161 return self._next(function () {
9162 self._nexting = false
9163 callback.apply(null, arguments)
9164 })
9165 }
9166
9167 process.nextTick(function () {
9168 self._nexting = false
9169 callback()
9170 })
9171}
9172
9173AbstractIterator.prototype.end = function (callback) {
9174 if (typeof callback != 'function')
9175 throw new Error('end() requires a callback argument')
9176
9177 if (this._ended)
9178 return callback(new Error('end() already called on iterator'))
9179
9180 this._ended = true
9181
9182 if (typeof this._end == 'function')
9183 return this._end(callback)
9184
9185 process.nextTick(callback)
9186}
9187
9188module.exports = AbstractIterator
9189}, {}],46: [function (exports, require, module, global) {/* Copyright (c) 2013 Rod Vagg, MIT License */
9190
9191function AbstractChainedBatch (db) {
9192 this._db = db
9193 this._operations = []
9194 this._written = false
9195}
9196
9197AbstractChainedBatch.prototype._checkWritten = function () {
9198 if (this._written)
9199 throw new Error('write() already called on this batch')
9200}
9201
9202AbstractChainedBatch.prototype.put = function (key, value) {
9203 this._checkWritten()
9204
9205 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
9206 if (err) throw err
9207 err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
9208 if (err) throw err
9209
9210 if (!this._db._isBuffer(key)) key = String(key)
9211 if (!this._db._isBuffer(value)) value = String(value)
9212
9213 if (typeof this._put == 'function' )
9214 this._put(key, value)
9215 else
9216 this._operations.push({ type: 'put', key: key, value: value })
9217
9218 return this
9219}
9220
9221AbstractChainedBatch.prototype.del = function (key) {
9222 this._checkWritten()
9223
9224 var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
9225 if (err) throw err
9226
9227 if (!this._db._isBuffer(key)) key = String(key)
9228
9229 if (typeof this._del == 'function' )
9230 this._del(key)
9231 else
9232 this._operations.push({ type: 'del', key: key })
9233
9234 return this
9235}
9236
9237AbstractChainedBatch.prototype.clear = function () {
9238 this._checkWritten()
9239
9240 this._operations = []
9241
9242 if (typeof this._clear == 'function' )
9243 this._clear()
9244
9245 return this
9246}
9247
9248AbstractChainedBatch.prototype.write = function (options, callback) {
9249 this._checkWritten()
9250
9251 if (typeof options == 'function')
9252 callback = options
9253 if (typeof callback != 'function')
9254 throw new Error('write() requires a callback argument')
9255 if (typeof options != 'object')
9256 options = {}
9257
9258 this._written = true
9259
9260 if (typeof this._write == 'function' )
9261 return this._write(callback)
9262
9263 if (typeof this._db._batch == 'function')
9264 return this._db._batch(this._operations, options, callback)
9265
9266 process.nextTick(callback)
9267}
9268
9269module.exports = AbstractChainedBatch}, {}],47: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
9270 * See list at <https://github.com/rvagg/node-levelup#contributing>
9271 * MIT License
9272 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
9273 */
9274
9275var createError = require('errno').create
9276 , LevelUPError = createError('LevelUPError')
9277 , NotFoundError = createError('NotFoundError', LevelUPError)
9278
9279NotFoundError.prototype.notFound = true
9280NotFoundError.prototype.status = 404
9281
9282module.exports = {
9283 LevelUPError : LevelUPError
9284 , InitializationError : createError('InitializationError', LevelUPError)
9285 , OpenError : createError('OpenError', LevelUPError)
9286 , ReadError : createError('ReadError', LevelUPError)
9287 , WriteError : createError('WriteError', LevelUPError)
9288 , NotFoundError : NotFoundError
9289 , EncodingError : createError('EncodingError', LevelUPError)
9290}
9291}, {"errno":48}],48: [function (exports, require, module, global) {var all = module.exports.all = [
9292 {
9293 errno: -2,
9294 code: 'ENOENT',
9295 description: 'no such file or directory'
9296 },
9297 {
9298 errno: -1,
9299 code: 'UNKNOWN',
9300 description: 'unknown error'
9301 },
9302 {
9303 errno: 0,
9304 code: 'OK',
9305 description: 'success'
9306 },
9307 {
9308 errno: 1,
9309 code: 'EOF',
9310 description: 'end of file'
9311 },
9312 {
9313 errno: 2,
9314 code: 'EADDRINFO',
9315 description: 'getaddrinfo error'
9316 },
9317 {
9318 errno: 3,
9319 code: 'EACCES',
9320 description: 'permission denied'
9321 },
9322 {
9323 errno: 4,
9324 code: 'EAGAIN',
9325 description: 'resource temporarily unavailable'
9326 },
9327 {
9328 errno: 5,
9329 code: 'EADDRINUSE',
9330 description: 'address already in use'
9331 },
9332 {
9333 errno: 6,
9334 code: 'EADDRNOTAVAIL',
9335 description: 'address not available'
9336 },
9337 {
9338 errno: 7,
9339 code: 'EAFNOSUPPORT',
9340 description: 'address family not supported'
9341 },
9342 {
9343 errno: 8,
9344 code: 'EALREADY',
9345 description: 'connection already in progress'
9346 },
9347 {
9348 errno: 9,
9349 code: 'EBADF',
9350 description: 'bad file descriptor'
9351 },
9352 {
9353 errno: 10,
9354 code: 'EBUSY',
9355 description: 'resource busy or locked'
9356 },
9357 {
9358 errno: 11,
9359 code: 'ECONNABORTED',
9360 description: 'software caused connection abort'
9361 },
9362 {
9363 errno: 12,
9364 code: 'ECONNREFUSED',
9365 description: 'connection refused'
9366 },
9367 {
9368 errno: 13,
9369 code: 'ECONNRESET',
9370 description: 'connection reset by peer'
9371 },
9372 {
9373 errno: 14,
9374 code: 'EDESTADDRREQ',
9375 description: 'destination address required'
9376 },
9377 {
9378 errno: 15,
9379 code: 'EFAULT',
9380 description: 'bad address in system call argument'
9381 },
9382 {
9383 errno: 16,
9384 code: 'EHOSTUNREACH',
9385 description: 'host is unreachable'
9386 },
9387 {
9388 errno: 17,
9389 code: 'EINTR',
9390 description: 'interrupted system call'
9391 },
9392 {
9393 errno: 18,
9394 code: 'EINVAL',
9395 description: 'invalid argument'
9396 },
9397 {
9398 errno: 19,
9399 code: 'EISCONN',
9400 description: 'socket is already connected'
9401 },
9402 {
9403 errno: 20,
9404 code: 'EMFILE',
9405 description: 'too many open files'
9406 },
9407 {
9408 errno: 21,
9409 code: 'EMSGSIZE',
9410 description: 'message too long'
9411 },
9412 {
9413 errno: 22,
9414 code: 'ENETDOWN',
9415 description: 'network is down'
9416 },
9417 {
9418 errno: 23,
9419 code: 'ENETUNREACH',
9420 description: 'network is unreachable'
9421 },
9422 {
9423 errno: 24,
9424 code: 'ENFILE',
9425 description: 'file table overflow'
9426 },
9427 {
9428 errno: 25,
9429 code: 'ENOBUFS',
9430 description: 'no buffer space available'
9431 },
9432 {
9433 errno: 26,
9434 code: 'ENOMEM',
9435 description: 'not enough memory'
9436 },
9437 {
9438 errno: 27,
9439 code: 'ENOTDIR',
9440 description: 'not a directory'
9441 },
9442 {
9443 errno: 28,
9444 code: 'EISDIR',
9445 description: 'illegal operation on a directory'
9446 },
9447 {
9448 errno: 29,
9449 code: 'ENONET',
9450 description: 'machine is not on the network'
9451 },
9452 {
9453 errno: 31,
9454 code: 'ENOTCONN',
9455 description: 'socket is not connected'
9456 },
9457 {
9458 errno: 32,
9459 code: 'ENOTSOCK',
9460 description: 'socket operation on non-socket'
9461 },
9462 {
9463 errno: 33,
9464 code: 'ENOTSUP',
9465 description: 'operation not supported on socket'
9466 },
9467 {
9468 errno: 34,
9469 code: 'ENOENT',
9470 description: 'no such file or directory'
9471 },
9472 {
9473 errno: 35,
9474 code: 'ENOSYS',
9475 description: 'function not implemented'
9476 },
9477 {
9478 errno: 36,
9479 code: 'EPIPE',
9480 description: 'broken pipe'
9481 },
9482 {
9483 errno: 37,
9484 code: 'EPROTO',
9485 description: 'protocol error'
9486 },
9487 {
9488 errno: 38,
9489 code: 'EPROTONOSUPPORT',
9490 description: 'protocol not supported'
9491 },
9492 {
9493 errno: 39,
9494 code: 'EPROTOTYPE',
9495 description: 'protocol wrong type for socket'
9496 },
9497 {
9498 errno: 40,
9499 code: 'ETIMEDOUT',
9500 description: 'connection timed out'
9501 },
9502 {
9503 errno: 41,
9504 code: 'ECHARSET',
9505 description: 'invalid Unicode character'
9506 },
9507 {
9508 errno: 42,
9509 code: 'EAIFAMNOSUPPORT',
9510 description: 'address family for hostname not supported'
9511 },
9512 {
9513 errno: 44,
9514 code: 'EAISERVICE',
9515 description: 'servname not supported for ai_socktype'
9516 },
9517 {
9518 errno: 45,
9519 code: 'EAISOCKTYPE',
9520 description: 'ai_socktype not supported'
9521 },
9522 {
9523 errno: 46,
9524 code: 'ESHUTDOWN',
9525 description: 'cannot send after transport endpoint shutdown'
9526 },
9527 {
9528 errno: 47,
9529 code: 'EEXIST',
9530 description: 'file already exists'
9531 },
9532 {
9533 errno: 48,
9534 code: 'ESRCH',
9535 description: 'no such process'
9536 },
9537 {
9538 errno: 49,
9539 code: 'ENAMETOOLONG',
9540 description: 'name too long'
9541 },
9542 {
9543 errno: 50,
9544 code: 'EPERM',
9545 description: 'operation not permitted'
9546 },
9547 {
9548 errno: 51,
9549 code: 'ELOOP',
9550 description: 'too many symbolic links encountered'
9551 },
9552 {
9553 errno: 52,
9554 code: 'EXDEV',
9555 description: 'cross-device link not permitted'
9556 },
9557 {
9558 errno: 53,
9559 code: 'ENOTEMPTY',
9560 description: 'directory not empty'
9561 },
9562 {
9563 errno: 54,
9564 code: 'ENOSPC',
9565 description: 'no space left on device'
9566 },
9567 {
9568 errno: 55,
9569 code: 'EIO',
9570 description: 'i/o error'
9571 },
9572 {
9573 errno: 56,
9574 code: 'EROFS',
9575 description: 'read-only file system'
9576 },
9577 {
9578 errno: 57,
9579 code: 'ENODEV',
9580 description: 'no such device'
9581 },
9582 {
9583 errno: 58,
9584 code: 'ESPIPE',
9585 description: 'invalid seek'
9586 },
9587 {
9588 errno: 59,
9589 code: 'ECANCELED',
9590 description: 'operation canceled'
9591 }
9592]
9593
9594module.exports.errno = {}
9595module.exports.code = {}
9596
9597all.forEach(function (error) {
9598 module.exports.errno[error.errno] = error
9599 module.exports.code[error.code] = error
9600})
9601
9602module.exports.custom = require('./custom')(module.exports)
9603module.exports.create = module.exports.custom.createError
9604}, {"./custom":49}],49: [function (exports, require, module, global) {var prr = require('prr')
9605
9606function init (type, message, cause) {
9607 prr(this, {
9608 type : type
9609 , name : type
9610 // can be passed just a 'cause'
9611 , cause : typeof message != 'string' ? message : cause
9612 , message : !!message && typeof message != 'string' ? message.message : message
9613
9614 }, 'ewr')
9615}
9616
9617// generic prototype, not intended to be actually used - helpful for `instanceof`
9618function CustomError (message, cause) {
9619 Error.call(this)
9620 if (Error.captureStackTrace)
9621 Error.captureStackTrace(this, arguments.callee)
9622 init.call(this, 'CustomError', message, cause)
9623}
9624
9625CustomError.prototype = new Error()
9626
9627function createError (errno, type, proto) {
9628 var err = function (message, cause) {
9629 init.call(this, type, message, cause)
9630 //TODO: the specificity here is stupid, errno should be available everywhere
9631 if (type == 'FilesystemError') {
9632 this.code = this.cause.code
9633 this.path = this.cause.path
9634 this.errno = this.cause.errno
9635 this.message =
9636 (errno.errno[this.cause.errno]
9637 ? errno.errno[this.cause.errno].description
9638 : this.cause.message)
9639 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
9640 }
9641 Error.call(this)
9642 if (Error.captureStackTrace)
9643 Error.captureStackTrace(this, arguments.callee)
9644 }
9645 err.prototype = !!proto ? new proto() : new CustomError()
9646 return err
9647}
9648
9649module.exports = function (errno) {
9650 var ce = function (type, proto) {
9651 return createError(errno, type, proto)
9652 }
9653 return {
9654 CustomError : CustomError
9655 , FilesystemError : ce('FilesystemError')
9656 , createError : ce
9657 }
9658}
9659}, {"prr":42}],50: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
9660 * See list at <https://github.com/rvagg/node-levelup#contributing>
9661 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
9662 */
9663
9664// NOTE: we are fixed to readable-stream@1.0.x for now
9665// for pure Streams2 across Node versions
9666var Readable = require('readable-stream').Readable
9667 , inherits = require('util').inherits
9668 , extend = require('xtend')
9669 , EncodingError = require('./errors').EncodingError
9670 , util = require('./util')
9671
9672 , defaultOptions = { keys: true, values: true }
9673
9674 , makeKeyValueData = function (key, value) {
9675 return {
9676 key: util.decodeKey(key, this._options)
9677 , value: util.decodeValue(value, this._options)
9678 }
9679 }
9680 , makeKeyData = function (key) {
9681 return util.decodeKey(key, this._options)
9682 }
9683 , makeValueData = function (_, value) {
9684 return util.decodeValue(value, this._options)
9685 }
9686 , makeNoData = function () { return null }
9687
9688function ReadStream (options, db, iteratorFactory) {
9689 if (!(this instanceof ReadStream))
9690 return new ReadStream(options, db, iteratorFactory)
9691
9692 Readable.call(this, { objectMode: true, highWaterMark: options.highWaterMark })
9693
9694 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
9695 this._db = db
9696
9697 options = this._options = extend(defaultOptions, options)
9698
9699 this._keyEncoding = options.keyEncoding || options.encoding
9700 this._valueEncoding = options.valueEncoding || options.encoding
9701
9702 if (typeof this._options.start != 'undefined')
9703 this._options.start = util.encodeKey(this._options.start, this._options)
9704 if (typeof this._options.end != 'undefined')
9705 this._options.end = util.encodeKey(this._options.end, this._options)
9706 if (typeof this._options.limit != 'number')
9707 this._options.limit = -1
9708
9709 this._options.keyAsBuffer = util.isKeyAsBuffer(this._options)
9710
9711 this._options.valueAsBuffer = util.isValueAsBuffer(this._options)
9712
9713 this._makeData = this._options.keys && this._options.values
9714 ? makeKeyValueData : this._options.keys
9715 ? makeKeyData : this._options.values
9716 ? makeValueData : makeNoData
9717
9718 var self = this
9719 if (!this._db.isOpen()) {
9720 this._db.once('ready', function () {
9721 if (!self._destroyed) {
9722 self._iterator = iteratorFactory(self._options)
9723 }
9724 })
9725 } else
9726 this._iterator = iteratorFactory(this._options)
9727}
9728
9729inherits(ReadStream, Readable)
9730
9731ReadStream.prototype._read = function read () {
9732 var self = this
9733 if (!self._db.isOpen()) {
9734 return self._db.once('ready', function () { read.call(self) })
9735 }
9736 if (self._destroyed)
9737 return
9738
9739 self._iterator.next(function(err, key, value) {
9740 if (err || (key === undefined && value === undefined)) {
9741 if (!err && !self._destroyed)
9742 self.push(null)
9743 return self._cleanup(err)
9744 }
9745
9746 try {
9747 value = self._makeData(key, value)
9748 } catch (e) {
9749 return self._cleanup(new EncodingError(e))
9750 }
9751 if (!self._destroyed)
9752 self.push(value)
9753 })
9754}
9755
9756ReadStream.prototype._cleanup = function (err) {
9757 if (this._destroyed)
9758 return
9759
9760 this._destroyed = true
9761
9762 var self = this
9763 if (err)
9764 self.emit('error', err)
9765
9766 if (self._iterator) {
9767 self._iterator.end(function () {
9768 self._iterator = null
9769 self.emit('close')
9770 })
9771 } else {
9772 self.emit('close')
9773 }
9774}
9775
9776ReadStream.prototype.destroy = function () {
9777 this._cleanup()
9778}
9779
9780ReadStream.prototype.toString = function () {
9781 return 'LevelUP.ReadStream'
9782}
9783
9784module.exports = ReadStream
9785}, {"readable-stream":51,"util":23,"xtend":41,"./errors":47,"./util":77}],51: [function (exports, require, module, global) {var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify
9786exports = module.exports = require('./lib/_stream_readable.js');
9787exports.Stream = Stream;
9788exports.Readable = exports;
9789exports.Writable = require('./lib/_stream_writable.js');
9790exports.Duplex = require('./lib/_stream_duplex.js');
9791exports.Transform = require('./lib/_stream_transform.js');
9792exports.PassThrough = require('./lib/_stream_passthrough.js');
9793}, {"stream":52,"./lib/_stream_readable.js":69,"./lib/_stream_writable.js":73,"./lib/_stream_duplex.js":74,"./lib/_stream_transform.js":75,"./lib/_stream_passthrough.js":76}],52: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
9794//
9795// Permission is hereby granted, free of charge, to any person obtaining a
9796// copy of this software and associated documentation files (the
9797// "Software"), to deal in the Software without restriction, including
9798// without limitation the rights to use, copy, modify, merge, publish,
9799// distribute, sublicense, and/or sell copies of the Software, and to permit
9800// persons to whom the Software is furnished to do so, subject to the
9801// following conditions:
9802//
9803// The above copyright notice and this permission notice shall be included
9804// in all copies or substantial portions of the Software.
9805//
9806// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9807// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9808// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9809// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9810// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9811// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9812// USE OR OTHER DEALINGS IN THE SOFTWARE.
9813
9814module.exports = Stream;
9815
9816var EE = require('events').EventEmitter;
9817var inherits = require('inherits');
9818
9819inherits(Stream, EE);
9820Stream.Readable = require('readable-stream/readable.js');
9821Stream.Writable = require('readable-stream/writable.js');
9822Stream.Duplex = require('readable-stream/duplex.js');
9823Stream.Transform = require('readable-stream/transform.js');
9824Stream.PassThrough = require('readable-stream/passthrough.js');
9825
9826// Backwards-compat with node 0.4.x
9827Stream.Stream = Stream;
9828
9829
9830
9831// old-style streams. Note that the pipe method (the only relevant
9832// part of this class) is overridden in the Readable class.
9833
9834function Stream() {
9835 EE.call(this);
9836}
9837
9838Stream.prototype.pipe = function(dest, options) {
9839 var source = this;
9840
9841 function ondata(chunk) {
9842 if (dest.writable) {
9843 if (false === dest.write(chunk) && source.pause) {
9844 source.pause();
9845 }
9846 }
9847 }
9848
9849 source.on('data', ondata);
9850
9851 function ondrain() {
9852 if (source.readable && source.resume) {
9853 source.resume();
9854 }
9855 }
9856
9857 dest.on('drain', ondrain);
9858
9859 // If the 'end' option is not supplied, dest.end() will be called when
9860 // source gets the 'end' or 'close' events. Only dest.end() once.
9861 if (!dest._isStdio && (!options || options.end !== false)) {
9862 source.on('end', onend);
9863 source.on('close', onclose);
9864 }
9865
9866 var didOnEnd = false;
9867 function onend() {
9868 if (didOnEnd) return;
9869 didOnEnd = true;
9870
9871 dest.end();
9872 }
9873
9874
9875 function onclose() {
9876 if (didOnEnd) return;
9877 didOnEnd = true;
9878
9879 if (typeof dest.destroy === 'function') dest.destroy();
9880 }
9881
9882 // don't leave dangling pipes when there are errors.
9883 function onerror(er) {
9884 cleanup();
9885 if (EE.listenerCount(this, 'error') === 0) {
9886 throw er; // Unhandled stream error in pipe.
9887 }
9888 }
9889
9890 source.on('error', onerror);
9891 dest.on('error', onerror);
9892
9893 // remove all the event listeners that were added.
9894 function cleanup() {
9895 source.removeListener('data', ondata);
9896 dest.removeListener('drain', ondrain);
9897
9898 source.removeListener('end', onend);
9899 source.removeListener('close', onclose);
9900
9901 source.removeListener('error', onerror);
9902 dest.removeListener('error', onerror);
9903
9904 source.removeListener('end', cleanup);
9905 source.removeListener('close', cleanup);
9906
9907 dest.removeListener('close', cleanup);
9908 }
9909
9910 source.on('end', cleanup);
9911 source.on('close', cleanup);
9912
9913 dest.on('close', cleanup);
9914
9915 dest.emit('pipe', source);
9916
9917 // Allow for unix-like usage: A.pipe(B).pipe(C)
9918 return dest;
9919};
9920}, {"events":3,"inherits":53,"readable-stream/readable.js":54,"readable-stream/writable.js":65,"readable-stream/duplex.js":66,"readable-stream/transform.js":67,"readable-stream/passthrough.js":68}],53: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
9921 // implementation from standard node.js 'util' module
9922 module.exports = function inherits(ctor, superCtor) {
9923 ctor.super_ = superCtor
9924 ctor.prototype = Object.create(superCtor.prototype, {
9925 constructor: {
9926 value: ctor,
9927 enumerable: false,
9928 writable: true,
9929 configurable: true
9930 }
9931 });
9932 };
9933} else {
9934 // old school shim for old browsers
9935 module.exports = function inherits(ctor, superCtor) {
9936 ctor.super_ = superCtor
9937 var TempCtor = function () {}
9938 TempCtor.prototype = superCtor.prototype
9939 ctor.prototype = new TempCtor()
9940 ctor.prototype.constructor = ctor
9941 }
9942}
9943}, {}],54: [function (exports, require, module, global) {var Stream = (function (){
9944 try {
9945 return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
9946 } catch(_){}
9947}());
9948exports = module.exports = require('./lib/_stream_readable.js');
9949exports.Stream = Stream || exports;
9950exports.Readable = exports;
9951exports.Writable = require('./lib/_stream_writable.js');
9952exports.Duplex = require('./lib/_stream_duplex.js');
9953exports.Transform = require('./lib/_stream_transform.js');
9954exports.PassThrough = require('./lib/_stream_passthrough.js');
9955}, {"./lib/_stream_readable.js":55,"./lib/_stream_writable.js":60,"./lib/_stream_duplex.js":59,"./lib/_stream_transform.js":63,"./lib/_stream_passthrough.js":64}],55: [function (exports, require, module, global) {'use strict';
9956
9957module.exports = Readable;
9958
9959/*<replacement>*/
9960var processNextTick = require('process-nextick-args');
9961/*</replacement>*/
9962
9963
9964/*<replacement>*/
9965var isArray = require('isarray');
9966/*</replacement>*/
9967
9968
9969/*<replacement>*/
9970var Buffer = require('buffer').Buffer;
9971/*</replacement>*/
9972
9973Readable.ReadableState = ReadableState;
9974
9975var EE = require('events');
9976
9977/*<replacement>*/
9978var EElistenerCount = function(emitter, type) {
9979 return emitter.listeners(type).length;
9980};
9981/*</replacement>*/
9982
9983
9984
9985/*<replacement>*/
9986var Stream;
9987(function (){try{
9988 Stream = require('st' + 'ream');
9989}catch(_){}finally{
9990 if (!Stream)
9991 Stream = require('events').EventEmitter;
9992}}())
9993/*</replacement>*/
9994
9995var Buffer = require('buffer').Buffer;
9996
9997/*<replacement>*/
9998var util = require('core-util-is');
9999util.inherits = require('inherits');
10000/*</replacement>*/
10001
10002
10003
10004/*<replacement>*/
10005var debugUtil = require('util');
10006var debug;
10007if (debugUtil && debugUtil.debuglog) {
10008 debug = debugUtil.debuglog('stream');
10009} else {
10010 debug = function () {};
10011}
10012/*</replacement>*/
10013
10014var StringDecoder;
10015
10016util.inherits(Readable, Stream);
10017
10018function ReadableState(options, stream) {
10019 var Duplex = require('./_stream_duplex');
10020
10021 options = options || {};
10022
10023 // object stream flag. Used to make read(n) ignore n and to
10024 // make all the buffer merging and length checks go away
10025 this.objectMode = !!options.objectMode;
10026
10027 if (stream instanceof Duplex)
10028 this.objectMode = this.objectMode || !!options.readableObjectMode;
10029
10030 // the point at which it stops calling _read() to fill the buffer
10031 // Note: 0 is a valid value, means "don't call _read preemptively ever"
10032 var hwm = options.highWaterMark;
10033 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
10034 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
10035
10036 // cast to ints.
10037 this.highWaterMark = ~~this.highWaterMark;
10038
10039 this.buffer = [];
10040 this.length = 0;
10041 this.pipes = null;
10042 this.pipesCount = 0;
10043 this.flowing = null;
10044 this.ended = false;
10045 this.endEmitted = false;
10046 this.reading = false;
10047
10048 // a flag to be able to tell if the onwrite cb is called immediately,
10049 // or on a later tick. We set this to true at first, because any
10050 // actions that shouldn't happen until "later" should generally also
10051 // not happen before the first write call.
10052 this.sync = true;
10053
10054 // whenever we return null, then we set a flag to say
10055 // that we're awaiting a 'readable' event emission.
10056 this.needReadable = false;
10057 this.emittedReadable = false;
10058 this.readableListening = false;
10059
10060 // Crypto is kind of old and crusty. Historically, its default string
10061 // encoding is 'binary' so we have to make this configurable.
10062 // Everything else in the universe uses 'utf8', though.
10063 this.defaultEncoding = options.defaultEncoding || 'utf8';
10064
10065 // when piping, we only care about 'readable' events that happen
10066 // after read()ing all the bytes and not getting any pushback.
10067 this.ranOut = false;
10068
10069 // the number of writers that are awaiting a drain event in .pipe()s
10070 this.awaitDrain = 0;
10071
10072 // if true, a maybeReadMore has been scheduled
10073 this.readingMore = false;
10074
10075 this.decoder = null;
10076 this.encoding = null;
10077 if (options.encoding) {
10078 if (!StringDecoder)
10079 StringDecoder = require('string_decoder/').StringDecoder;
10080 this.decoder = new StringDecoder(options.encoding);
10081 this.encoding = options.encoding;
10082 }
10083}
10084
10085function Readable(options) {
10086 var Duplex = require('./_stream_duplex');
10087
10088 if (!(this instanceof Readable))
10089 return new Readable(options);
10090
10091 this._readableState = new ReadableState(options, this);
10092
10093 // legacy
10094 this.readable = true;
10095
10096 if (options && typeof options.read === 'function')
10097 this._read = options.read;
10098
10099 Stream.call(this);
10100}
10101
10102// Manually shove something into the read() buffer.
10103// This returns true if the highWaterMark has not been hit yet,
10104// similar to how Writable.write() returns true if you should
10105// write() some more.
10106Readable.prototype.push = function(chunk, encoding) {
10107 var state = this._readableState;
10108
10109 if (!state.objectMode && typeof chunk === 'string') {
10110 encoding = encoding || state.defaultEncoding;
10111 if (encoding !== state.encoding) {
10112 chunk = new Buffer(chunk, encoding);
10113 encoding = '';
10114 }
10115 }
10116
10117 return readableAddChunk(this, state, chunk, encoding, false);
10118};
10119
10120// Unshift should *always* be something directly out of read()
10121Readable.prototype.unshift = function(chunk) {
10122 var state = this._readableState;
10123 return readableAddChunk(this, state, chunk, '', true);
10124};
10125
10126Readable.prototype.isPaused = function() {
10127 return this._readableState.flowing === false;
10128};
10129
10130function readableAddChunk(stream, state, chunk, encoding, addToFront) {
10131 var er = chunkInvalid(state, chunk);
10132 if (er) {
10133 stream.emit('error', er);
10134 } else if (chunk === null) {
10135 state.reading = false;
10136 onEofChunk(stream, state);
10137 } else if (state.objectMode || chunk && chunk.length > 0) {
10138 if (state.ended && !addToFront) {
10139 var e = new Error('stream.push() after EOF');
10140 stream.emit('error', e);
10141 } else if (state.endEmitted && addToFront) {
10142 var e = new Error('stream.unshift() after end event');
10143 stream.emit('error', e);
10144 } else {
10145 if (state.decoder && !addToFront && !encoding)
10146 chunk = state.decoder.write(chunk);
10147
10148 if (!addToFront)
10149 state.reading = false;
10150
10151 // if we want the data now, just emit it.
10152 if (state.flowing && state.length === 0 && !state.sync) {
10153 stream.emit('data', chunk);
10154 stream.read(0);
10155 } else {
10156 // update the buffer info.
10157 state.length += state.objectMode ? 1 : chunk.length;
10158 if (addToFront)
10159 state.buffer.unshift(chunk);
10160 else
10161 state.buffer.push(chunk);
10162
10163 if (state.needReadable)
10164 emitReadable(stream);
10165 }
10166
10167 maybeReadMore(stream, state);
10168 }
10169 } else if (!addToFront) {
10170 state.reading = false;
10171 }
10172
10173 return needMoreData(state);
10174}
10175
10176
10177// if it's past the high water mark, we can push in some more.
10178// Also, if we have no data yet, we can stand some
10179// more bytes. This is to work around cases where hwm=0,
10180// such as the repl. Also, if the push() triggered a
10181// readable event, and the user called read(largeNumber) such that
10182// needReadable was set, then we ought to push more, so that another
10183// 'readable' event will be triggered.
10184function needMoreData(state) {
10185 return !state.ended &&
10186 (state.needReadable ||
10187 state.length < state.highWaterMark ||
10188 state.length === 0);
10189}
10190
10191// backwards compatibility.
10192Readable.prototype.setEncoding = function(enc) {
10193 if (!StringDecoder)
10194 StringDecoder = require('string_decoder/').StringDecoder;
10195 this._readableState.decoder = new StringDecoder(enc);
10196 this._readableState.encoding = enc;
10197 return this;
10198};
10199
10200// Don't raise the hwm > 8MB
10201var MAX_HWM = 0x800000;
10202function computeNewHighWaterMark(n) {
10203 if (n >= MAX_HWM) {
10204 n = MAX_HWM;
10205 } else {
10206 // Get the next highest power of 2
10207 n--;
10208 n |= n >>> 1;
10209 n |= n >>> 2;
10210 n |= n >>> 4;
10211 n |= n >>> 8;
10212 n |= n >>> 16;
10213 n++;
10214 }
10215 return n;
10216}
10217
10218function howMuchToRead(n, state) {
10219 if (state.length === 0 && state.ended)
10220 return 0;
10221
10222 if (state.objectMode)
10223 return n === 0 ? 0 : 1;
10224
10225 if (n === null || isNaN(n)) {
10226 // only flow one buffer at a time
10227 if (state.flowing && state.buffer.length)
10228 return state.buffer[0].length;
10229 else
10230 return state.length;
10231 }
10232
10233 if (n <= 0)
10234 return 0;
10235
10236 // If we're asking for more than the target buffer level,
10237 // then raise the water mark. Bump up to the next highest
10238 // power of 2, to prevent increasing it excessively in tiny
10239 // amounts.
10240 if (n > state.highWaterMark)
10241 state.highWaterMark = computeNewHighWaterMark(n);
10242
10243 // don't have that much. return null, unless we've ended.
10244 if (n > state.length) {
10245 if (!state.ended) {
10246 state.needReadable = true;
10247 return 0;
10248 } else {
10249 return state.length;
10250 }
10251 }
10252
10253 return n;
10254}
10255
10256// you can override either this method, or the async _read(n) below.
10257Readable.prototype.read = function(n) {
10258 debug('read', n);
10259 var state = this._readableState;
10260 var nOrig = n;
10261
10262 if (typeof n !== 'number' || n > 0)
10263 state.emittedReadable = false;
10264
10265 // if we're doing read(0) to trigger a readable event, but we
10266 // already have a bunch of data in the buffer, then just trigger
10267 // the 'readable' event and move on.
10268 if (n === 0 &&
10269 state.needReadable &&
10270 (state.length >= state.highWaterMark || state.ended)) {
10271 debug('read: emitReadable', state.length, state.ended);
10272 if (state.length === 0 && state.ended)
10273 endReadable(this);
10274 else
10275 emitReadable(this);
10276 return null;
10277 }
10278
10279 n = howMuchToRead(n, state);
10280
10281 // if we've ended, and we're now clear, then finish it up.
10282 if (n === 0 && state.ended) {
10283 if (state.length === 0)
10284 endReadable(this);
10285 return null;
10286 }
10287
10288 // All the actual chunk generation logic needs to be
10289 // *below* the call to _read. The reason is that in certain
10290 // synthetic stream cases, such as passthrough streams, _read
10291 // may be a completely synchronous operation which may change
10292 // the state of the read buffer, providing enough data when
10293 // before there was *not* enough.
10294 //
10295 // So, the steps are:
10296 // 1. Figure out what the state of things will be after we do
10297 // a read from the buffer.
10298 //
10299 // 2. If that resulting state will trigger a _read, then call _read.
10300 // Note that this may be asynchronous, or synchronous. Yes, it is
10301 // deeply ugly to write APIs this way, but that still doesn't mean
10302 // that the Readable class should behave improperly, as streams are
10303 // designed to be sync/async agnostic.
10304 // Take note if the _read call is sync or async (ie, if the read call
10305 // has returned yet), so that we know whether or not it's safe to emit
10306 // 'readable' etc.
10307 //
10308 // 3. Actually pull the requested chunks out of the buffer and return.
10309
10310 // if we need a readable event, then we need to do some reading.
10311 var doRead = state.needReadable;
10312 debug('need readable', doRead);
10313
10314 // if we currently have less than the highWaterMark, then also read some
10315 if (state.length === 0 || state.length - n < state.highWaterMark) {
10316 doRead = true;
10317 debug('length less than watermark', doRead);
10318 }
10319
10320 // however, if we've ended, then there's no point, and if we're already
10321 // reading, then it's unnecessary.
10322 if (state.ended || state.reading) {
10323 doRead = false;
10324 debug('reading or ended', doRead);
10325 }
10326
10327 if (doRead) {
10328 debug('do read');
10329 state.reading = true;
10330 state.sync = true;
10331 // if the length is currently zero, then we *need* a readable event.
10332 if (state.length === 0)
10333 state.needReadable = true;
10334 // call internal read method
10335 this._read(state.highWaterMark);
10336 state.sync = false;
10337 }
10338
10339 // If _read pushed data synchronously, then `reading` will be false,
10340 // and we need to re-evaluate how much data we can return to the user.
10341 if (doRead && !state.reading)
10342 n = howMuchToRead(nOrig, state);
10343
10344 var ret;
10345 if (n > 0)
10346 ret = fromList(n, state);
10347 else
10348 ret = null;
10349
10350 if (ret === null) {
10351 state.needReadable = true;
10352 n = 0;
10353 }
10354
10355 state.length -= n;
10356
10357 // If we have nothing in the buffer, then we want to know
10358 // as soon as we *do* get something into the buffer.
10359 if (state.length === 0 && !state.ended)
10360 state.needReadable = true;
10361
10362 // If we tried to read() past the EOF, then emit end on the next tick.
10363 if (nOrig !== n && state.ended && state.length === 0)
10364 endReadable(this);
10365
10366 if (ret !== null)
10367 this.emit('data', ret);
10368
10369 return ret;
10370};
10371
10372function chunkInvalid(state, chunk) {
10373 var er = null;
10374 if (!(Buffer.isBuffer(chunk)) &&
10375 typeof chunk !== 'string' &&
10376 chunk !== null &&
10377 chunk !== undefined &&
10378 !state.objectMode) {
10379 er = new TypeError('Invalid non-string/buffer chunk');
10380 }
10381 return er;
10382}
10383
10384
10385function onEofChunk(stream, state) {
10386 if (state.ended) return;
10387 if (state.decoder) {
10388 var chunk = state.decoder.end();
10389 if (chunk && chunk.length) {
10390 state.buffer.push(chunk);
10391 state.length += state.objectMode ? 1 : chunk.length;
10392 }
10393 }
10394 state.ended = true;
10395
10396 // emit 'readable' now to make sure it gets picked up.
10397 emitReadable(stream);
10398}
10399
10400// Don't emit readable right away in sync mode, because this can trigger
10401// another read() call => stack overflow. This way, it might trigger
10402// a nextTick recursion warning, but that's not so bad.
10403function emitReadable(stream) {
10404 var state = stream._readableState;
10405 state.needReadable = false;
10406 if (!state.emittedReadable) {
10407 debug('emitReadable', state.flowing);
10408 state.emittedReadable = true;
10409 if (state.sync)
10410 processNextTick(emitReadable_, stream);
10411 else
10412 emitReadable_(stream);
10413 }
10414}
10415
10416function emitReadable_(stream) {
10417 debug('emit readable');
10418 stream.emit('readable');
10419 flow(stream);
10420}
10421
10422
10423// at this point, the user has presumably seen the 'readable' event,
10424// and called read() to consume some data. that may have triggered
10425// in turn another _read(n) call, in which case reading = true if
10426// it's in progress.
10427// However, if we're not ended, or reading, and the length < hwm,
10428// then go ahead and try to read some more preemptively.
10429function maybeReadMore(stream, state) {
10430 if (!state.readingMore) {
10431 state.readingMore = true;
10432 processNextTick(maybeReadMore_, stream, state);
10433 }
10434}
10435
10436function maybeReadMore_(stream, state) {
10437 var len = state.length;
10438 while (!state.reading && !state.flowing && !state.ended &&
10439 state.length < state.highWaterMark) {
10440 debug('maybeReadMore read 0');
10441 stream.read(0);
10442 if (len === state.length)
10443 // didn't get any data, stop spinning.
10444 break;
10445 else
10446 len = state.length;
10447 }
10448 state.readingMore = false;
10449}
10450
10451// abstract method. to be overridden in specific implementation classes.
10452// call cb(er, data) where data is <= n in length.
10453// for virtual (non-string, non-buffer) streams, "length" is somewhat
10454// arbitrary, and perhaps not very meaningful.
10455Readable.prototype._read = function(n) {
10456 this.emit('error', new Error('not implemented'));
10457};
10458
10459Readable.prototype.pipe = function(dest, pipeOpts) {
10460 var src = this;
10461 var state = this._readableState;
10462
10463 switch (state.pipesCount) {
10464 case 0:
10465 state.pipes = dest;
10466 break;
10467 case 1:
10468 state.pipes = [state.pipes, dest];
10469 break;
10470 default:
10471 state.pipes.push(dest);
10472 break;
10473 }
10474 state.pipesCount += 1;
10475 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
10476
10477 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
10478 dest !== process.stdout &&
10479 dest !== process.stderr;
10480
10481 var endFn = doEnd ? onend : cleanup;
10482 if (state.endEmitted)
10483 processNextTick(endFn);
10484 else
10485 src.once('end', endFn);
10486
10487 dest.on('unpipe', onunpipe);
10488 function onunpipe(readable) {
10489 debug('onunpipe');
10490 if (readable === src) {
10491 cleanup();
10492 }
10493 }
10494
10495 function onend() {
10496 debug('onend');
10497 dest.end();
10498 }
10499
10500 // when the dest drains, it reduces the awaitDrain counter
10501 // on the source. This would be more elegant with a .once()
10502 // handler in flow(), but adding and removing repeatedly is
10503 // too slow.
10504 var ondrain = pipeOnDrain(src);
10505 dest.on('drain', ondrain);
10506
10507 function cleanup() {
10508 debug('cleanup');
10509 // cleanup event handlers once the pipe is broken
10510 dest.removeListener('close', onclose);
10511 dest.removeListener('finish', onfinish);
10512 dest.removeListener('drain', ondrain);
10513 dest.removeListener('error', onerror);
10514 dest.removeListener('unpipe', onunpipe);
10515 src.removeListener('end', onend);
10516 src.removeListener('end', cleanup);
10517 src.removeListener('data', ondata);
10518
10519 // if the reader is waiting for a drain event from this
10520 // specific writer, then it would cause it to never start
10521 // flowing again.
10522 // So, if this is awaiting a drain, then we just call it now.
10523 // If we don't know, then assume that we are waiting for one.
10524 if (state.awaitDrain &&
10525 (!dest._writableState || dest._writableState.needDrain))
10526 ondrain();
10527 }
10528
10529 src.on('data', ondata);
10530 function ondata(chunk) {
10531 debug('ondata');
10532 var ret = dest.write(chunk);
10533 if (false === ret) {
10534 debug('false write response, pause',
10535 src._readableState.awaitDrain);
10536 src._readableState.awaitDrain++;
10537 src.pause();
10538 }
10539 }
10540
10541 // if the dest has an error, then stop piping into it.
10542 // however, don't suppress the throwing behavior for this.
10543 function onerror(er) {
10544 debug('onerror', er);
10545 unpipe();
10546 dest.removeListener('error', onerror);
10547 if (EElistenerCount(dest, 'error') === 0)
10548 dest.emit('error', er);
10549 }
10550 // This is a brutally ugly hack to make sure that our error handler
10551 // is attached before any userland ones. NEVER DO THIS.
10552 if (!dest._events || !dest._events.error)
10553 dest.on('error', onerror);
10554 else if (isArray(dest._events.error))
10555 dest._events.error.unshift(onerror);
10556 else
10557 dest._events.error = [onerror, dest._events.error];
10558
10559
10560 // Both close and finish should trigger unpipe, but only once.
10561 function onclose() {
10562 dest.removeListener('finish', onfinish);
10563 unpipe();
10564 }
10565 dest.once('close', onclose);
10566 function onfinish() {
10567 debug('onfinish');
10568 dest.removeListener('close', onclose);
10569 unpipe();
10570 }
10571 dest.once('finish', onfinish);
10572
10573 function unpipe() {
10574 debug('unpipe');
10575 src.unpipe(dest);
10576 }
10577
10578 // tell the dest that it's being piped to
10579 dest.emit('pipe', src);
10580
10581 // start the flow if it hasn't been started already.
10582 if (!state.flowing) {
10583 debug('pipe resume');
10584 src.resume();
10585 }
10586
10587 return dest;
10588};
10589
10590function pipeOnDrain(src) {
10591 return function() {
10592 var state = src._readableState;
10593 debug('pipeOnDrain', state.awaitDrain);
10594 if (state.awaitDrain)
10595 state.awaitDrain--;
10596 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
10597 state.flowing = true;
10598 flow(src);
10599 }
10600 };
10601}
10602
10603
10604Readable.prototype.unpipe = function(dest) {
10605 var state = this._readableState;
10606
10607 // if we're not piping anywhere, then do nothing.
10608 if (state.pipesCount === 0)
10609 return this;
10610
10611 // just one destination. most common case.
10612 if (state.pipesCount === 1) {
10613 // passed in one, but it's not the right one.
10614 if (dest && dest !== state.pipes)
10615 return this;
10616
10617 if (!dest)
10618 dest = state.pipes;
10619
10620 // got a match.
10621 state.pipes = null;
10622 state.pipesCount = 0;
10623 state.flowing = false;
10624 if (dest)
10625 dest.emit('unpipe', this);
10626 return this;
10627 }
10628
10629 // slow case. multiple pipe destinations.
10630
10631 if (!dest) {
10632 // remove all.
10633 var dests = state.pipes;
10634 var len = state.pipesCount;
10635 state.pipes = null;
10636 state.pipesCount = 0;
10637 state.flowing = false;
10638
10639 for (var i = 0; i < len; i++)
10640 dests[i].emit('unpipe', this);
10641 return this;
10642 }
10643
10644 // try to find the right one.
10645 var i = indexOf(state.pipes, dest);
10646 if (i === -1)
10647 return this;
10648
10649 state.pipes.splice(i, 1);
10650 state.pipesCount -= 1;
10651 if (state.pipesCount === 1)
10652 state.pipes = state.pipes[0];
10653
10654 dest.emit('unpipe', this);
10655
10656 return this;
10657};
10658
10659// set up data events if they are asked for
10660// Ensure readable listeners eventually get something
10661Readable.prototype.on = function(ev, fn) {
10662 var res = Stream.prototype.on.call(this, ev, fn);
10663
10664 // If listening to data, and it has not explicitly been paused,
10665 // then call resume to start the flow of data on the next tick.
10666 if (ev === 'data' && false !== this._readableState.flowing) {
10667 this.resume();
10668 }
10669
10670 if (ev === 'readable' && this.readable) {
10671 var state = this._readableState;
10672 if (!state.readableListening) {
10673 state.readableListening = true;
10674 state.emittedReadable = false;
10675 state.needReadable = true;
10676 if (!state.reading) {
10677 processNextTick(nReadingNextTick, this);
10678 } else if (state.length) {
10679 emitReadable(this, state);
10680 }
10681 }
10682 }
10683
10684 return res;
10685};
10686Readable.prototype.addListener = Readable.prototype.on;
10687
10688function nReadingNextTick(self) {
10689 debug('readable nexttick read 0');
10690 self.read(0);
10691}
10692
10693// pause() and resume() are remnants of the legacy readable stream API
10694// If the user uses them, then switch into old mode.
10695Readable.prototype.resume = function() {
10696 var state = this._readableState;
10697 if (!state.flowing) {
10698 debug('resume');
10699 state.flowing = true;
10700 resume(this, state);
10701 }
10702 return this;
10703};
10704
10705function resume(stream, state) {
10706 if (!state.resumeScheduled) {
10707 state.resumeScheduled = true;
10708 processNextTick(resume_, stream, state);
10709 }
10710}
10711
10712function resume_(stream, state) {
10713 if (!state.reading) {
10714 debug('resume read 0');
10715 stream.read(0);
10716 }
10717
10718 state.resumeScheduled = false;
10719 stream.emit('resume');
10720 flow(stream);
10721 if (state.flowing && !state.reading)
10722 stream.read(0);
10723}
10724
10725Readable.prototype.pause = function() {
10726 debug('call pause flowing=%j', this._readableState.flowing);
10727 if (false !== this._readableState.flowing) {
10728 debug('pause');
10729 this._readableState.flowing = false;
10730 this.emit('pause');
10731 }
10732 return this;
10733};
10734
10735function flow(stream) {
10736 var state = stream._readableState;
10737 debug('flow', state.flowing);
10738 if (state.flowing) {
10739 do {
10740 var chunk = stream.read();
10741 } while (null !== chunk && state.flowing);
10742 }
10743}
10744
10745// wrap an old-style stream as the async data source.
10746// This is *not* part of the readable stream interface.
10747// It is an ugly unfortunate mess of history.
10748Readable.prototype.wrap = function(stream) {
10749 var state = this._readableState;
10750 var paused = false;
10751
10752 var self = this;
10753 stream.on('end', function() {
10754 debug('wrapped end');
10755 if (state.decoder && !state.ended) {
10756 var chunk = state.decoder.end();
10757 if (chunk && chunk.length)
10758 self.push(chunk);
10759 }
10760
10761 self.push(null);
10762 });
10763
10764 stream.on('data', function(chunk) {
10765 debug('wrapped data');
10766 if (state.decoder)
10767 chunk = state.decoder.write(chunk);
10768
10769 // don't skip over falsy values in objectMode
10770 if (state.objectMode && (chunk === null || chunk === undefined))
10771 return;
10772 else if (!state.objectMode && (!chunk || !chunk.length))
10773 return;
10774
10775 var ret = self.push(chunk);
10776 if (!ret) {
10777 paused = true;
10778 stream.pause();
10779 }
10780 });
10781
10782 // proxy all the other methods.
10783 // important when wrapping filters and duplexes.
10784 for (var i in stream) {
10785 if (this[i] === undefined && typeof stream[i] === 'function') {
10786 this[i] = function(method) { return function() {
10787 return stream[method].apply(stream, arguments);
10788 }; }(i);
10789 }
10790 }
10791
10792 // proxy certain important events.
10793 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
10794 forEach(events, function(ev) {
10795 stream.on(ev, self.emit.bind(self, ev));
10796 });
10797
10798 // when we try to consume some more bytes, simply unpause the
10799 // underlying stream.
10800 self._read = function(n) {
10801 debug('wrapped _read', n);
10802 if (paused) {
10803 paused = false;
10804 stream.resume();
10805 }
10806 };
10807
10808 return self;
10809};
10810
10811
10812// exposed for testing purposes only.
10813Readable._fromList = fromList;
10814
10815// Pluck off n bytes from an array of buffers.
10816// Length is the combined lengths of all the buffers in the list.
10817function fromList(n, state) {
10818 var list = state.buffer;
10819 var length = state.length;
10820 var stringMode = !!state.decoder;
10821 var objectMode = !!state.objectMode;
10822 var ret;
10823
10824 // nothing in the list, definitely empty.
10825 if (list.length === 0)
10826 return null;
10827
10828 if (length === 0)
10829 ret = null;
10830 else if (objectMode)
10831 ret = list.shift();
10832 else if (!n || n >= length) {
10833 // read it all, truncate the array.
10834 if (stringMode)
10835 ret = list.join('');
10836 else
10837 ret = Buffer.concat(list, length);
10838 list.length = 0;
10839 } else {
10840 // read just some of it.
10841 if (n < list[0].length) {
10842 // just take a part of the first list item.
10843 // slice is the same for buffers and strings.
10844 var buf = list[0];
10845 ret = buf.slice(0, n);
10846 list[0] = buf.slice(n);
10847 } else if (n === list[0].length) {
10848 // first list is a perfect match
10849 ret = list.shift();
10850 } else {
10851 // complex case.
10852 // we have enough to cover it, but it spans past the first buffer.
10853 if (stringMode)
10854 ret = '';
10855 else
10856 ret = new Buffer(n);
10857
10858 var c = 0;
10859 for (var i = 0, l = list.length; i < l && c < n; i++) {
10860 var buf = list[0];
10861 var cpy = Math.min(n - c, buf.length);
10862
10863 if (stringMode)
10864 ret += buf.slice(0, cpy);
10865 else
10866 buf.copy(ret, c, 0, cpy);
10867
10868 if (cpy < buf.length)
10869 list[0] = buf.slice(cpy);
10870 else
10871 list.shift();
10872
10873 c += cpy;
10874 }
10875 }
10876 }
10877
10878 return ret;
10879}
10880
10881function endReadable(stream) {
10882 var state = stream._readableState;
10883
10884 // If we get here before consuming all the bytes, then that is a
10885 // bug in node. Should never happen.
10886 if (state.length > 0)
10887 throw new Error('endReadable called on non-empty stream');
10888
10889 if (!state.endEmitted) {
10890 state.ended = true;
10891 processNextTick(endReadableNT, state, stream);
10892 }
10893}
10894
10895function endReadableNT(state, stream) {
10896 // Check that we didn't get one last unshift.
10897 if (!state.endEmitted && state.length === 0) {
10898 state.endEmitted = true;
10899 stream.readable = false;
10900 stream.emit('end');
10901 }
10902}
10903
10904function forEach (xs, f) {
10905 for (var i = 0, l = xs.length; i < l; i++) {
10906 f(xs[i], i);
10907 }
10908}
10909
10910function indexOf (xs, x) {
10911 for (var i = 0, l = xs.length; i < l; i++) {
10912 if (xs[i] === x) return i;
10913 }
10914 return -1;
10915}
10916}, {"process-nextick-args":56,"isarray":57,"buffer":29,"events":3,"core-util-is":58,"inherits":53,"util":23,"./_stream_duplex":59,"string_decoder/":62}],56: [function (exports, require, module, global) {'use strict';
10917module.exports = nextTick;
10918
10919function nextTick(fn) {
10920 var args = new Array(arguments.length - 1);
10921 var i = 0;
10922 while (i < args.length) {
10923 args[i++] = arguments[i];
10924 }
10925 process.nextTick(function afterTick() {
10926 fn.apply(null, args);
10927 });
10928}
10929}, {}],57: [function (exports, require, module, global) {module.exports = Array.isArray || function (arr) {
10930 return Object.prototype.toString.call(arr) == '[object Array]';
10931};
10932}, {}],58: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
10933//
10934// Permission is hereby granted, free of charge, to any person obtaining a
10935// copy of this software and associated documentation files (the
10936// "Software"), to deal in the Software without restriction, including
10937// without limitation the rights to use, copy, modify, merge, publish,
10938// distribute, sublicense, and/or sell copies of the Software, and to permit
10939// persons to whom the Software is furnished to do so, subject to the
10940// following conditions:
10941//
10942// The above copyright notice and this permission notice shall be included
10943// in all copies or substantial portions of the Software.
10944//
10945// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10946// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10947// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10948// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10949// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10950// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10951// USE OR OTHER DEALINGS IN THE SOFTWARE.
10952
10953// NOTE: These type checking functions intentionally don't use `instanceof`
10954// because it is fragile and can be easily faked with `Object.create()`.
10955function isArray(ar) {
10956 return Array.isArray(ar);
10957}
10958exports.isArray = isArray;
10959
10960function isBoolean(arg) {
10961 return typeof arg === 'boolean';
10962}
10963exports.isBoolean = isBoolean;
10964
10965function isNull(arg) {
10966 return arg === null;
10967}
10968exports.isNull = isNull;
10969
10970function isNullOrUndefined(arg) {
10971 return arg == null;
10972}
10973exports.isNullOrUndefined = isNullOrUndefined;
10974
10975function isNumber(arg) {
10976 return typeof arg === 'number';
10977}
10978exports.isNumber = isNumber;
10979
10980function isString(arg) {
10981 return typeof arg === 'string';
10982}
10983exports.isString = isString;
10984
10985function isSymbol(arg) {
10986 return typeof arg === 'symbol';
10987}
10988exports.isSymbol = isSymbol;
10989
10990function isUndefined(arg) {
10991 return arg === void 0;
10992}
10993exports.isUndefined = isUndefined;
10994
10995function isRegExp(re) {
10996 return isObject(re) && objectToString(re) === '[object RegExp]';
10997}
10998exports.isRegExp = isRegExp;
10999
11000function isObject(arg) {
11001 return typeof arg === 'object' && arg !== null;
11002}
11003exports.isObject = isObject;
11004
11005function isDate(d) {
11006 return isObject(d) && objectToString(d) === '[object Date]';
11007}
11008exports.isDate = isDate;
11009
11010function isError(e) {
11011 return isObject(e) &&
11012 (objectToString(e) === '[object Error]' || e instanceof Error);
11013}
11014exports.isError = isError;
11015
11016function isFunction(arg) {
11017 return typeof arg === 'function';
11018}
11019exports.isFunction = isFunction;
11020
11021function isPrimitive(arg) {
11022 return arg === null ||
11023 typeof arg === 'boolean' ||
11024 typeof arg === 'number' ||
11025 typeof arg === 'string' ||
11026 typeof arg === 'symbol' || // ES6 symbol
11027 typeof arg === 'undefined';
11028}
11029exports.isPrimitive = isPrimitive;
11030
11031function isBuffer(arg) {
11032 return Buffer.isBuffer(arg);
11033}
11034exports.isBuffer = isBuffer;
11035
11036function objectToString(o) {
11037 return Object.prototype.toString.call(o);
11038}}, {}],59: [function (exports, require, module, global) {// a duplex stream is just a stream that is both readable and writable.
11039// Since JS doesn't have multiple prototypal inheritance, this class
11040// prototypally inherits from Readable, and then parasitically from
11041// Writable.
11042
11043'use strict';
11044
11045/*<replacement>*/
11046var objectKeys = Object.keys || function (obj) {
11047 var keys = [];
11048 for (var key in obj) keys.push(key);
11049 return keys;
11050}
11051/*</replacement>*/
11052
11053
11054module.exports = Duplex;
11055
11056/*<replacement>*/
11057var processNextTick = require('process-nextick-args');
11058/*</replacement>*/
11059
11060
11061
11062/*<replacement>*/
11063var util = require('core-util-is');
11064util.inherits = require('inherits');
11065/*</replacement>*/
11066
11067var Readable = require('./_stream_readable');
11068var Writable = require('./_stream_writable');
11069
11070util.inherits(Duplex, Readable);
11071
11072var keys = objectKeys(Writable.prototype);
11073for (var v = 0; v < keys.length; v++) {
11074 var method = keys[v];
11075 if (!Duplex.prototype[method])
11076 Duplex.prototype[method] = Writable.prototype[method];
11077}
11078
11079function Duplex(options) {
11080 if (!(this instanceof Duplex))
11081 return new Duplex(options);
11082
11083 Readable.call(this, options);
11084 Writable.call(this, options);
11085
11086 if (options && options.readable === false)
11087 this.readable = false;
11088
11089 if (options && options.writable === false)
11090 this.writable = false;
11091
11092 this.allowHalfOpen = true;
11093 if (options && options.allowHalfOpen === false)
11094 this.allowHalfOpen = false;
11095
11096 this.once('end', onend);
11097}
11098
11099// the no-half-open enforcer
11100function onend() {
11101 // if we allow half-open state, or if the writable side ended,
11102 // then we're ok.
11103 if (this.allowHalfOpen || this._writableState.ended)
11104 return;
11105
11106 // no more data can be written.
11107 // But allow more writes to happen in this tick.
11108 processNextTick(onEndNT, this);
11109}
11110
11111function onEndNT(self) {
11112 self.end();
11113}
11114
11115function forEach (xs, f) {
11116 for (var i = 0, l = xs.length; i < l; i++) {
11117 f(xs[i], i);
11118 }
11119}
11120}, {"process-nextick-args":56,"core-util-is":58,"inherits":53,"./_stream_readable":55,"./_stream_writable":60}],60: [function (exports, require, module, global) {// A bit simpler than readable streams.
11121// Implement an async ._write(chunk, cb), and it'll handle all
11122// the drain event emission and buffering.
11123
11124'use strict';
11125
11126module.exports = Writable;
11127
11128/*<replacement>*/
11129var processNextTick = require('process-nextick-args');
11130/*</replacement>*/
11131
11132
11133/*<replacement>*/
11134var Buffer = require('buffer').Buffer;
11135/*</replacement>*/
11136
11137Writable.WritableState = WritableState;
11138
11139
11140/*<replacement>*/
11141var util = require('core-util-is');
11142util.inherits = require('inherits');
11143/*</replacement>*/
11144
11145
11146/*<replacement>*/
11147var internalUtil = {
11148 deprecate: require('util-deprecate')
11149};
11150/*</replacement>*/
11151
11152
11153
11154/*<replacement>*/
11155var Stream;
11156(function (){try{
11157 Stream = require('st' + 'ream');
11158}catch(_){}finally{
11159 if (!Stream)
11160 Stream = require('events').EventEmitter;
11161}}())
11162/*</replacement>*/
11163
11164var Buffer = require('buffer').Buffer;
11165
11166util.inherits(Writable, Stream);
11167
11168function nop() {}
11169
11170function WriteReq(chunk, encoding, cb) {
11171 this.chunk = chunk;
11172 this.encoding = encoding;
11173 this.callback = cb;
11174 this.next = null;
11175}
11176
11177function WritableState(options, stream) {
11178 var Duplex = require('./_stream_duplex');
11179
11180 options = options || {};
11181
11182 // object stream flag to indicate whether or not this stream
11183 // contains buffers or objects.
11184 this.objectMode = !!options.objectMode;
11185
11186 if (stream instanceof Duplex)
11187 this.objectMode = this.objectMode || !!options.writableObjectMode;
11188
11189 // the point at which write() starts returning false
11190 // Note: 0 is a valid value, means that we always return false if
11191 // the entire buffer is not flushed immediately on write()
11192 var hwm = options.highWaterMark;
11193 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
11194 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11195
11196 // cast to ints.
11197 this.highWaterMark = ~~this.highWaterMark;
11198
11199 this.needDrain = false;
11200 // at the start of calling end()
11201 this.ending = false;
11202 // when end() has been called, and returned
11203 this.ended = false;
11204 // when 'finish' is emitted
11205 this.finished = false;
11206
11207 // should we decode strings into buffers before passing to _write?
11208 // this is here so that some node-core streams can optimize string
11209 // handling at a lower level.
11210 var noDecode = options.decodeStrings === false;
11211 this.decodeStrings = !noDecode;
11212
11213 // Crypto is kind of old and crusty. Historically, its default string
11214 // encoding is 'binary' so we have to make this configurable.
11215 // Everything else in the universe uses 'utf8', though.
11216 this.defaultEncoding = options.defaultEncoding || 'utf8';
11217
11218 // not an actual buffer we keep track of, but a measurement
11219 // of how much we're waiting to get pushed to some underlying
11220 // socket or file.
11221 this.length = 0;
11222
11223 // a flag to see when we're in the middle of a write.
11224 this.writing = false;
11225
11226 // when true all writes will be buffered until .uncork() call
11227 this.corked = 0;
11228
11229 // a flag to be able to tell if the onwrite cb is called immediately,
11230 // or on a later tick. We set this to true at first, because any
11231 // actions that shouldn't happen until "later" should generally also
11232 // not happen before the first write call.
11233 this.sync = true;
11234
11235 // a flag to know if we're processing previously buffered items, which
11236 // may call the _write() callback in the same tick, so that we don't
11237 // end up in an overlapped onwrite situation.
11238 this.bufferProcessing = false;
11239
11240 // the callback that's passed to _write(chunk,cb)
11241 this.onwrite = function(er) {
11242 onwrite(stream, er);
11243 };
11244
11245 // the callback that the user supplies to write(chunk,encoding,cb)
11246 this.writecb = null;
11247
11248 // the amount that is being written when _write is called.
11249 this.writelen = 0;
11250
11251 this.bufferedRequest = null;
11252 this.lastBufferedRequest = null;
11253
11254 // number of pending user-supplied write callbacks
11255 // this must be 0 before 'finish' can be emitted
11256 this.pendingcb = 0;
11257
11258 // emit prefinish if the only thing we're waiting for is _write cbs
11259 // This is relevant for synchronous Transform streams
11260 this.prefinished = false;
11261
11262 // True if the error was already emitted and should not be thrown again
11263 this.errorEmitted = false;
11264}
11265
11266WritableState.prototype.getBuffer = function writableStateGetBuffer() {
11267 var current = this.bufferedRequest;
11268 var out = [];
11269 while (current) {
11270 out.push(current);
11271 current = current.next;
11272 }
11273 return out;
11274};
11275
11276(function (){try {
11277Object.defineProperty(WritableState.prototype, 'buffer', {
11278 get: internalUtil.deprecate(function() {
11279 return this.getBuffer();
11280 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
11281 'instead.')
11282});
11283}catch(_){}}());
11284
11285
11286function Writable(options) {
11287 var Duplex = require('./_stream_duplex');
11288
11289 // Writable ctor is applied to Duplexes, though they're not
11290 // instanceof Writable, they're instanceof Readable.
11291 if (!(this instanceof Writable) && !(this instanceof Duplex))
11292 return new Writable(options);
11293
11294 this._writableState = new WritableState(options, this);
11295
11296 // legacy.
11297 this.writable = true;
11298
11299 if (options) {
11300 if (typeof options.write === 'function')
11301 this._write = options.write;
11302
11303 if (typeof options.writev === 'function')
11304 this._writev = options.writev;
11305 }
11306
11307 Stream.call(this);
11308}
11309
11310// Otherwise people can pipe Writable streams, which is just wrong.
11311Writable.prototype.pipe = function() {
11312 this.emit('error', new Error('Cannot pipe. Not readable.'));
11313};
11314
11315
11316function writeAfterEnd(stream, cb) {
11317 var er = new Error('write after end');
11318 // TODO: defer error events consistently everywhere, not just the cb
11319 stream.emit('error', er);
11320 processNextTick(cb, er);
11321}
11322
11323// If we get something that is not a buffer, string, null, or undefined,
11324// and we're not in objectMode, then that's an error.
11325// Otherwise stream chunks are all considered to be of length=1, and the
11326// watermarks determine how many objects to keep in the buffer, rather than
11327// how many bytes or characters.
11328function validChunk(stream, state, chunk, cb) {
11329 var valid = true;
11330
11331 if (!(Buffer.isBuffer(chunk)) &&
11332 typeof chunk !== 'string' &&
11333 chunk !== null &&
11334 chunk !== undefined &&
11335 !state.objectMode) {
11336 var er = new TypeError('Invalid non-string/buffer chunk');
11337 stream.emit('error', er);
11338 processNextTick(cb, er);
11339 valid = false;
11340 }
11341 return valid;
11342}
11343
11344Writable.prototype.write = function(chunk, encoding, cb) {
11345 var state = this._writableState;
11346 var ret = false;
11347
11348 if (typeof encoding === 'function') {
11349 cb = encoding;
11350 encoding = null;
11351 }
11352
11353 if (Buffer.isBuffer(chunk))
11354 encoding = 'buffer';
11355 else if (!encoding)
11356 encoding = state.defaultEncoding;
11357
11358 if (typeof cb !== 'function')
11359 cb = nop;
11360
11361 if (state.ended)
11362 writeAfterEnd(this, cb);
11363 else if (validChunk(this, state, chunk, cb)) {
11364 state.pendingcb++;
11365 ret = writeOrBuffer(this, state, chunk, encoding, cb);
11366 }
11367
11368 return ret;
11369};
11370
11371Writable.prototype.cork = function() {
11372 var state = this._writableState;
11373
11374 state.corked++;
11375};
11376
11377Writable.prototype.uncork = function() {
11378 var state = this._writableState;
11379
11380 if (state.corked) {
11381 state.corked--;
11382
11383 if (!state.writing &&
11384 !state.corked &&
11385 !state.finished &&
11386 !state.bufferProcessing &&
11387 state.bufferedRequest)
11388 clearBuffer(this, state);
11389 }
11390};
11391
11392Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
11393 // node::ParseEncoding() requires lower case.
11394 if (typeof encoding === 'string')
11395 encoding = encoding.toLowerCase();
11396 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64',
11397'ucs2', 'ucs-2','utf16le', 'utf-16le', 'raw']
11398.indexOf((encoding + '').toLowerCase()) > -1))
11399 throw new TypeError('Unknown encoding: ' + encoding);
11400 this._writableState.defaultEncoding = encoding;
11401};
11402
11403function decodeChunk(state, chunk, encoding) {
11404 if (!state.objectMode &&
11405 state.decodeStrings !== false &&
11406 typeof chunk === 'string') {
11407 chunk = new Buffer(chunk, encoding);
11408 }
11409 return chunk;
11410}
11411
11412// if we're already writing something, then just put this
11413// in the queue, and wait our turn. Otherwise, call _write
11414// If we return false, then we need a drain event, so set that flag.
11415function writeOrBuffer(stream, state, chunk, encoding, cb) {
11416 chunk = decodeChunk(state, chunk, encoding);
11417
11418 if (Buffer.isBuffer(chunk))
11419 encoding = 'buffer';
11420 var len = state.objectMode ? 1 : chunk.length;
11421
11422 state.length += len;
11423
11424 var ret = state.length < state.highWaterMark;
11425 // we must ensure that previous needDrain will not be reset to false.
11426 if (!ret)
11427 state.needDrain = true;
11428
11429 if (state.writing || state.corked) {
11430 var last = state.lastBufferedRequest;
11431 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
11432 if (last) {
11433 last.next = state.lastBufferedRequest;
11434 } else {
11435 state.bufferedRequest = state.lastBufferedRequest;
11436 }
11437 } else {
11438 doWrite(stream, state, false, len, chunk, encoding, cb);
11439 }
11440
11441 return ret;
11442}
11443
11444function doWrite(stream, state, writev, len, chunk, encoding, cb) {
11445 state.writelen = len;
11446 state.writecb = cb;
11447 state.writing = true;
11448 state.sync = true;
11449 if (writev)
11450 stream._writev(chunk, state.onwrite);
11451 else
11452 stream._write(chunk, encoding, state.onwrite);
11453 state.sync = false;
11454}
11455
11456function onwriteError(stream, state, sync, er, cb) {
11457 --state.pendingcb;
11458 if (sync)
11459 processNextTick(cb, er);
11460 else
11461 cb(er);
11462
11463 stream._writableState.errorEmitted = true;
11464 stream.emit('error', er);
11465}
11466
11467function onwriteStateUpdate(state) {
11468 state.writing = false;
11469 state.writecb = null;
11470 state.length -= state.writelen;
11471 state.writelen = 0;
11472}
11473
11474function onwrite(stream, er) {
11475 var state = stream._writableState;
11476 var sync = state.sync;
11477 var cb = state.writecb;
11478
11479 onwriteStateUpdate(state);
11480
11481 if (er)
11482 onwriteError(stream, state, sync, er, cb);
11483 else {
11484 // Check if we're actually ready to finish, but don't emit yet
11485 var finished = needFinish(state);
11486
11487 if (!finished &&
11488 !state.corked &&
11489 !state.bufferProcessing &&
11490 state.bufferedRequest) {
11491 clearBuffer(stream, state);
11492 }
11493
11494 if (sync) {
11495 processNextTick(afterWrite, stream, state, finished, cb);
11496 } else {
11497 afterWrite(stream, state, finished, cb);
11498 }
11499 }
11500}
11501
11502function afterWrite(stream, state, finished, cb) {
11503 if (!finished)
11504 onwriteDrain(stream, state);
11505 state.pendingcb--;
11506 cb();
11507 finishMaybe(stream, state);
11508}
11509
11510// Must force callback to be called on nextTick, so that we don't
11511// emit 'drain' before the write() consumer gets the 'false' return
11512// value, and has a chance to attach a 'drain' listener.
11513function onwriteDrain(stream, state) {
11514 if (state.length === 0 && state.needDrain) {
11515 state.needDrain = false;
11516 stream.emit('drain');
11517 }
11518}
11519
11520
11521// if there's something in the buffer waiting, then process it
11522function clearBuffer(stream, state) {
11523 state.bufferProcessing = true;
11524 var entry = state.bufferedRequest;
11525
11526 if (stream._writev && entry && entry.next) {
11527 // Fast case, write everything using _writev()
11528 var buffer = [];
11529 var cbs = [];
11530 while (entry) {
11531 cbs.push(entry.callback);
11532 buffer.push(entry);
11533 entry = entry.next;
11534 }
11535
11536 // count the one we are adding, as well.
11537 // TODO(isaacs) clean this up
11538 state.pendingcb++;
11539 state.lastBufferedRequest = null;
11540 doWrite(stream, state, true, state.length, buffer, '', function(err) {
11541 for (var i = 0; i < cbs.length; i++) {
11542 state.pendingcb--;
11543 cbs[i](err);
11544 }
11545 });
11546
11547 // Clear buffer
11548 } else {
11549 // Slow case, write chunks one-by-one
11550 while (entry) {
11551 var chunk = entry.chunk;
11552 var encoding = entry.encoding;
11553 var cb = entry.callback;
11554 var len = state.objectMode ? 1 : chunk.length;
11555
11556 doWrite(stream, state, false, len, chunk, encoding, cb);
11557 entry = entry.next;
11558 // if we didn't call the onwrite immediately, then
11559 // it means that we need to wait until it does.
11560 // also, that means that the chunk and cb are currently
11561 // being processed, so move the buffer counter past them.
11562 if (state.writing) {
11563 break;
11564 }
11565 }
11566
11567 if (entry === null)
11568 state.lastBufferedRequest = null;
11569 }
11570 state.bufferedRequest = entry;
11571 state.bufferProcessing = false;
11572}
11573
11574Writable.prototype._write = function(chunk, encoding, cb) {
11575 cb(new Error('not implemented'));
11576};
11577
11578Writable.prototype._writev = null;
11579
11580Writable.prototype.end = function(chunk, encoding, cb) {
11581 var state = this._writableState;
11582
11583 if (typeof chunk === 'function') {
11584 cb = chunk;
11585 chunk = null;
11586 encoding = null;
11587 } else if (typeof encoding === 'function') {
11588 cb = encoding;
11589 encoding = null;
11590 }
11591
11592 if (chunk !== null && chunk !== undefined)
11593 this.write(chunk, encoding);
11594
11595 // .end() fully uncorks
11596 if (state.corked) {
11597 state.corked = 1;
11598 this.uncork();
11599 }
11600
11601 // ignore unnecessary end() calls.
11602 if (!state.ending && !state.finished)
11603 endWritable(this, state, cb);
11604};
11605
11606
11607function needFinish(state) {
11608 return (state.ending &&
11609 state.length === 0 &&
11610 state.bufferedRequest === null &&
11611 !state.finished &&
11612 !state.writing);
11613}
11614
11615function prefinish(stream, state) {
11616 if (!state.prefinished) {
11617 state.prefinished = true;
11618 stream.emit('prefinish');
11619 }
11620}
11621
11622function finishMaybe(stream, state) {
11623 var need = needFinish(state);
11624 if (need) {
11625 if (state.pendingcb === 0) {
11626 prefinish(stream, state);
11627 state.finished = true;
11628 stream.emit('finish');
11629 } else {
11630 prefinish(stream, state);
11631 }
11632 }
11633 return need;
11634}
11635
11636function endWritable(stream, state, cb) {
11637 state.ending = true;
11638 finishMaybe(stream, state);
11639 if (cb) {
11640 if (state.finished)
11641 processNextTick(cb);
11642 else
11643 stream.once('finish', cb);
11644 }
11645 state.ended = true;
11646}
11647}, {"process-nextick-args":56,"buffer":29,"core-util-is":58,"inherits":53,"util-deprecate":61,"events":3,"./_stream_duplex":59}],61: [function (exports, require, module, global) {
11648/**
11649 * Module exports.
11650 */
11651
11652module.exports = deprecate;
11653
11654/**
11655 * Mark that a method should not be used.
11656 * Returns a modified function which warns once by default.
11657 *
11658 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
11659 *
11660 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
11661 * will throw an Error when invoked.
11662 *
11663 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
11664 * will invoke `console.trace()` instead of `console.error()`.
11665 *
11666 * @param {Function} fn - the function to deprecate
11667 * @param {String} msg - the string to print to the console when `fn` is invoked
11668 * @returns {Function} a new "deprecated" version of `fn`
11669 * @api public
11670 */
11671
11672function deprecate (fn, msg) {
11673 if (config('noDeprecation')) {
11674 return fn;
11675 }
11676
11677 var warned = false;
11678 function deprecated() {
11679 if (!warned) {
11680 if (config('throwDeprecation')) {
11681 throw new Error(msg);
11682 } else if (config('traceDeprecation')) {
11683 console.trace(msg);
11684 } else {
11685 console.warn(msg);
11686 }
11687 warned = true;
11688 }
11689 return fn.apply(this, arguments);
11690 }
11691
11692 return deprecated;
11693}
11694
11695/**
11696 * Checks `localStorage` for boolean values for the given `name`.
11697 *
11698 * @param {String} name
11699 * @returns {Boolean}
11700 * @api private
11701 */
11702
11703function config (name) {
11704 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
11705 try {
11706 if (!global.localStorage) return false;
11707 } catch (_) {
11708 return false;
11709 }
11710 var val = global.localStorage[name];
11711 if (null == val) return false;
11712 return String(val).toLowerCase() === 'true';
11713}
11714}, {}],62: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
11715//
11716// Permission is hereby granted, free of charge, to any person obtaining a
11717// copy of this software and associated documentation files (the
11718// "Software"), to deal in the Software without restriction, including
11719// without limitation the rights to use, copy, modify, merge, publish,
11720// distribute, sublicense, and/or sell copies of the Software, and to permit
11721// persons to whom the Software is furnished to do so, subject to the
11722// following conditions:
11723//
11724// The above copyright notice and this permission notice shall be included
11725// in all copies or substantial portions of the Software.
11726//
11727// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11728// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11729// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11730// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11731// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11732// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11733// USE OR OTHER DEALINGS IN THE SOFTWARE.
11734
11735var Buffer = require('buffer').Buffer;
11736
11737var isBufferEncoding = Buffer.isEncoding
11738 || function(encoding) {
11739 switch (encoding && encoding.toLowerCase()) {
11740 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
11741 default: return false;
11742 }
11743 }
11744
11745
11746function assertEncoding(encoding) {
11747 if (encoding && !isBufferEncoding(encoding)) {
11748 throw new Error('Unknown encoding: ' + encoding);
11749 }
11750}
11751
11752// StringDecoder provides an interface for efficiently splitting a series of
11753// buffers into a series of JS strings without breaking apart multi-byte
11754// characters. CESU-8 is handled as part of the UTF-8 encoding.
11755//
11756// @TODO Handling all encodings inside a single object makes it very difficult
11757// to reason about this code, so it should be split up in the future.
11758// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
11759// points as used by CESU-8.
11760var StringDecoder = exports.StringDecoder = function(encoding) {
11761 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
11762 assertEncoding(encoding);
11763 switch (this.encoding) {
11764 case 'utf8':
11765 // CESU-8 represents each of Surrogate Pair by 3-bytes
11766 this.surrogateSize = 3;
11767 break;
11768 case 'ucs2':
11769 case 'utf16le':
11770 // UTF-16 represents each of Surrogate Pair by 2-bytes
11771 this.surrogateSize = 2;
11772 this.detectIncompleteChar = utf16DetectIncompleteChar;
11773 break;
11774 case 'base64':
11775 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
11776 this.surrogateSize = 3;
11777 this.detectIncompleteChar = base64DetectIncompleteChar;
11778 break;
11779 default:
11780 this.write = passThroughWrite;
11781 return;
11782 }
11783
11784 // Enough space to store all bytes of a single character. UTF-8 needs 4
11785 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
11786 this.charBuffer = new Buffer(6);
11787 // Number of bytes received for the current incomplete multi-byte character.
11788 this.charReceived = 0;
11789 // Number of bytes expected for the current incomplete multi-byte character.
11790 this.charLength = 0;
11791};
11792
11793
11794// write decodes the given buffer and returns it as JS string that is
11795// guaranteed to not contain any partial multi-byte characters. Any partial
11796// character found at the end of the buffer is buffered up, and will be
11797// returned when calling write again with the remaining bytes.
11798//
11799// Note: Converting a Buffer containing an orphan surrogate to a String
11800// currently works, but converting a String to a Buffer (via `new Buffer`, or
11801// Buffer#write) will replace incomplete surrogates with the unicode
11802// replacement character. See https://codereview.chromium.org/121173009/ .
11803StringDecoder.prototype.write = function(buffer) {
11804 var charStr = '';
11805 // if our last write ended with an incomplete multibyte character
11806 while (this.charLength) {
11807 // determine how many remaining bytes this buffer has to offer for this char
11808 var available = (buffer.length >= this.charLength - this.charReceived) ?
11809 this.charLength - this.charReceived :
11810 buffer.length;
11811
11812 // add the new bytes to the char buffer
11813 buffer.copy(this.charBuffer, this.charReceived, 0, available);
11814 this.charReceived += available;
11815
11816 if (this.charReceived < this.charLength) {
11817 // still not enough chars in this buffer? wait for more ...
11818 return '';
11819 }
11820
11821 // remove bytes belonging to the current character from the buffer
11822 buffer = buffer.slice(available, buffer.length);
11823
11824 // get the character that was split
11825 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
11826
11827 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
11828 var charCode = charStr.charCodeAt(charStr.length - 1);
11829 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
11830 this.charLength += this.surrogateSize;
11831 charStr = '';
11832 continue;
11833 }
11834 this.charReceived = this.charLength = 0;
11835
11836 // if there are no more bytes in this buffer, just emit our char
11837 if (buffer.length === 0) {
11838 return charStr;
11839 }
11840 break;
11841 }
11842
11843 // determine and set charLength / charReceived
11844 this.detectIncompleteChar(buffer);
11845
11846 var end = buffer.length;
11847 if (this.charLength) {
11848 // buffer the incomplete character bytes we got
11849 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
11850 end -= this.charReceived;
11851 }
11852
11853 charStr += buffer.toString(this.encoding, 0, end);
11854
11855 var end = charStr.length - 1;
11856 var charCode = charStr.charCodeAt(end);
11857 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
11858 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
11859 var size = this.surrogateSize;
11860 this.charLength += size;
11861 this.charReceived += size;
11862 this.charBuffer.copy(this.charBuffer, size, 0, size);
11863 buffer.copy(this.charBuffer, 0, 0, size);
11864 return charStr.substring(0, end);
11865 }
11866
11867 // or just emit the charStr
11868 return charStr;
11869};
11870
11871// detectIncompleteChar determines if there is an incomplete UTF-8 character at
11872// the end of the given buffer. If so, it sets this.charLength to the byte
11873// length that character, and sets this.charReceived to the number of bytes
11874// that are available for this character.
11875StringDecoder.prototype.detectIncompleteChar = function(buffer) {
11876 // determine how many bytes we have to check at the end of this buffer
11877 var i = (buffer.length >= 3) ? 3 : buffer.length;
11878
11879 // Figure out if one of the last i bytes of our buffer announces an
11880 // incomplete char.
11881 for (; i > 0; i--) {
11882 var c = buffer[buffer.length - i];
11883
11884 // See http://en.wikipedia.org/wiki/UTF-8#Description
11885
11886 // 110XXXXX
11887 if (i == 1 && c >> 5 == 0x06) {
11888 this.charLength = 2;
11889 break;
11890 }
11891
11892 // 1110XXXX
11893 if (i <= 2 && c >> 4 == 0x0E) {
11894 this.charLength = 3;
11895 break;
11896 }
11897
11898 // 11110XXX
11899 if (i <= 3 && c >> 3 == 0x1E) {
11900 this.charLength = 4;
11901 break;
11902 }
11903 }
11904 this.charReceived = i;
11905};
11906
11907StringDecoder.prototype.end = function(buffer) {
11908 var res = '';
11909 if (buffer && buffer.length)
11910 res = this.write(buffer);
11911
11912 if (this.charReceived) {
11913 var cr = this.charReceived;
11914 var buf = this.charBuffer;
11915 var enc = this.encoding;
11916 res += buf.slice(0, cr).toString(enc);
11917 }
11918
11919 return res;
11920};
11921
11922function passThroughWrite(buffer) {
11923 return buffer.toString(this.encoding);
11924}
11925
11926function utf16DetectIncompleteChar(buffer) {
11927 this.charReceived = buffer.length % 2;
11928 this.charLength = this.charReceived ? 2 : 0;
11929}
11930
11931function base64DetectIncompleteChar(buffer) {
11932 this.charReceived = buffer.length % 3;
11933 this.charLength = this.charReceived ? 3 : 0;
11934}
11935}, {"buffer":29}],63: [function (exports, require, module, global) {// a transform stream is a readable/writable stream where you do
11936// something with the data. Sometimes it's called a "filter",
11937// but that's not a great name for it, since that implies a thing where
11938// some bits pass through, and others are simply ignored. (That would
11939// be a valid example of a transform, of course.)
11940//
11941// While the output is causally related to the input, it's not a
11942// necessarily symmetric or synchronous transformation. For example,
11943// a zlib stream might take multiple plain-text writes(), and then
11944// emit a single compressed chunk some time in the future.
11945//
11946// Here's how this works:
11947//
11948// The Transform stream has all the aspects of the readable and writable
11949// stream classes. When you write(chunk), that calls _write(chunk,cb)
11950// internally, and returns false if there's a lot of pending writes
11951// buffered up. When you call read(), that calls _read(n) until
11952// there's enough pending readable data buffered up.
11953//
11954// In a transform stream, the written data is placed in a buffer. When
11955// _read(n) is called, it transforms the queued up data, calling the
11956// buffered _write cb's as it consumes chunks. If consuming a single
11957// written chunk would result in multiple output chunks, then the first
11958// outputted bit calls the readcb, and subsequent chunks just go into
11959// the read buffer, and will cause it to emit 'readable' if necessary.
11960//
11961// This way, back-pressure is actually determined by the reading side,
11962// since _read has to be called to start processing a new chunk. However,
11963// a pathological inflate type of transform can cause excessive buffering
11964// here. For example, imagine a stream where every byte of input is
11965// interpreted as an integer from 0-255, and then results in that many
11966// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
11967// 1kb of data being output. In this case, you could write a very small
11968// amount of input, and end up with a very large amount of output. In
11969// such a pathological inflating mechanism, there'd be no way to tell
11970// the system to stop doing the transform. A single 4MB write could
11971// cause the system to run out of memory.
11972//
11973// However, even in such a pathological case, only a single written chunk
11974// would be consumed, and then the rest would wait (un-transformed) until
11975// the results of the previous transformed chunk were consumed.
11976
11977'use strict';
11978
11979module.exports = Transform;
11980
11981var Duplex = require('./_stream_duplex');
11982
11983/*<replacement>*/
11984var util = require('core-util-is');
11985util.inherits = require('inherits');
11986/*</replacement>*/
11987
11988util.inherits(Transform, Duplex);
11989
11990
11991function TransformState(stream) {
11992 this.afterTransform = function(er, data) {
11993 return afterTransform(stream, er, data);
11994 };
11995
11996 this.needTransform = false;
11997 this.transforming = false;
11998 this.writecb = null;
11999 this.writechunk = null;
12000}
12001
12002function afterTransform(stream, er, data) {
12003 var ts = stream._transformState;
12004 ts.transforming = false;
12005
12006 var cb = ts.writecb;
12007
12008 if (!cb)
12009 return stream.emit('error', new Error('no writecb in Transform class'));
12010
12011 ts.writechunk = null;
12012 ts.writecb = null;
12013
12014 if (data !== null && data !== undefined)
12015 stream.push(data);
12016
12017 if (cb)
12018 cb(er);
12019
12020 var rs = stream._readableState;
12021 rs.reading = false;
12022 if (rs.needReadable || rs.length < rs.highWaterMark) {
12023 stream._read(rs.highWaterMark);
12024 }
12025}
12026
12027
12028function Transform(options) {
12029 if (!(this instanceof Transform))
12030 return new Transform(options);
12031
12032 Duplex.call(this, options);
12033
12034 this._transformState = new TransformState(this);
12035
12036 // when the writable side finishes, then flush out anything remaining.
12037 var stream = this;
12038
12039 // start out asking for a readable event once data is transformed.
12040 this._readableState.needReadable = true;
12041
12042 // we have implemented the _read method, and done the other things
12043 // that Readable wants before the first _read call, so unset the
12044 // sync guard flag.
12045 this._readableState.sync = false;
12046
12047 if (options) {
12048 if (typeof options.transform === 'function')
12049 this._transform = options.transform;
12050
12051 if (typeof options.flush === 'function')
12052 this._flush = options.flush;
12053 }
12054
12055 this.once('prefinish', function() {
12056 if (typeof this._flush === 'function')
12057 this._flush(function(er) {
12058 done(stream, er);
12059 });
12060 else
12061 done(stream);
12062 });
12063}
12064
12065Transform.prototype.push = function(chunk, encoding) {
12066 this._transformState.needTransform = false;
12067 return Duplex.prototype.push.call(this, chunk, encoding);
12068};
12069
12070// This is the part where you do stuff!
12071// override this function in implementation classes.
12072// 'chunk' is an input chunk.
12073//
12074// Call `push(newChunk)` to pass along transformed output
12075// to the readable side. You may call 'push' zero or more times.
12076//
12077// Call `cb(err)` when you are done with this chunk. If you pass
12078// an error, then that'll put the hurt on the whole operation. If you
12079// never call cb(), then you'll never get another chunk.
12080Transform.prototype._transform = function(chunk, encoding, cb) {
12081 throw new Error('not implemented');
12082};
12083
12084Transform.prototype._write = function(chunk, encoding, cb) {
12085 var ts = this._transformState;
12086 ts.writecb = cb;
12087 ts.writechunk = chunk;
12088 ts.writeencoding = encoding;
12089 if (!ts.transforming) {
12090 var rs = this._readableState;
12091 if (ts.needTransform ||
12092 rs.needReadable ||
12093 rs.length < rs.highWaterMark)
12094 this._read(rs.highWaterMark);
12095 }
12096};
12097
12098// Doesn't matter what the args are here.
12099// _transform does all the work.
12100// That we got here means that the readable side wants more data.
12101Transform.prototype._read = function(n) {
12102 var ts = this._transformState;
12103
12104 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
12105 ts.transforming = true;
12106 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12107 } else {
12108 // mark that we need a transform, so that any data that comes in
12109 // will get processed, now that we've asked for it.
12110 ts.needTransform = true;
12111 }
12112};
12113
12114
12115function done(stream, er) {
12116 if (er)
12117 return stream.emit('error', er);
12118
12119 // if there's nothing in the write buffer, then that means
12120 // that nothing more will ever be provided
12121 var ws = stream._writableState;
12122 var ts = stream._transformState;
12123
12124 if (ws.length)
12125 throw new Error('calling transform done when ws.length != 0');
12126
12127 if (ts.transforming)
12128 throw new Error('calling transform done when still transforming');
12129
12130 return stream.push(null);
12131}
12132}, {"./_stream_duplex":59,"core-util-is":58,"inherits":53}],64: [function (exports, require, module, global) {// a passthrough stream.
12133// basically just the most minimal sort of Transform stream.
12134// Every written chunk gets output as-is.
12135
12136'use strict';
12137
12138module.exports = PassThrough;
12139
12140var Transform = require('./_stream_transform');
12141
12142/*<replacement>*/
12143var util = require('core-util-is');
12144util.inherits = require('inherits');
12145/*</replacement>*/
12146
12147util.inherits(PassThrough, Transform);
12148
12149function PassThrough(options) {
12150 if (!(this instanceof PassThrough))
12151 return new PassThrough(options);
12152
12153 Transform.call(this, options);
12154}
12155
12156PassThrough.prototype._transform = function(chunk, encoding, cb) {
12157 cb(null, chunk);
12158};
12159}, {"./_stream_transform":63,"core-util-is":58,"inherits":53}],65: [function (exports, require, module, global) {module.exports = require("./lib/_stream_writable.js")
12160}, {"./lib/_stream_writable.js":60}],66: [function (exports, require, module, global) {module.exports = require("./lib/_stream_duplex.js")
12161}, {"./lib/_stream_duplex.js":59}],67: [function (exports, require, module, global) {module.exports = require("./lib/_stream_transform.js")
12162}, {"./lib/_stream_transform.js":63}],68: [function (exports, require, module, global) {module.exports = require("./lib/_stream_passthrough.js")
12163}, {"./lib/_stream_passthrough.js":64}],69: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
12164//
12165// Permission is hereby granted, free of charge, to any person obtaining a
12166// copy of this software and associated documentation files (the
12167// "Software"), to deal in the Software without restriction, including
12168// without limitation the rights to use, copy, modify, merge, publish,
12169// distribute, sublicense, and/or sell copies of the Software, and to permit
12170// persons to whom the Software is furnished to do so, subject to the
12171// following conditions:
12172//
12173// The above copyright notice and this permission notice shall be included
12174// in all copies or substantial portions of the Software.
12175//
12176// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12177// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12178// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12179// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12180// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12181// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12182// USE OR OTHER DEALINGS IN THE SOFTWARE.
12183
12184module.exports = Readable;
12185
12186/*<replacement>*/
12187var isArray = require('isarray');
12188/*</replacement>*/
12189
12190
12191/*<replacement>*/
12192var Buffer = require('buffer').Buffer;
12193/*</replacement>*/
12194
12195Readable.ReadableState = ReadableState;
12196
12197var EE = require('events').EventEmitter;
12198
12199/*<replacement>*/
12200if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
12201 return emitter.listeners(type).length;
12202};
12203/*</replacement>*/
12204
12205var Stream = require('stream');
12206
12207/*<replacement>*/
12208var util = require('core-util-is');
12209util.inherits = require('inherits');
12210/*</replacement>*/
12211
12212var StringDecoder;
12213
12214util.inherits(Readable, Stream);
12215
12216function ReadableState(options, stream) {
12217 options = options || {};
12218
12219 // the point at which it stops calling _read() to fill the buffer
12220 // Note: 0 is a valid value, means "don't call _read preemptively ever"
12221 var hwm = options.highWaterMark;
12222 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
12223
12224 // cast to ints.
12225 this.highWaterMark = ~~this.highWaterMark;
12226
12227 this.buffer = [];
12228 this.length = 0;
12229 this.pipes = null;
12230 this.pipesCount = 0;
12231 this.flowing = false;
12232 this.ended = false;
12233 this.endEmitted = false;
12234 this.reading = false;
12235
12236 // In streams that never have any data, and do push(null) right away,
12237 // the consumer can miss the 'end' event if they do some I/O before
12238 // consuming the stream. So, we don't emit('end') until some reading
12239 // happens.
12240 this.calledRead = false;
12241
12242 // a flag to be able to tell if the onwrite cb is called immediately,
12243 // or on a later tick. We set this to true at first, becuase any
12244 // actions that shouldn't happen until "later" should generally also
12245 // not happen before the first write call.
12246 this.sync = true;
12247
12248 // whenever we return null, then we set a flag to say
12249 // that we're awaiting a 'readable' event emission.
12250 this.needReadable = false;
12251 this.emittedReadable = false;
12252 this.readableListening = false;
12253
12254
12255 // object stream flag. Used to make read(n) ignore n and to
12256 // make all the buffer merging and length checks go away
12257 this.objectMode = !!options.objectMode;
12258
12259 // Crypto is kind of old and crusty. Historically, its default string
12260 // encoding is 'binary' so we have to make this configurable.
12261 // Everything else in the universe uses 'utf8', though.
12262 this.defaultEncoding = options.defaultEncoding || 'utf8';
12263
12264 // when piping, we only care about 'readable' events that happen
12265 // after read()ing all the bytes and not getting any pushback.
12266 this.ranOut = false;
12267
12268 // the number of writers that are awaiting a drain event in .pipe()s
12269 this.awaitDrain = 0;
12270
12271 // if true, a maybeReadMore has been scheduled
12272 this.readingMore = false;
12273
12274 this.decoder = null;
12275 this.encoding = null;
12276 if (options.encoding) {
12277 if (!StringDecoder)
12278 StringDecoder = require('string_decoder/').StringDecoder;
12279 this.decoder = new StringDecoder(options.encoding);
12280 this.encoding = options.encoding;
12281 }
12282}
12283
12284function Readable(options) {
12285 if (!(this instanceof Readable))
12286 return new Readable(options);
12287
12288 this._readableState = new ReadableState(options, this);
12289
12290 // legacy
12291 this.readable = true;
12292
12293 Stream.call(this);
12294}
12295
12296// Manually shove something into the read() buffer.
12297// This returns true if the highWaterMark has not been hit yet,
12298// similar to how Writable.write() returns true if you should
12299// write() some more.
12300Readable.prototype.push = function(chunk, encoding) {
12301 var state = this._readableState;
12302
12303 if (typeof chunk === 'string' && !state.objectMode) {
12304 encoding = encoding || state.defaultEncoding;
12305 if (encoding !== state.encoding) {
12306 chunk = new Buffer(chunk, encoding);
12307 encoding = '';
12308 }
12309 }
12310
12311 return readableAddChunk(this, state, chunk, encoding, false);
12312};
12313
12314// Unshift should *always* be something directly out of read()
12315Readable.prototype.unshift = function(chunk) {
12316 var state = this._readableState;
12317 return readableAddChunk(this, state, chunk, '', true);
12318};
12319
12320function readableAddChunk(stream, state, chunk, encoding, addToFront) {
12321 var er = chunkInvalid(state, chunk);
12322 if (er) {
12323 stream.emit('error', er);
12324 } else if (chunk === null || chunk === undefined) {
12325 state.reading = false;
12326 if (!state.ended)
12327 onEofChunk(stream, state);
12328 } else if (state.objectMode || chunk && chunk.length > 0) {
12329 if (state.ended && !addToFront) {
12330 var e = new Error('stream.push() after EOF');
12331 stream.emit('error', e);
12332 } else if (state.endEmitted && addToFront) {
12333 var e = new Error('stream.unshift() after end event');
12334 stream.emit('error', e);
12335 } else {
12336 if (state.decoder && !addToFront && !encoding)
12337 chunk = state.decoder.write(chunk);
12338
12339 // update the buffer info.
12340 state.length += state.objectMode ? 1 : chunk.length;
12341 if (addToFront) {
12342 state.buffer.unshift(chunk);
12343 } else {
12344 state.reading = false;
12345 state.buffer.push(chunk);
12346 }
12347
12348 if (state.needReadable)
12349 emitReadable(stream);
12350
12351 maybeReadMore(stream, state);
12352 }
12353 } else if (!addToFront) {
12354 state.reading = false;
12355 }
12356
12357 return needMoreData(state);
12358}
12359
12360
12361
12362// if it's past the high water mark, we can push in some more.
12363// Also, if we have no data yet, we can stand some
12364// more bytes. This is to work around cases where hwm=0,
12365// such as the repl. Also, if the push() triggered a
12366// readable event, and the user called read(largeNumber) such that
12367// needReadable was set, then we ought to push more, so that another
12368// 'readable' event will be triggered.
12369function needMoreData(state) {
12370 return !state.ended &&
12371 (state.needReadable ||
12372 state.length < state.highWaterMark ||
12373 state.length === 0);
12374}
12375
12376// backwards compatibility.
12377Readable.prototype.setEncoding = function(enc) {
12378 if (!StringDecoder)
12379 StringDecoder = require('string_decoder/').StringDecoder;
12380 this._readableState.decoder = new StringDecoder(enc);
12381 this._readableState.encoding = enc;
12382};
12383
12384// Don't raise the hwm > 128MB
12385var MAX_HWM = 0x800000;
12386function roundUpToNextPowerOf2(n) {
12387 if (n >= MAX_HWM) {
12388 n = MAX_HWM;
12389 } else {
12390 // Get the next highest power of 2
12391 n--;
12392 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
12393 n++;
12394 }
12395 return n;
12396}
12397
12398function howMuchToRead(n, state) {
12399 if (state.length === 0 && state.ended)
12400 return 0;
12401
12402 if (state.objectMode)
12403 return n === 0 ? 0 : 1;
12404
12405 if (n === null || isNaN(n)) {
12406 // only flow one buffer at a time
12407 if (state.flowing && state.buffer.length)
12408 return state.buffer[0].length;
12409 else
12410 return state.length;
12411 }
12412
12413 if (n <= 0)
12414 return 0;
12415
12416 // If we're asking for more than the target buffer level,
12417 // then raise the water mark. Bump up to the next highest
12418 // power of 2, to prevent increasing it excessively in tiny
12419 // amounts.
12420 if (n > state.highWaterMark)
12421 state.highWaterMark = roundUpToNextPowerOf2(n);
12422
12423 // don't have that much. return null, unless we've ended.
12424 if (n > state.length) {
12425 if (!state.ended) {
12426 state.needReadable = true;
12427 return 0;
12428 } else
12429 return state.length;
12430 }
12431
12432 return n;
12433}
12434
12435// you can override either this method, or the async _read(n) below.
12436Readable.prototype.read = function(n) {
12437 var state = this._readableState;
12438 state.calledRead = true;
12439 var nOrig = n;
12440 var ret;
12441
12442 if (typeof n !== 'number' || n > 0)
12443 state.emittedReadable = false;
12444
12445 // if we're doing read(0) to trigger a readable event, but we
12446 // already have a bunch of data in the buffer, then just trigger
12447 // the 'readable' event and move on.
12448 if (n === 0 &&
12449 state.needReadable &&
12450 (state.length >= state.highWaterMark || state.ended)) {
12451 emitReadable(this);
12452 return null;
12453 }
12454
12455 n = howMuchToRead(n, state);
12456
12457 // if we've ended, and we're now clear, then finish it up.
12458 if (n === 0 && state.ended) {
12459 ret = null;
12460
12461 // In cases where the decoder did not receive enough data
12462 // to produce a full chunk, then immediately received an
12463 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
12464 // howMuchToRead will see this and coerce the amount to
12465 // read to zero (because it's looking at the length of the
12466 // first <Buffer > in state.buffer), and we'll end up here.
12467 //
12468 // This can only happen via state.decoder -- no other venue
12469 // exists for pushing a zero-length chunk into state.buffer
12470 // and triggering this behavior. In this case, we return our
12471 // remaining data and end the stream, if appropriate.
12472 if (state.length > 0 && state.decoder) {
12473 ret = fromList(n, state);
12474 state.length -= ret.length;
12475 }
12476
12477 if (state.length === 0)
12478 endReadable(this);
12479
12480 return ret;
12481 }
12482
12483 // All the actual chunk generation logic needs to be
12484 // *below* the call to _read. The reason is that in certain
12485 // synthetic stream cases, such as passthrough streams, _read
12486 // may be a completely synchronous operation which may change
12487 // the state of the read buffer, providing enough data when
12488 // before there was *not* enough.
12489 //
12490 // So, the steps are:
12491 // 1. Figure out what the state of things will be after we do
12492 // a read from the buffer.
12493 //
12494 // 2. If that resulting state will trigger a _read, then call _read.
12495 // Note that this may be asynchronous, or synchronous. Yes, it is
12496 // deeply ugly to write APIs this way, but that still doesn't mean
12497 // that the Readable class should behave improperly, as streams are
12498 // designed to be sync/async agnostic.
12499 // Take note if the _read call is sync or async (ie, if the read call
12500 // has returned yet), so that we know whether or not it's safe to emit
12501 // 'readable' etc.
12502 //
12503 // 3. Actually pull the requested chunks out of the buffer and return.
12504
12505 // if we need a readable event, then we need to do some reading.
12506 var doRead = state.needReadable;
12507
12508 // if we currently have less than the highWaterMark, then also read some
12509 if (state.length - n <= state.highWaterMark)
12510 doRead = true;
12511
12512 // however, if we've ended, then there's no point, and if we're already
12513 // reading, then it's unnecessary.
12514 if (state.ended || state.reading)
12515 doRead = false;
12516
12517 if (doRead) {
12518 state.reading = true;
12519 state.sync = true;
12520 // if the length is currently zero, then we *need* a readable event.
12521 if (state.length === 0)
12522 state.needReadable = true;
12523 // call internal read method
12524 this._read(state.highWaterMark);
12525 state.sync = false;
12526 }
12527
12528 // If _read called its callback synchronously, then `reading`
12529 // will be false, and we need to re-evaluate how much data we
12530 // can return to the user.
12531 if (doRead && !state.reading)
12532 n = howMuchToRead(nOrig, state);
12533
12534 if (n > 0)
12535 ret = fromList(n, state);
12536 else
12537 ret = null;
12538
12539 if (ret === null) {
12540 state.needReadable = true;
12541 n = 0;
12542 }
12543
12544 state.length -= n;
12545
12546 // If we have nothing in the buffer, then we want to know
12547 // as soon as we *do* get something into the buffer.
12548 if (state.length === 0 && !state.ended)
12549 state.needReadable = true;
12550
12551 // If we happened to read() exactly the remaining amount in the
12552 // buffer, and the EOF has been seen at this point, then make sure
12553 // that we emit 'end' on the very next tick.
12554 if (state.ended && !state.endEmitted && state.length === 0)
12555 endReadable(this);
12556
12557 return ret;
12558};
12559
12560function chunkInvalid(state, chunk) {
12561 var er = null;
12562 if (!Buffer.isBuffer(chunk) &&
12563 'string' !== typeof chunk &&
12564 chunk !== null &&
12565 chunk !== undefined &&
12566 !state.objectMode) {
12567 er = new TypeError('Invalid non-string/buffer chunk');
12568 }
12569 return er;
12570}
12571
12572
12573function onEofChunk(stream, state) {
12574 if (state.decoder && !state.ended) {
12575 var chunk = state.decoder.end();
12576 if (chunk && chunk.length) {
12577 state.buffer.push(chunk);
12578 state.length += state.objectMode ? 1 : chunk.length;
12579 }
12580 }
12581 state.ended = true;
12582
12583 // if we've ended and we have some data left, then emit
12584 // 'readable' now to make sure it gets picked up.
12585 if (state.length > 0)
12586 emitReadable(stream);
12587 else
12588 endReadable(stream);
12589}
12590
12591// Don't emit readable right away in sync mode, because this can trigger
12592// another read() call => stack overflow. This way, it might trigger
12593// a nextTick recursion warning, but that's not so bad.
12594function emitReadable(stream) {
12595 var state = stream._readableState;
12596 state.needReadable = false;
12597 if (state.emittedReadable)
12598 return;
12599
12600 state.emittedReadable = true;
12601 if (state.sync)
12602 process.nextTick(function() {
12603 emitReadable_(stream);
12604 });
12605 else
12606 emitReadable_(stream);
12607}
12608
12609function emitReadable_(stream) {
12610 stream.emit('readable');
12611}
12612
12613
12614// at this point, the user has presumably seen the 'readable' event,
12615// and called read() to consume some data. that may have triggered
12616// in turn another _read(n) call, in which case reading = true if
12617// it's in progress.
12618// However, if we're not ended, or reading, and the length < hwm,
12619// then go ahead and try to read some more preemptively.
12620function maybeReadMore(stream, state) {
12621 if (!state.readingMore) {
12622 state.readingMore = true;
12623 process.nextTick(function() {
12624 maybeReadMore_(stream, state);
12625 });
12626 }
12627}
12628
12629function maybeReadMore_(stream, state) {
12630 var len = state.length;
12631 while (!state.reading && !state.flowing && !state.ended &&
12632 state.length < state.highWaterMark) {
12633 stream.read(0);
12634 if (len === state.length)
12635 // didn't get any data, stop spinning.
12636 break;
12637 else
12638 len = state.length;
12639 }
12640 state.readingMore = false;
12641}
12642
12643// abstract method. to be overridden in specific implementation classes.
12644// call cb(er, data) where data is <= n in length.
12645// for virtual (non-string, non-buffer) streams, "length" is somewhat
12646// arbitrary, and perhaps not very meaningful.
12647Readable.prototype._read = function(n) {
12648 this.emit('error', new Error('not implemented'));
12649};
12650
12651Readable.prototype.pipe = function(dest, pipeOpts) {
12652 var src = this;
12653 var state = this._readableState;
12654
12655 switch (state.pipesCount) {
12656 case 0:
12657 state.pipes = dest;
12658 break;
12659 case 1:
12660 state.pipes = [state.pipes, dest];
12661 break;
12662 default:
12663 state.pipes.push(dest);
12664 break;
12665 }
12666 state.pipesCount += 1;
12667
12668 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12669 dest !== process.stdout &&
12670 dest !== process.stderr;
12671
12672 var endFn = doEnd ? onend : cleanup;
12673 if (state.endEmitted)
12674 process.nextTick(endFn);
12675 else
12676 src.once('end', endFn);
12677
12678 dest.on('unpipe', onunpipe);
12679 function onunpipe(readable) {
12680 if (readable !== src) return;
12681 cleanup();
12682 }
12683
12684 function onend() {
12685 dest.end();
12686 }
12687
12688 // when the dest drains, it reduces the awaitDrain counter
12689 // on the source. This would be more elegant with a .once()
12690 // handler in flow(), but adding and removing repeatedly is
12691 // too slow.
12692 var ondrain = pipeOnDrain(src);
12693 dest.on('drain', ondrain);
12694
12695 function cleanup() {
12696 // cleanup event handlers once the pipe is broken
12697 dest.removeListener('close', onclose);
12698 dest.removeListener('finish', onfinish);
12699 dest.removeListener('drain', ondrain);
12700 dest.removeListener('error', onerror);
12701 dest.removeListener('unpipe', onunpipe);
12702 src.removeListener('end', onend);
12703 src.removeListener('end', cleanup);
12704
12705 // if the reader is waiting for a drain event from this
12706 // specific writer, then it would cause it to never start
12707 // flowing again.
12708 // So, if this is awaiting a drain, then we just call it now.
12709 // If we don't know, then assume that we are waiting for one.
12710 if (!dest._writableState || dest._writableState.needDrain)
12711 ondrain();
12712 }
12713
12714 // if the dest has an error, then stop piping into it.
12715 // however, don't suppress the throwing behavior for this.
12716 function onerror(er) {
12717 unpipe();
12718 dest.removeListener('error', onerror);
12719 if (EE.listenerCount(dest, 'error') === 0)
12720 dest.emit('error', er);
12721 }
12722 // This is a brutally ugly hack to make sure that our error handler
12723 // is attached before any userland ones. NEVER DO THIS.
12724 if (!dest._events || !dest._events.error)
12725 dest.on('error', onerror);
12726 else if (isArray(dest._events.error))
12727 dest._events.error.unshift(onerror);
12728 else
12729 dest._events.error = [onerror, dest._events.error];
12730
12731
12732
12733 // Both close and finish should trigger unpipe, but only once.
12734 function onclose() {
12735 dest.removeListener('finish', onfinish);
12736 unpipe();
12737 }
12738 dest.once('close', onclose);
12739 function onfinish() {
12740 dest.removeListener('close', onclose);
12741 unpipe();
12742 }
12743 dest.once('finish', onfinish);
12744
12745 function unpipe() {
12746 src.unpipe(dest);
12747 }
12748
12749 // tell the dest that it's being piped to
12750 dest.emit('pipe', src);
12751
12752 // start the flow if it hasn't been started already.
12753 if (!state.flowing) {
12754 // the handler that waits for readable events after all
12755 // the data gets sucked out in flow.
12756 // This would be easier to follow with a .once() handler
12757 // in flow(), but that is too slow.
12758 this.on('readable', pipeOnReadable);
12759
12760 state.flowing = true;
12761 process.nextTick(function() {
12762 flow(src);
12763 });
12764 }
12765
12766 return dest;
12767};
12768
12769function pipeOnDrain(src) {
12770 return function() {
12771 var dest = this;
12772 var state = src._readableState;
12773 state.awaitDrain--;
12774 if (state.awaitDrain === 0)
12775 flow(src);
12776 };
12777}
12778
12779function flow(src) {
12780 var state = src._readableState;
12781 var chunk;
12782 state.awaitDrain = 0;
12783
12784 function write(dest, i, list) {
12785 var written = dest.write(chunk);
12786 if (false === written) {
12787 state.awaitDrain++;
12788 }
12789 }
12790
12791 while (state.pipesCount && null !== (chunk = src.read())) {
12792
12793 if (state.pipesCount === 1)
12794 write(state.pipes, 0, null);
12795 else
12796 forEach(state.pipes, write);
12797
12798 src.emit('data', chunk);
12799
12800 // if anyone needs a drain, then we have to wait for that.
12801 if (state.awaitDrain > 0)
12802 return;
12803 }
12804
12805 // if every destination was unpiped, either before entering this
12806 // function, or in the while loop, then stop flowing.
12807 //
12808 // NB: This is a pretty rare edge case.
12809 if (state.pipesCount === 0) {
12810 state.flowing = false;
12811
12812 // if there were data event listeners added, then switch to old mode.
12813 if (EE.listenerCount(src, 'data') > 0)
12814 emitDataEvents(src);
12815 return;
12816 }
12817
12818 // at this point, no one needed a drain, so we just ran out of data
12819 // on the next readable event, start it over again.
12820 state.ranOut = true;
12821}
12822
12823function pipeOnReadable() {
12824 if (this._readableState.ranOut) {
12825 this._readableState.ranOut = false;
12826 flow(this);
12827 }
12828}
12829
12830
12831Readable.prototype.unpipe = function(dest) {
12832 var state = this._readableState;
12833
12834 // if we're not piping anywhere, then do nothing.
12835 if (state.pipesCount === 0)
12836 return this;
12837
12838 // just one destination. most common case.
12839 if (state.pipesCount === 1) {
12840 // passed in one, but it's not the right one.
12841 if (dest && dest !== state.pipes)
12842 return this;
12843
12844 if (!dest)
12845 dest = state.pipes;
12846
12847 // got a match.
12848 state.pipes = null;
12849 state.pipesCount = 0;
12850 this.removeListener('readable', pipeOnReadable);
12851 state.flowing = false;
12852 if (dest)
12853 dest.emit('unpipe', this);
12854 return this;
12855 }
12856
12857 // slow case. multiple pipe destinations.
12858
12859 if (!dest) {
12860 // remove all.
12861 var dests = state.pipes;
12862 var len = state.pipesCount;
12863 state.pipes = null;
12864 state.pipesCount = 0;
12865 this.removeListener('readable', pipeOnReadable);
12866 state.flowing = false;
12867
12868 for (var i = 0; i < len; i++)
12869 dests[i].emit('unpipe', this);
12870 return this;
12871 }
12872
12873 // try to find the right one.
12874 var i = indexOf(state.pipes, dest);
12875 if (i === -1)
12876 return this;
12877
12878 state.pipes.splice(i, 1);
12879 state.pipesCount -= 1;
12880 if (state.pipesCount === 1)
12881 state.pipes = state.pipes[0];
12882
12883 dest.emit('unpipe', this);
12884
12885 return this;
12886};
12887
12888// set up data events if they are asked for
12889// Ensure readable listeners eventually get something
12890Readable.prototype.on = function(ev, fn) {
12891 var res = Stream.prototype.on.call(this, ev, fn);
12892
12893 if (ev === 'data' && !this._readableState.flowing)
12894 emitDataEvents(this);
12895
12896 if (ev === 'readable' && this.readable) {
12897 var state = this._readableState;
12898 if (!state.readableListening) {
12899 state.readableListening = true;
12900 state.emittedReadable = false;
12901 state.needReadable = true;
12902 if (!state.reading) {
12903 this.read(0);
12904 } else if (state.length) {
12905 emitReadable(this, state);
12906 }
12907 }
12908 }
12909
12910 return res;
12911};
12912Readable.prototype.addListener = Readable.prototype.on;
12913
12914// pause() and resume() are remnants of the legacy readable stream API
12915// If the user uses them, then switch into old mode.
12916Readable.prototype.resume = function() {
12917 emitDataEvents(this);
12918 this.read(0);
12919 this.emit('resume');
12920};
12921
12922Readable.prototype.pause = function() {
12923 emitDataEvents(this, true);
12924 this.emit('pause');
12925};
12926
12927function emitDataEvents(stream, startPaused) {
12928 var state = stream._readableState;
12929
12930 if (state.flowing) {
12931 // https://github.com/isaacs/readable-stream/issues/16
12932 throw new Error('Cannot switch to old mode now.');
12933 }
12934
12935 var paused = startPaused || false;
12936 var readable = false;
12937
12938 // convert to an old-style stream.
12939 stream.readable = true;
12940 stream.pipe = Stream.prototype.pipe;
12941 stream.on = stream.addListener = Stream.prototype.on;
12942
12943 stream.on('readable', function() {
12944 readable = true;
12945
12946 var c;
12947 while (!paused && (null !== (c = stream.read())))
12948 stream.emit('data', c);
12949
12950 if (c === null) {
12951 readable = false;
12952 stream._readableState.needReadable = true;
12953 }
12954 });
12955
12956 stream.pause = function() {
12957 paused = true;
12958 this.emit('pause');
12959 };
12960
12961 stream.resume = function() {
12962 paused = false;
12963 if (readable)
12964 process.nextTick(function() {
12965 stream.emit('readable');
12966 });
12967 else
12968 this.read(0);
12969 this.emit('resume');
12970 };
12971
12972 // now make it start, just in case it hadn't already.
12973 stream.emit('readable');
12974}
12975
12976// wrap an old-style stream as the async data source.
12977// This is *not* part of the readable stream interface.
12978// It is an ugly unfortunate mess of history.
12979Readable.prototype.wrap = function(stream) {
12980 var state = this._readableState;
12981 var paused = false;
12982
12983 var self = this;
12984 stream.on('end', function() {
12985 if (state.decoder && !state.ended) {
12986 var chunk = state.decoder.end();
12987 if (chunk && chunk.length)
12988 self.push(chunk);
12989 }
12990
12991 self.push(null);
12992 });
12993
12994 stream.on('data', function(chunk) {
12995 if (state.decoder)
12996 chunk = state.decoder.write(chunk);
12997
12998 // don't skip over falsy values in objectMode
12999 //if (state.objectMode && util.isNullOrUndefined(chunk))
13000 if (state.objectMode && (chunk === null || chunk === undefined))
13001 return;
13002 else if (!state.objectMode && (!chunk || !chunk.length))
13003 return;
13004
13005 var ret = self.push(chunk);
13006 if (!ret) {
13007 paused = true;
13008 stream.pause();
13009 }
13010 });
13011
13012 // proxy all the other methods.
13013 // important when wrapping filters and duplexes.
13014 for (var i in stream) {
13015 if (typeof stream[i] === 'function' &&
13016 typeof this[i] === 'undefined') {
13017 this[i] = function(method) { return function() {
13018 return stream[method].apply(stream, arguments);
13019 }}(i);
13020 }
13021 }
13022
13023 // proxy certain important events.
13024 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
13025 forEach(events, function(ev) {
13026 stream.on(ev, self.emit.bind(self, ev));
13027 });
13028
13029 // when we try to consume some more bytes, simply unpause the
13030 // underlying stream.
13031 self._read = function(n) {
13032 if (paused) {
13033 paused = false;
13034 stream.resume();
13035 }
13036 };
13037
13038 return self;
13039};
13040
13041
13042
13043// exposed for testing purposes only.
13044Readable._fromList = fromList;
13045
13046// Pluck off n bytes from an array of buffers.
13047// Length is the combined lengths of all the buffers in the list.
13048function fromList(n, state) {
13049 var list = state.buffer;
13050 var length = state.length;
13051 var stringMode = !!state.decoder;
13052 var objectMode = !!state.objectMode;
13053 var ret;
13054
13055 // nothing in the list, definitely empty.
13056 if (list.length === 0)
13057 return null;
13058
13059 if (length === 0)
13060 ret = null;
13061 else if (objectMode)
13062 ret = list.shift();
13063 else if (!n || n >= length) {
13064 // read it all, truncate the array.
13065 if (stringMode)
13066 ret = list.join('');
13067 else
13068 ret = Buffer.concat(list, length);
13069 list.length = 0;
13070 } else {
13071 // read just some of it.
13072 if (n < list[0].length) {
13073 // just take a part of the first list item.
13074 // slice is the same for buffers and strings.
13075 var buf = list[0];
13076 ret = buf.slice(0, n);
13077 list[0] = buf.slice(n);
13078 } else if (n === list[0].length) {
13079 // first list is a perfect match
13080 ret = list.shift();
13081 } else {
13082 // complex case.
13083 // we have enough to cover it, but it spans past the first buffer.
13084 if (stringMode)
13085 ret = '';
13086 else
13087 ret = new Buffer(n);
13088
13089 var c = 0;
13090 for (var i = 0, l = list.length; i < l && c < n; i++) {
13091 var buf = list[0];
13092 var cpy = Math.min(n - c, buf.length);
13093
13094 if (stringMode)
13095 ret += buf.slice(0, cpy);
13096 else
13097 buf.copy(ret, c, 0, cpy);
13098
13099 if (cpy < buf.length)
13100 list[0] = buf.slice(cpy);
13101 else
13102 list.shift();
13103
13104 c += cpy;
13105 }
13106 }
13107 }
13108
13109 return ret;
13110}
13111
13112function endReadable(stream) {
13113 var state = stream._readableState;
13114
13115 // If we get here before consuming all the bytes, then that is a
13116 // bug in node. Should never happen.
13117 if (state.length > 0)
13118 throw new Error('endReadable called on non-empty stream');
13119
13120 if (!state.endEmitted && state.calledRead) {
13121 state.ended = true;
13122 process.nextTick(function() {
13123 // Check that we didn't get one last unshift.
13124 if (!state.endEmitted && state.length === 0) {
13125 state.endEmitted = true;
13126 stream.readable = false;
13127 stream.emit('end');
13128 }
13129 });
13130 }
13131}
13132
13133function forEach (xs, f) {
13134 for (var i = 0, l = xs.length; i < l; i++) {
13135 f(xs[i], i);
13136 }
13137}
13138
13139function indexOf (xs, x) {
13140 for (var i = 0, l = xs.length; i < l; i++) {
13141 if (xs[i] === x) return i;
13142 }
13143 return -1;
13144}
13145}, {"isarray":70,"buffer":29,"events":3,"stream":52,"core-util-is":71,"inherits":72,"string_decoder/":62}],70: [function (exports, require, module, global) {module.exports = Array.isArray || function (arr) {
13146 return Object.prototype.toString.call(arr) == '[object Array]';
13147};
13148}, {}],71: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
13149//
13150// Permission is hereby granted, free of charge, to any person obtaining a
13151// copy of this software and associated documentation files (the
13152// "Software"), to deal in the Software without restriction, including
13153// without limitation the rights to use, copy, modify, merge, publish,
13154// distribute, sublicense, and/or sell copies of the Software, and to permit
13155// persons to whom the Software is furnished to do so, subject to the
13156// following conditions:
13157//
13158// The above copyright notice and this permission notice shall be included
13159// in all copies or substantial portions of the Software.
13160//
13161// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13162// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13163// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13164// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13165// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13166// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13167// USE OR OTHER DEALINGS IN THE SOFTWARE.
13168
13169// NOTE: These type checking functions intentionally don't use `instanceof`
13170// because it is fragile and can be easily faked with `Object.create()`.
13171function isArray(ar) {
13172 return Array.isArray(ar);
13173}
13174exports.isArray = isArray;
13175
13176function isBoolean(arg) {
13177 return typeof arg === 'boolean';
13178}
13179exports.isBoolean = isBoolean;
13180
13181function isNull(arg) {
13182 return arg === null;
13183}
13184exports.isNull = isNull;
13185
13186function isNullOrUndefined(arg) {
13187 return arg == null;
13188}
13189exports.isNullOrUndefined = isNullOrUndefined;
13190
13191function isNumber(arg) {
13192 return typeof arg === 'number';
13193}
13194exports.isNumber = isNumber;
13195
13196function isString(arg) {
13197 return typeof arg === 'string';
13198}
13199exports.isString = isString;
13200
13201function isSymbol(arg) {
13202 return typeof arg === 'symbol';
13203}
13204exports.isSymbol = isSymbol;
13205
13206function isUndefined(arg) {
13207 return arg === void 0;
13208}
13209exports.isUndefined = isUndefined;
13210
13211function isRegExp(re) {
13212 return isObject(re) && objectToString(re) === '[object RegExp]';
13213}
13214exports.isRegExp = isRegExp;
13215
13216function isObject(arg) {
13217 return typeof arg === 'object' && arg !== null;
13218}
13219exports.isObject = isObject;
13220
13221function isDate(d) {
13222 return isObject(d) && objectToString(d) === '[object Date]';
13223}
13224exports.isDate = isDate;
13225
13226function isError(e) {
13227 return isObject(e) &&
13228 (objectToString(e) === '[object Error]' || e instanceof Error);
13229}
13230exports.isError = isError;
13231
13232function isFunction(arg) {
13233 return typeof arg === 'function';
13234}
13235exports.isFunction = isFunction;
13236
13237function isPrimitive(arg) {
13238 return arg === null ||
13239 typeof arg === 'boolean' ||
13240 typeof arg === 'number' ||
13241 typeof arg === 'string' ||
13242 typeof arg === 'symbol' || // ES6 symbol
13243 typeof arg === 'undefined';
13244}
13245exports.isPrimitive = isPrimitive;
13246
13247function isBuffer(arg) {
13248 return Buffer.isBuffer(arg);
13249}
13250exports.isBuffer = isBuffer;
13251
13252function objectToString(o) {
13253 return Object.prototype.toString.call(o);
13254}}, {}],72: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
13255 // implementation from standard node.js 'util' module
13256 module.exports = function inherits(ctor, superCtor) {
13257 ctor.super_ = superCtor
13258 ctor.prototype = Object.create(superCtor.prototype, {
13259 constructor: {
13260 value: ctor,
13261 enumerable: false,
13262 writable: true,
13263 configurable: true
13264 }
13265 });
13266 };
13267} else {
13268 // old school shim for old browsers
13269 module.exports = function inherits(ctor, superCtor) {
13270 ctor.super_ = superCtor
13271 var TempCtor = function () {}
13272 TempCtor.prototype = superCtor.prototype
13273 ctor.prototype = new TempCtor()
13274 ctor.prototype.constructor = ctor
13275 }
13276}
13277}, {}],73: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
13278//
13279// Permission is hereby granted, free of charge, to any person obtaining a
13280// copy of this software and associated documentation files (the
13281// "Software"), to deal in the Software without restriction, including
13282// without limitation the rights to use, copy, modify, merge, publish,
13283// distribute, sublicense, and/or sell copies of the Software, and to permit
13284// persons to whom the Software is furnished to do so, subject to the
13285// following conditions:
13286//
13287// The above copyright notice and this permission notice shall be included
13288// in all copies or substantial portions of the Software.
13289//
13290// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13291// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13292// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13293// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13294// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13295// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13296// USE OR OTHER DEALINGS IN THE SOFTWARE.
13297
13298// A bit simpler than readable streams.
13299// Implement an async ._write(chunk, cb), and it'll handle all
13300// the drain event emission and buffering.
13301
13302module.exports = Writable;
13303
13304/*<replacement>*/
13305var Buffer = require('buffer').Buffer;
13306/*</replacement>*/
13307
13308Writable.WritableState = WritableState;
13309
13310
13311/*<replacement>*/
13312var util = require('core-util-is');
13313util.inherits = require('inherits');
13314/*</replacement>*/
13315
13316var Stream = require('stream');
13317
13318util.inherits(Writable, Stream);
13319
13320function WriteReq(chunk, encoding, cb) {
13321 this.chunk = chunk;
13322 this.encoding = encoding;
13323 this.callback = cb;
13324}
13325
13326function WritableState(options, stream) {
13327 options = options || {};
13328
13329 // the point at which write() starts returning false
13330 // Note: 0 is a valid value, means that we always return false if
13331 // the entire buffer is not flushed immediately on write()
13332 var hwm = options.highWaterMark;
13333 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
13334
13335 // object stream flag to indicate whether or not this stream
13336 // contains buffers or objects.
13337 this.objectMode = !!options.objectMode;
13338
13339 // cast to ints.
13340 this.highWaterMark = ~~this.highWaterMark;
13341
13342 this.needDrain = false;
13343 // at the start of calling end()
13344 this.ending = false;
13345 // when end() has been called, and returned
13346 this.ended = false;
13347 // when 'finish' is emitted
13348 this.finished = false;
13349
13350 // should we decode strings into buffers before passing to _write?
13351 // this is here so that some node-core streams can optimize string
13352 // handling at a lower level.
13353 var noDecode = options.decodeStrings === false;
13354 this.decodeStrings = !noDecode;
13355
13356 // Crypto is kind of old and crusty. Historically, its default string
13357 // encoding is 'binary' so we have to make this configurable.
13358 // Everything else in the universe uses 'utf8', though.
13359 this.defaultEncoding = options.defaultEncoding || 'utf8';
13360
13361 // not an actual buffer we keep track of, but a measurement
13362 // of how much we're waiting to get pushed to some underlying
13363 // socket or file.
13364 this.length = 0;
13365
13366 // a flag to see when we're in the middle of a write.
13367 this.writing = false;
13368
13369 // a flag to be able to tell if the onwrite cb is called immediately,
13370 // or on a later tick. We set this to true at first, becuase any
13371 // actions that shouldn't happen until "later" should generally also
13372 // not happen before the first write call.
13373 this.sync = true;
13374
13375 // a flag to know if we're processing previously buffered items, which
13376 // may call the _write() callback in the same tick, so that we don't
13377 // end up in an overlapped onwrite situation.
13378 this.bufferProcessing = false;
13379
13380 // the callback that's passed to _write(chunk,cb)
13381 this.onwrite = function(er) {
13382 onwrite(stream, er);
13383 };
13384
13385 // the callback that the user supplies to write(chunk,encoding,cb)
13386 this.writecb = null;
13387
13388 // the amount that is being written when _write is called.
13389 this.writelen = 0;
13390
13391 this.buffer = [];
13392
13393 // True if the error was already emitted and should not be thrown again
13394 this.errorEmitted = false;
13395}
13396
13397function Writable(options) {
13398 var Duplex = require('./_stream_duplex');
13399
13400 // Writable ctor is applied to Duplexes, though they're not
13401 // instanceof Writable, they're instanceof Readable.
13402 if (!(this instanceof Writable) && !(this instanceof Duplex))
13403 return new Writable(options);
13404
13405 this._writableState = new WritableState(options, this);
13406
13407 // legacy.
13408 this.writable = true;
13409
13410 Stream.call(this);
13411}
13412
13413// Otherwise people can pipe Writable streams, which is just wrong.
13414Writable.prototype.pipe = function() {
13415 this.emit('error', new Error('Cannot pipe. Not readable.'));
13416};
13417
13418
13419function writeAfterEnd(stream, state, cb) {
13420 var er = new Error('write after end');
13421 // TODO: defer error events consistently everywhere, not just the cb
13422 stream.emit('error', er);
13423 process.nextTick(function() {
13424 cb(er);
13425 });
13426}
13427
13428// If we get something that is not a buffer, string, null, or undefined,
13429// and we're not in objectMode, then that's an error.
13430// Otherwise stream chunks are all considered to be of length=1, and the
13431// watermarks determine how many objects to keep in the buffer, rather than
13432// how many bytes or characters.
13433function validChunk(stream, state, chunk, cb) {
13434 var valid = true;
13435 if (!Buffer.isBuffer(chunk) &&
13436 'string' !== typeof chunk &&
13437 chunk !== null &&
13438 chunk !== undefined &&
13439 !state.objectMode) {
13440 var er = new TypeError('Invalid non-string/buffer chunk');
13441 stream.emit('error', er);
13442 process.nextTick(function() {
13443 cb(er);
13444 });
13445 valid = false;
13446 }
13447 return valid;
13448}
13449
13450Writable.prototype.write = function(chunk, encoding, cb) {
13451 var state = this._writableState;
13452 var ret = false;
13453
13454 if (typeof encoding === 'function') {
13455 cb = encoding;
13456 encoding = null;
13457 }
13458
13459 if (Buffer.isBuffer(chunk))
13460 encoding = 'buffer';
13461 else if (!encoding)
13462 encoding = state.defaultEncoding;
13463
13464 if (typeof cb !== 'function')
13465 cb = function() {};
13466
13467 if (state.ended)
13468 writeAfterEnd(this, state, cb);
13469 else if (validChunk(this, state, chunk, cb))
13470 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13471
13472 return ret;
13473};
13474
13475function decodeChunk(state, chunk, encoding) {
13476 if (!state.objectMode &&
13477 state.decodeStrings !== false &&
13478 typeof chunk === 'string') {
13479 chunk = new Buffer(chunk, encoding);
13480 }
13481 return chunk;
13482}
13483
13484// if we're already writing something, then just put this
13485// in the queue, and wait our turn. Otherwise, call _write
13486// If we return false, then we need a drain event, so set that flag.
13487function writeOrBuffer(stream, state, chunk, encoding, cb) {
13488 chunk = decodeChunk(state, chunk, encoding);
13489 if (Buffer.isBuffer(chunk))
13490 encoding = 'buffer';
13491 var len = state.objectMode ? 1 : chunk.length;
13492
13493 state.length += len;
13494
13495 var ret = state.length < state.highWaterMark;
13496 // we must ensure that previous needDrain will not be reset to false.
13497 if (!ret)
13498 state.needDrain = true;
13499
13500 if (state.writing)
13501 state.buffer.push(new WriteReq(chunk, encoding, cb));
13502 else
13503 doWrite(stream, state, len, chunk, encoding, cb);
13504
13505 return ret;
13506}
13507
13508function doWrite(stream, state, len, chunk, encoding, cb) {
13509 state.writelen = len;
13510 state.writecb = cb;
13511 state.writing = true;
13512 state.sync = true;
13513 stream._write(chunk, encoding, state.onwrite);
13514 state.sync = false;
13515}
13516
13517function onwriteError(stream, state, sync, er, cb) {
13518 if (sync)
13519 process.nextTick(function() {
13520 cb(er);
13521 });
13522 else
13523 cb(er);
13524
13525 stream._writableState.errorEmitted = true;
13526 stream.emit('error', er);
13527}
13528
13529function onwriteStateUpdate(state) {
13530 state.writing = false;
13531 state.writecb = null;
13532 state.length -= state.writelen;
13533 state.writelen = 0;
13534}
13535
13536function onwrite(stream, er) {
13537 var state = stream._writableState;
13538 var sync = state.sync;
13539 var cb = state.writecb;
13540
13541 onwriteStateUpdate(state);
13542
13543 if (er)
13544 onwriteError(stream, state, sync, er, cb);
13545 else {
13546 // Check if we're actually ready to finish, but don't emit yet
13547 var finished = needFinish(stream, state);
13548
13549 if (!finished && !state.bufferProcessing && state.buffer.length)
13550 clearBuffer(stream, state);
13551
13552 if (sync) {
13553 process.nextTick(function() {
13554 afterWrite(stream, state, finished, cb);
13555 });
13556 } else {
13557 afterWrite(stream, state, finished, cb);
13558 }
13559 }
13560}
13561
13562function afterWrite(stream, state, finished, cb) {
13563 if (!finished)
13564 onwriteDrain(stream, state);
13565 cb();
13566 if (finished)
13567 finishMaybe(stream, state);
13568}
13569
13570// Must force callback to be called on nextTick, so that we don't
13571// emit 'drain' before the write() consumer gets the 'false' return
13572// value, and has a chance to attach a 'drain' listener.
13573function onwriteDrain(stream, state) {
13574 if (state.length === 0 && state.needDrain) {
13575 state.needDrain = false;
13576 stream.emit('drain');
13577 }
13578}
13579
13580
13581// if there's something in the buffer waiting, then process it
13582function clearBuffer(stream, state) {
13583 state.bufferProcessing = true;
13584
13585 for (var c = 0; c < state.buffer.length; c++) {
13586 var entry = state.buffer[c];
13587 var chunk = entry.chunk;
13588 var encoding = entry.encoding;
13589 var cb = entry.callback;
13590 var len = state.objectMode ? 1 : chunk.length;
13591
13592 doWrite(stream, state, len, chunk, encoding, cb);
13593
13594 // if we didn't call the onwrite immediately, then
13595 // it means that we need to wait until it does.
13596 // also, that means that the chunk and cb are currently
13597 // being processed, so move the buffer counter past them.
13598 if (state.writing) {
13599 c++;
13600 break;
13601 }
13602 }
13603
13604 state.bufferProcessing = false;
13605 if (c < state.buffer.length)
13606 state.buffer = state.buffer.slice(c);
13607 else
13608 state.buffer.length = 0;
13609}
13610
13611Writable.prototype._write = function(chunk, encoding, cb) {
13612 cb(new Error('not implemented'));
13613};
13614
13615Writable.prototype.end = function(chunk, encoding, cb) {
13616 var state = this._writableState;
13617
13618 if (typeof chunk === 'function') {
13619 cb = chunk;
13620 chunk = null;
13621 encoding = null;
13622 } else if (typeof encoding === 'function') {
13623 cb = encoding;
13624 encoding = null;
13625 }
13626
13627 if (typeof chunk !== 'undefined' && chunk !== null)
13628 this.write(chunk, encoding);
13629
13630 // ignore unnecessary end() calls.
13631 if (!state.ending && !state.finished)
13632 endWritable(this, state, cb);
13633};
13634
13635
13636function needFinish(stream, state) {
13637 return (state.ending &&
13638 state.length === 0 &&
13639 !state.finished &&
13640 !state.writing);
13641}
13642
13643function finishMaybe(stream, state) {
13644 var need = needFinish(stream, state);
13645 if (need) {
13646 state.finished = true;
13647 stream.emit('finish');
13648 }
13649 return need;
13650}
13651
13652function endWritable(stream, state, cb) {
13653 state.ending = true;
13654 finishMaybe(stream, state);
13655 if (cb) {
13656 if (state.finished)
13657 process.nextTick(cb);
13658 else
13659 stream.once('finish', cb);
13660 }
13661 state.ended = true;
13662}
13663}, {"buffer":29,"core-util-is":71,"inherits":72,"stream":52,"./_stream_duplex":74}],74: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
13664//
13665// Permission is hereby granted, free of charge, to any person obtaining a
13666// copy of this software and associated documentation files (the
13667// "Software"), to deal in the Software without restriction, including
13668// without limitation the rights to use, copy, modify, merge, publish,
13669// distribute, sublicense, and/or sell copies of the Software, and to permit
13670// persons to whom the Software is furnished to do so, subject to the
13671// following conditions:
13672//
13673// The above copyright notice and this permission notice shall be included
13674// in all copies or substantial portions of the Software.
13675//
13676// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13677// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13678// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13679// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13680// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13681// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13682// USE OR OTHER DEALINGS IN THE SOFTWARE.
13683
13684// a duplex stream is just a stream that is both readable and writable.
13685// Since JS doesn't have multiple prototypal inheritance, this class
13686// prototypally inherits from Readable, and then parasitically from
13687// Writable.
13688
13689module.exports = Duplex;
13690
13691/*<replacement>*/
13692var objectKeys = Object.keys || function (obj) {
13693 var keys = [];
13694 for (var key in obj) keys.push(key);
13695 return keys;
13696}
13697/*</replacement>*/
13698
13699
13700/*<replacement>*/
13701var util = require('core-util-is');
13702util.inherits = require('inherits');
13703/*</replacement>*/
13704
13705var Readable = require('./_stream_readable');
13706var Writable = require('./_stream_writable');
13707
13708util.inherits(Duplex, Readable);
13709
13710forEach(objectKeys(Writable.prototype), function(method) {
13711 if (!Duplex.prototype[method])
13712 Duplex.prototype[method] = Writable.prototype[method];
13713});
13714
13715function Duplex(options) {
13716 if (!(this instanceof Duplex))
13717 return new Duplex(options);
13718
13719 Readable.call(this, options);
13720 Writable.call(this, options);
13721
13722 if (options && options.readable === false)
13723 this.readable = false;
13724
13725 if (options && options.writable === false)
13726 this.writable = false;
13727
13728 this.allowHalfOpen = true;
13729 if (options && options.allowHalfOpen === false)
13730 this.allowHalfOpen = false;
13731
13732 this.once('end', onend);
13733}
13734
13735// the no-half-open enforcer
13736function onend() {
13737 // if we allow half-open state, or if the writable side ended,
13738 // then we're ok.
13739 if (this.allowHalfOpen || this._writableState.ended)
13740 return;
13741
13742 // no more data can be written.
13743 // But allow more writes to happen in this tick.
13744 process.nextTick(this.end.bind(this));
13745}
13746
13747function forEach (xs, f) {
13748 for (var i = 0, l = xs.length; i < l; i++) {
13749 f(xs[i], i);
13750 }
13751}
13752}, {"core-util-is":71,"inherits":72,"./_stream_readable":69,"./_stream_writable":73}],75: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
13753//
13754// Permission is hereby granted, free of charge, to any person obtaining a
13755// copy of this software and associated documentation files (the
13756// "Software"), to deal in the Software without restriction, including
13757// without limitation the rights to use, copy, modify, merge, publish,
13758// distribute, sublicense, and/or sell copies of the Software, and to permit
13759// persons to whom the Software is furnished to do so, subject to the
13760// following conditions:
13761//
13762// The above copyright notice and this permission notice shall be included
13763// in all copies or substantial portions of the Software.
13764//
13765// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13766// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13767// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13768// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13769// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13770// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13771// USE OR OTHER DEALINGS IN THE SOFTWARE.
13772
13773
13774// a transform stream is a readable/writable stream where you do
13775// something with the data. Sometimes it's called a "filter",
13776// but that's not a great name for it, since that implies a thing where
13777// some bits pass through, and others are simply ignored. (That would
13778// be a valid example of a transform, of course.)
13779//
13780// While the output is causally related to the input, it's not a
13781// necessarily symmetric or synchronous transformation. For example,
13782// a zlib stream might take multiple plain-text writes(), and then
13783// emit a single compressed chunk some time in the future.
13784//
13785// Here's how this works:
13786//
13787// The Transform stream has all the aspects of the readable and writable
13788// stream classes. When you write(chunk), that calls _write(chunk,cb)
13789// internally, and returns false if there's a lot of pending writes
13790// buffered up. When you call read(), that calls _read(n) until
13791// there's enough pending readable data buffered up.
13792//
13793// In a transform stream, the written data is placed in a buffer. When
13794// _read(n) is called, it transforms the queued up data, calling the
13795// buffered _write cb's as it consumes chunks. If consuming a single
13796// written chunk would result in multiple output chunks, then the first
13797// outputted bit calls the readcb, and subsequent chunks just go into
13798// the read buffer, and will cause it to emit 'readable' if necessary.
13799//
13800// This way, back-pressure is actually determined by the reading side,
13801// since _read has to be called to start processing a new chunk. However,
13802// a pathological inflate type of transform can cause excessive buffering
13803// here. For example, imagine a stream where every byte of input is
13804// interpreted as an integer from 0-255, and then results in that many
13805// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
13806// 1kb of data being output. In this case, you could write a very small
13807// amount of input, and end up with a very large amount of output. In
13808// such a pathological inflating mechanism, there'd be no way to tell
13809// the system to stop doing the transform. A single 4MB write could
13810// cause the system to run out of memory.
13811//
13812// However, even in such a pathological case, only a single written chunk
13813// would be consumed, and then the rest would wait (un-transformed) until
13814// the results of the previous transformed chunk were consumed.
13815
13816module.exports = Transform;
13817
13818var Duplex = require('./_stream_duplex');
13819
13820/*<replacement>*/
13821var util = require('core-util-is');
13822util.inherits = require('inherits');
13823/*</replacement>*/
13824
13825util.inherits(Transform, Duplex);
13826
13827
13828function TransformState(options, stream) {
13829 this.afterTransform = function(er, data) {
13830 return afterTransform(stream, er, data);
13831 };
13832
13833 this.needTransform = false;
13834 this.transforming = false;
13835 this.writecb = null;
13836 this.writechunk = null;
13837}
13838
13839function afterTransform(stream, er, data) {
13840 var ts = stream._transformState;
13841 ts.transforming = false;
13842
13843 var cb = ts.writecb;
13844
13845 if (!cb)
13846 return stream.emit('error', new Error('no writecb in Transform class'));
13847
13848 ts.writechunk = null;
13849 ts.writecb = null;
13850
13851 if (data !== null && data !== undefined)
13852 stream.push(data);
13853
13854 if (cb)
13855 cb(er);
13856
13857 var rs = stream._readableState;
13858 rs.reading = false;
13859 if (rs.needReadable || rs.length < rs.highWaterMark) {
13860 stream._read(rs.highWaterMark);
13861 }
13862}
13863
13864
13865function Transform(options) {
13866 if (!(this instanceof Transform))
13867 return new Transform(options);
13868
13869 Duplex.call(this, options);
13870
13871 var ts = this._transformState = new TransformState(options, this);
13872
13873 // when the writable side finishes, then flush out anything remaining.
13874 var stream = this;
13875
13876 // start out asking for a readable event once data is transformed.
13877 this._readableState.needReadable = true;
13878
13879 // we have implemented the _read method, and done the other things
13880 // that Readable wants before the first _read call, so unset the
13881 // sync guard flag.
13882 this._readableState.sync = false;
13883
13884 this.once('finish', function() {
13885 if ('function' === typeof this._flush)
13886 this._flush(function(er) {
13887 done(stream, er);
13888 });
13889 else
13890 done(stream);
13891 });
13892}
13893
13894Transform.prototype.push = function(chunk, encoding) {
13895 this._transformState.needTransform = false;
13896 return Duplex.prototype.push.call(this, chunk, encoding);
13897};
13898
13899// This is the part where you do stuff!
13900// override this function in implementation classes.
13901// 'chunk' is an input chunk.
13902//
13903// Call `push(newChunk)` to pass along transformed output
13904// to the readable side. You may call 'push' zero or more times.
13905//
13906// Call `cb(err)` when you are done with this chunk. If you pass
13907// an error, then that'll put the hurt on the whole operation. If you
13908// never call cb(), then you'll never get another chunk.
13909Transform.prototype._transform = function(chunk, encoding, cb) {
13910 throw new Error('not implemented');
13911};
13912
13913Transform.prototype._write = function(chunk, encoding, cb) {
13914 var ts = this._transformState;
13915 ts.writecb = cb;
13916 ts.writechunk = chunk;
13917 ts.writeencoding = encoding;
13918 if (!ts.transforming) {
13919 var rs = this._readableState;
13920 if (ts.needTransform ||
13921 rs.needReadable ||
13922 rs.length < rs.highWaterMark)
13923 this._read(rs.highWaterMark);
13924 }
13925};
13926
13927// Doesn't matter what the args are here.
13928// _transform does all the work.
13929// That we got here means that the readable side wants more data.
13930Transform.prototype._read = function(n) {
13931 var ts = this._transformState;
13932
13933 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
13934 ts.transforming = true;
13935 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
13936 } else {
13937 // mark that we need a transform, so that any data that comes in
13938 // will get processed, now that we've asked for it.
13939 ts.needTransform = true;
13940 }
13941};
13942
13943
13944function done(stream, er) {
13945 if (er)
13946 return stream.emit('error', er);
13947
13948 // if there's nothing in the write buffer, then that means
13949 // that nothing more will ever be provided
13950 var ws = stream._writableState;
13951 var rs = stream._readableState;
13952 var ts = stream._transformState;
13953
13954 if (ws.length)
13955 throw new Error('calling transform done when ws.length != 0');
13956
13957 if (ts.transforming)
13958 throw new Error('calling transform done when still transforming');
13959
13960 return stream.push(null);
13961}
13962}, {"./_stream_duplex":74,"core-util-is":71,"inherits":72}],76: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
13963//
13964// Permission is hereby granted, free of charge, to any person obtaining a
13965// copy of this software and associated documentation files (the
13966// "Software"), to deal in the Software without restriction, including
13967// without limitation the rights to use, copy, modify, merge, publish,
13968// distribute, sublicense, and/or sell copies of the Software, and to permit
13969// persons to whom the Software is furnished to do so, subject to the
13970// following conditions:
13971//
13972// The above copyright notice and this permission notice shall be included
13973// in all copies or substantial portions of the Software.
13974//
13975// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13976// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13977// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13978// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13979// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13980// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13981// USE OR OTHER DEALINGS IN THE SOFTWARE.
13982
13983// a passthrough stream.
13984// basically just the most minimal sort of Transform stream.
13985// Every written chunk gets output as-is.
13986
13987module.exports = PassThrough;
13988
13989var Transform = require('./_stream_transform');
13990
13991/*<replacement>*/
13992var util = require('core-util-is');
13993util.inherits = require('inherits');
13994/*</replacement>*/
13995
13996util.inherits(PassThrough, Transform);
13997
13998function PassThrough(options) {
13999 if (!(this instanceof PassThrough))
14000 return new PassThrough(options);
14001
14002 Transform.call(this, options);
14003}
14004
14005PassThrough.prototype._transform = function(chunk, encoding, cb) {
14006 cb(null, chunk);
14007};
14008}, {"./_stream_transform":75,"core-util-is":71,"inherits":72}],77: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
14009 * See list at <https://github.com/rvagg/node-levelup#contributing>
14010 * MIT License
14011 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
14012 */
14013
14014var extend = require('xtend')
14015 , LevelUPError = require('./errors').LevelUPError
14016
14017 , encodingNames = [
14018 'hex'
14019 , 'utf8'
14020 , 'utf-8'
14021 , 'ascii'
14022 , 'binary'
14023 , 'base64'
14024 , 'ucs2'
14025 , 'ucs-2'
14026 , 'utf16le'
14027 , 'utf-16le'
14028 ]
14029
14030 , defaultOptions = {
14031 createIfMissing : true
14032 , errorIfExists : false
14033 , keyEncoding : 'utf8'
14034 , valueEncoding : 'utf8'
14035 , compression : true
14036 }
14037
14038 , leveldown
14039
14040 , encodings = (function () {
14041 function isBinary (data) {
14042 return data === undefined || data === null || Buffer.isBuffer(data)
14043 }
14044
14045 var encodings = {}
14046 encodings.utf8 = encodings['utf-8'] = {
14047 encode : function (data) {
14048 return isBinary(data) ? data : String(data)
14049 }
14050 , decode : function (data) {
14051 return data
14052 }
14053 , buffer : false
14054 , type : 'utf8'
14055 }
14056 encodings.json = {
14057 encode : JSON.stringify
14058 , decode : JSON.parse
14059 , buffer : false
14060 , type : 'json'
14061 }
14062 encodingNames.forEach(function (type) {
14063 if (encodings[type])
14064 return
14065 encodings[type] = {
14066 encode : function (data) {
14067 return isBinary(data) ? data : new Buffer(data, type)
14068 }
14069 , decode : function (buffer) {
14070 return process.browser ? buffer.toString(type) : buffer;
14071 }
14072 , buffer : true
14073 , type : type // useful for debugging purposes
14074 }
14075 })
14076 return encodings
14077 })()
14078
14079 , encodingOpts = (function () {
14080 var eo = {}
14081 encodingNames.forEach(function (e) {
14082 eo[e] = { valueEncoding : e }
14083 })
14084 return eo
14085 }())
14086
14087function copy (srcdb, dstdb, callback) {
14088 srcdb.readStream()
14089 .pipe(dstdb.writeStream())
14090 .on('close', callback ? callback : function () {})
14091 .on('error', callback ? callback : function (err) { throw err })
14092}
14093
14094function getOptions (levelup, options) {
14095 var s = typeof options == 'string' // just an encoding
14096 if (!s && options && options.encoding && !options.valueEncoding)
14097 options.valueEncoding = options.encoding
14098 return extend(
14099 (levelup && levelup.options) || {}
14100 , s ? encodingOpts[options] || encodingOpts[defaultOptions.valueEncoding]
14101 : options
14102 )
14103}
14104
14105function getLevelDOWN () {
14106 if (leveldown)
14107 return leveldown
14108
14109 var requiredVersion = require('../package.json').devDependencies.leveldown
14110 , missingLevelDOWNError = 'Could not locate LevelDOWN, try `npm install leveldown`'
14111 , leveldownVersion
14112
14113 try {
14114 leveldownVersion = require('leveldown/package').version
14115 } catch (e) {
14116 throw new LevelUPError(missingLevelDOWNError)
14117 }
14118
14119 if (!require('semver').satisfies(leveldownVersion, requiredVersion)) {
14120 throw new LevelUPError(
14121 'Installed version of LevelDOWN ('
14122 + leveldownVersion
14123 + ') does not match required version ('
14124 + requiredVersion
14125 + ')'
14126 )
14127 }
14128
14129 try {
14130 return leveldown = require('leveldown')
14131 } catch (e) {
14132 throw new LevelUPError(missingLevelDOWNError)
14133 }
14134}
14135
14136function dispatchError (levelup, error, callback) {
14137 return typeof callback == 'function'
14138 ? callback(error)
14139 : levelup.emit('error', error)
14140}
14141
14142function getKeyEncoder (options, op) {
14143 var type = ((op && op.keyEncoding) || options.keyEncoding) || 'utf8'
14144 return encodings[type] || type
14145}
14146
14147function getValueEncoder (options, op) {
14148 var type = (((op && (op.valueEncoding || op.encoding))
14149 || options.valueEncoding || options.encoding)) || 'utf8'
14150 return encodings[type] || type
14151}
14152
14153function encodeKey (key, options, op) {
14154 return getKeyEncoder(options, op).encode(key)
14155}
14156
14157function encodeValue (value, options, op) {
14158 return getValueEncoder(options, op).encode(value)
14159}
14160
14161function decodeKey (key, options) {
14162 return getKeyEncoder(options).decode(key)
14163}
14164
14165function decodeValue (value, options) {
14166 return getValueEncoder(options).decode(value)
14167}
14168
14169function isValueAsBuffer (options, op) {
14170 return getValueEncoder(options, op).buffer
14171}
14172
14173function isKeyAsBuffer (options, op) {
14174 return getKeyEncoder(options, op).buffer
14175}
14176
14177module.exports = {
14178 defaultOptions : defaultOptions
14179 , copy : copy
14180 , getOptions : getOptions
14181 , getLevelDOWN : getLevelDOWN
14182 , dispatchError : dispatchError
14183 , encodeKey : encodeKey
14184 , encodeValue : encodeValue
14185 , isValueAsBuffer : isValueAsBuffer
14186 , isKeyAsBuffer : isKeyAsBuffer
14187 , decodeValue : decodeValue
14188 , decodeKey : decodeKey
14189}
14190}, {"xtend":41,"./errors":47,"../package.json":78,"leveldown/package":79,"semver":79,"leveldown":79}],78: [function (exports, require, module, global) {module.exports = {
14191 "name": "levelup",
14192 "description": "Fast & simple storage - a Node.js-style LevelDB wrapper",
14193 "version": "0.18.6",
14194 "contributors": [
14195 {
14196 "name": "Rod Vagg",
14197 "email": "r@va.gg",
14198 "url": "https://github.com/rvagg"
14199 },
14200 {
14201 "name": "John Chesley",
14202 "email": "john@chesl.es",
14203 "url": "https://github.com/chesles/"
14204 },
14205 {
14206 "name": "Jake Verbaten",
14207 "email": "raynos2@gmail.com",
14208 "url": "https://github.com/raynos"
14209 },
14210 {
14211 "name": "Dominic Tarr",
14212 "email": "dominic.tarr@gmail.com",
14213 "url": "https://github.com/dominictarr"
14214 },
14215 {
14216 "name": "Max Ogden",
14217 "email": "max@maxogden.com",
14218 "url": "https://github.com/maxogden"
14219 },
14220 {
14221 "name": "Lars-Magnus Skog",
14222 "email": "lars.magnus.skog@gmail.com",
14223 "url": "https://github.com/ralphtheninja"
14224 },
14225 {
14226 "name": "David Björklund",
14227 "email": "david.bjorklund@gmail.com",
14228 "url": "https://github.com/kesla"
14229 },
14230 {
14231 "name": "Julian Gruber",
14232 "email": "julian@juliangruber.com",
14233 "url": "https://github.com/juliangruber"
14234 },
14235 {
14236 "name": "Paolo Fragomeni",
14237 "email": "paolo@async.ly",
14238 "url": "https://github.com/hij1nx"
14239 },
14240 {
14241 "name": "Anton Whalley",
14242 "email": "anton.whalley@nearform.com",
14243 "url": "https://github.com/No9"
14244 },
14245 {
14246 "name": "Matteo Collina",
14247 "email": "matteo.collina@gmail.com",
14248 "url": "https://github.com/mcollina"
14249 },
14250 {
14251 "name": "Pedro Teixeira",
14252 "email": "pedro.teixeira@gmail.com",
14253 "url": "https://github.com/pgte"
14254 },
14255 {
14256 "name": "James Halliday",
14257 "email": "mail@substack.net",
14258 "url": "https://github.com/substack"
14259 }
14260 ],
14261 "repository": {
14262 "type": "git",
14263 "url": "git+https://github.com/rvagg/node-levelup.git"
14264 },
14265 "homepage": "https://github.com/rvagg/node-levelup",
14266 "keywords": [
14267 "leveldb",
14268 "stream",
14269 "database",
14270 "db",
14271 "store",
14272 "storage",
14273 "json"
14274 ],
14275 "main": "lib/levelup.js",
14276 "dependencies": {
14277 "bl": "~0.8.1",
14278 "deferred-leveldown": "~0.2.0",
14279 "errno": "~0.1.1",
14280 "prr": "~0.0.0",
14281 "readable-stream": "~1.0.26",
14282 "semver": "~2.3.1",
14283 "xtend": "~3.0.0"
14284 },
14285 "devDependencies": {
14286 "leveldown": "~0.10.0",
14287 "bustermove": "*",
14288 "tap": "*",
14289 "referee": "*",
14290 "rimraf": "*",
14291 "async": "*",
14292 "fstream": "*",
14293 "tar": "*",
14294 "mkfiletree": "*",
14295 "readfiletree": "*",
14296 "slow-stream": ">=0.0.4",
14297 "delayed": "*",
14298 "boganipsum": "*",
14299 "du": "*",
14300 "memdown": "*",
14301 "msgpack-js": "*"
14302 },
14303 "browser": {
14304 "leveldown": false,
14305 "leveldown/package": false,
14306 "semver": false
14307 },
14308 "scripts": {
14309 "test": "tap test/*-test.js --stderr",
14310 "functionaltests": "node ./test/functional/fstream-test.js && node ./test/functional/binary-data-test.js && node ./test/functional/compat-test.js",
14311 "alltests": "npm test && npm run-script functionaltests"
14312 },
14313 "license": "MIT",
14314 "gitHead": "213e989e2b75273e2b44c23f84f95e35bff7ea11",
14315 "bugs": {
14316 "url": "https://github.com/rvagg/node-levelup/issues"
14317 },
14318 "_id": "levelup@0.18.6",
14319 "_shasum": "e6a01cb089616c8ecc0291c2a9bd3f0c44e3e5eb",
14320 "_from": "levelup@>=0.18.2 <0.19.0",
14321 "_npmVersion": "1.4.14",
14322 "_npmUser": {
14323 "name": "rvagg",
14324 "email": "rod@vagg.org"
14325 },
14326 "maintainers": [
14327 {
14328 "name": "rvagg",
14329 "email": "rod@vagg.org"
14330 }
14331 ],
14332 "dist": {
14333 "shasum": "e6a01cb089616c8ecc0291c2a9bd3f0c44e3e5eb",
14334 "tarball": "http://registry.npmjs.org/levelup/-/levelup-0.18.6.tgz"
14335 },
14336 "directories": {},
14337 "_resolved": "https://registry.npmjs.org/levelup/-/levelup-0.18.6.tgz",
14338 "readme": "ERROR: No README data found!"
14339}
14340}, {}],79: [function (exports, require, module, global) {}, {}],80: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
14341 * See list at <https://github.com/rvagg/node-levelup#contributing>
14342 * MIT License
14343 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
14344 */
14345
14346var Stream = require('stream').Stream
14347 , inherits = require('util').inherits
14348 , extend = require('xtend')
14349 , bl = require('bl')
14350
14351 , setImmediate = global.setImmediate || process.nextTick
14352
14353 , getOptions = require('./util').getOptions
14354
14355 , defaultOptions = { type: 'put' }
14356
14357function WriteStream (options, db) {
14358 if (!(this instanceof WriteStream))
14359 return new WriteStream(options, db)
14360
14361 Stream.call(this)
14362 this._options = extend(defaultOptions, getOptions(db, options))
14363 this._db = db
14364 this._buffer = []
14365 this._status = 'init'
14366 this._end = false
14367 this.writable = true
14368 this.readable = false
14369
14370 var self = this
14371 , ready = function () {
14372 if (!self.writable)
14373 return
14374 self._status = 'ready'
14375 self.emit('ready')
14376 self._process()
14377 }
14378
14379 if (db.isOpen())
14380 setImmediate(ready)
14381 else
14382 db.once('ready', ready)
14383}
14384
14385inherits(WriteStream, Stream)
14386
14387WriteStream.prototype.write = function (data) {
14388 if (!this.writable)
14389 return false
14390 this._buffer.push(data)
14391 if (this._status != 'init')
14392 this._processDelayed()
14393 if (this._options.maxBufferLength &&
14394 this._buffer.length > this._options.maxBufferLength) {
14395 this._writeBlock = true
14396 return false
14397 }
14398 return true
14399}
14400
14401WriteStream.prototype.end = function (data) {
14402 var self = this
14403 if (data)
14404 this.write(data)
14405 setImmediate(function () {
14406 self._end = true
14407 self._process()
14408 })
14409}
14410
14411WriteStream.prototype.destroy = function () {
14412 this.writable = false
14413 this.end()
14414}
14415
14416WriteStream.prototype.destroySoon = function () {
14417 this.end()
14418}
14419
14420WriteStream.prototype.add = function (entry) {
14421 if (!entry.props)
14422 return
14423 if (entry.props.Directory)
14424 entry.pipe(this._db.writeStream(this._options))
14425 else if (entry.props.File || entry.File || entry.type == 'File')
14426 this._write(entry)
14427 return true
14428}
14429
14430WriteStream.prototype._processDelayed = function () {
14431 var self = this
14432 setImmediate(function () {
14433 self._process()
14434 })
14435}
14436
14437WriteStream.prototype._process = function () {
14438 var buffer
14439 , self = this
14440
14441 , cb = function (err) {
14442 if (!self.writable)
14443 return
14444 if (self._status != 'closed')
14445 self._status = 'ready'
14446 if (err) {
14447 self.writable = false
14448 return self.emit('error', err)
14449 }
14450 self._process()
14451 }
14452
14453 if (self._status != 'ready' && self.writable) {
14454 if (self._buffer.length && self._status != 'closed')
14455 self._processDelayed()
14456 return
14457 }
14458
14459 if (self._buffer.length && self.writable) {
14460 self._status = 'writing'
14461 buffer = self._buffer
14462 self._buffer = []
14463
14464 self._db.batch(buffer.map(function (d) {
14465 return {
14466 type : d.type || self._options.type
14467 , key : d.key
14468 , value : d.value
14469 , keyEncoding : d.keyEncoding || self._options.keyEncoding
14470 , valueEncoding : d.valueEncoding
14471 || d.encoding
14472 || self._options.valueEncoding
14473 }
14474 }), cb)
14475
14476 if (self._writeBlock) {
14477 self._writeBlock = false
14478 self.emit('drain')
14479 }
14480
14481 // don't allow close until callback has returned
14482 return
14483 }
14484
14485 if (self._end && self._status != 'closed') {
14486 self._status = 'closed'
14487 self.writable = false
14488 self.emit('close')
14489 }
14490}
14491
14492WriteStream.prototype._write = function (entry) {
14493 var key = entry.path || entry.props.path
14494 , self = this
14495
14496 if (!key)
14497 return
14498
14499 entry.pipe(bl(function (err, data) {
14500 if (err) {
14501 self.writable = false
14502 return self.emit('error', err)
14503 }
14504
14505 if (self._options.fstreamRoot &&
14506 key.indexOf(self._options.fstreamRoot) > -1)
14507 key = key.substr(self._options.fstreamRoot.length + 1)
14508
14509 self.write({ key: key, value: data.slice(0) })
14510 }))
14511}
14512
14513WriteStream.prototype.toString = function () {
14514 return 'LevelUP.WriteStream'
14515}
14516
14517module.exports = WriteStream
14518}, {"stream":52,"util":23,"xtend":41,"bl":81,"./util":77}],81: [function (exports, require, module, global) {var DuplexStream = require('readable-stream').Duplex
14519 , util = require('util')
14520
14521function BufferList (callback) {
14522 if (!(this instanceof BufferList))
14523 return new BufferList(callback)
14524
14525 this._bufs = []
14526 this.length = 0
14527
14528 if (typeof callback == 'function') {
14529 this._callback = callback
14530
14531 var piper = function (err) {
14532 if (this._callback) {
14533 this._callback(err)
14534 this._callback = null
14535 }
14536 }.bind(this)
14537
14538 this.on('pipe', function (src) {
14539 src.on('error', piper)
14540 })
14541 this.on('unpipe', function (src) {
14542 src.removeListener('error', piper)
14543 })
14544 }
14545 else if (Buffer.isBuffer(callback))
14546 this.append(callback)
14547 else if (Array.isArray(callback)) {
14548 callback.forEach(function (b) {
14549 Buffer.isBuffer(b) && this.append(b)
14550 }.bind(this))
14551 }
14552
14553 DuplexStream.call(this)
14554}
14555
14556util.inherits(BufferList, DuplexStream)
14557
14558BufferList.prototype._offset = function (offset) {
14559 var tot = 0, i = 0, _t
14560 for (; i < this._bufs.length; i++) {
14561 _t = tot + this._bufs[i].length
14562 if (offset < _t)
14563 return [ i, offset - tot ]
14564 tot = _t
14565 }
14566}
14567
14568BufferList.prototype.append = function (buf) {
14569 this._bufs.push(Buffer.isBuffer(buf) ? buf : new Buffer(buf))
14570 this.length += buf.length
14571 return this
14572}
14573
14574BufferList.prototype._write = function (buf, encoding, callback) {
14575 this.append(buf)
14576 if (callback)
14577 callback()
14578}
14579
14580BufferList.prototype._read = function (size) {
14581 if (!this.length)
14582 return this.push(null)
14583 size = Math.min(size, this.length)
14584 this.push(this.slice(0, size))
14585 this.consume(size)
14586}
14587
14588BufferList.prototype.end = function (chunk) {
14589 DuplexStream.prototype.end.call(this, chunk)
14590
14591 if (this._callback) {
14592 this._callback(null, this.slice())
14593 this._callback = null
14594 }
14595}
14596
14597BufferList.prototype.get = function (index) {
14598 return this.slice(index, index + 1)[0]
14599}
14600
14601BufferList.prototype.slice = function (start, end) {
14602 return this.copy(null, 0, start, end)
14603}
14604
14605BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) {
14606 if (typeof srcStart != 'number' || srcStart < 0)
14607 srcStart = 0
14608 if (typeof srcEnd != 'number' || srcEnd > this.length)
14609 srcEnd = this.length
14610 if (srcStart >= this.length)
14611 return dst || new Buffer(0)
14612 if (srcEnd <= 0)
14613 return dst || new Buffer(0)
14614
14615 var copy = !!dst
14616 , off = this._offset(srcStart)
14617 , len = srcEnd - srcStart
14618 , bytes = len
14619 , bufoff = (copy && dstStart) || 0
14620 , start = off[1]
14621 , l
14622 , i
14623
14624 // copy/slice everything
14625 if (srcStart === 0 && srcEnd == this.length) {
14626 if (!copy) // slice, just return a full concat
14627 return Buffer.concat(this._bufs)
14628
14629 // copy, need to copy individual buffers
14630 for (i = 0; i < this._bufs.length; i++) {
14631 this._bufs[i].copy(dst, bufoff)
14632 bufoff += this._bufs[i].length
14633 }
14634
14635 return dst
14636 }
14637
14638 // easy, cheap case where it's a subset of one of the buffers
14639 if (bytes <= this._bufs[off[0]].length - start) {
14640 return copy
14641 ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
14642 : this._bufs[off[0]].slice(start, start + bytes)
14643 }
14644
14645 if (!copy) // a slice, we need something to copy in to
14646 dst = new Buffer(len)
14647
14648 for (i = off[0]; i < this._bufs.length; i++) {
14649 l = this._bufs[i].length - start
14650
14651 if (bytes > l) {
14652 this._bufs[i].copy(dst, bufoff, start)
14653 } else {
14654 this._bufs[i].copy(dst, bufoff, start, start + bytes)
14655 break
14656 }
14657
14658 bufoff += l
14659 bytes -= l
14660
14661 if (start)
14662 start = 0
14663 }
14664
14665 return dst
14666}
14667
14668BufferList.prototype.toString = function (encoding, start, end) {
14669 return this.slice(start, end).toString(encoding)
14670}
14671
14672BufferList.prototype.consume = function (bytes) {
14673 while (this._bufs.length) {
14674 if (bytes > this._bufs[0].length) {
14675 bytes -= this._bufs[0].length
14676 this.length -= this._bufs[0].length
14677 this._bufs.shift()
14678 } else {
14679 this._bufs[0] = this._bufs[0].slice(bytes)
14680 this.length -= bytes
14681 break
14682 }
14683 }
14684 return this
14685}
14686
14687BufferList.prototype.duplicate = function () {
14688 var i = 0
14689 , copy = new BufferList()
14690
14691 for (; i < this._bufs.length; i++)
14692 copy.append(this._bufs[i])
14693
14694 return copy
14695}
14696
14697BufferList.prototype.destroy = function () {
14698 this._bufs.length = 0;
14699 this.length = 0;
14700 this.push(null);
14701}
14702
14703;(function () {
14704 var methods = {
14705 'readDoubleBE' : 8
14706 , 'readDoubleLE' : 8
14707 , 'readFloatBE' : 4
14708 , 'readFloatLE' : 4
14709 , 'readInt32BE' : 4
14710 , 'readInt32LE' : 4
14711 , 'readUInt32BE' : 4
14712 , 'readUInt32LE' : 4
14713 , 'readInt16BE' : 2
14714 , 'readInt16LE' : 2
14715 , 'readUInt16BE' : 2
14716 , 'readUInt16LE' : 2
14717 , 'readInt8' : 1
14718 , 'readUInt8' : 1
14719 }
14720
14721 for (var m in methods) {
14722 (function (m) {
14723 BufferList.prototype[m] = function (offset) {
14724 return this.slice(offset, offset + methods[m])[m](0)
14725 }
14726 }(m))
14727 }
14728}())
14729
14730module.exports = BufferList
14731}, {"readable-stream":51,"util":23}],82: [function (exports, require, module, global) {/* Copyright (c) 2012-2014 LevelUP contributors
14732 * See list at <https://github.com/rvagg/node-levelup#contributing>
14733 * MIT License
14734 * <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
14735 */
14736
14737var util = require('./util')
14738 , WriteError = require('./errors').WriteError
14739
14740 , getOptions = util.getOptions
14741 , dispatchError = util.dispatchError
14742
14743function Batch (levelup) {
14744 this._levelup = levelup
14745 this.batch = levelup.db.batch()
14746 this.ops = []
14747}
14748
14749Batch.prototype.put = function (key_, value_, options) {
14750 options = getOptions(this._levelup, options)
14751
14752 var key = util.encodeKey(key_, options)
14753 , value = util.encodeValue(value_, options)
14754
14755 try {
14756 this.batch.put(key, value)
14757 } catch (e) {
14758 throw new WriteError(e)
14759 }
14760 this.ops.push({ type : 'put', key : key, value : value })
14761
14762 return this
14763}
14764
14765Batch.prototype.del = function (key_, options) {
14766 options = getOptions(this._levelup, options)
14767
14768 var key = util.encodeKey(key_, options)
14769
14770 try {
14771 this.batch.del(key)
14772 } catch (err) {
14773 throw new WriteError(err)
14774 }
14775 this.ops.push({ type : 'del', key : key })
14776
14777 return this
14778}
14779
14780Batch.prototype.clear = function () {
14781 try {
14782 this.batch.clear()
14783 } catch (err) {
14784 throw new WriteError(err)
14785 }
14786
14787 this.ops = []
14788 return this
14789}
14790
14791Batch.prototype.write = function (callback) {
14792 var levelup = this._levelup
14793 , ops = this.ops
14794
14795 try {
14796 this.batch.write(function (err) {
14797 if (err)
14798 return dispatchError(levelup, new WriteError(err), callback)
14799 levelup.emit('batch', ops)
14800 if (callback)
14801 callback()
14802 })
14803 } catch (err) {
14804 throw new WriteError(err)
14805 }
14806}
14807
14808module.exports = Batch
14809}, {"./util":77,"./errors":47}],83: [function (exports, require, module, global) {var fwd = require('fwd-stream');
14810var sublevel = require('level-sublevel');
14811var blobs = require('level-blobs');
14812var peek = require('level-peek');
14813var once = require('once');
14814var errno = require('./errno');
14815var paths = require('./paths');
14816var watchers = require('./watchers');
14817
14818var nextTick = function(cb, err, val) {
14819 process.nextTick(function() {
14820 cb(err, val);
14821 });
14822};
14823
14824var noop = function() {};
14825
14826module.exports = function(db, opts) {
14827 var fs = {};
14828
14829 db = sublevel(db);
14830
14831 var bl = blobs(db.sublevel('blobs'), opts);
14832 var ps = paths(db.sublevel('stats'));
14833 var links = db.sublevel('links');
14834
14835 var listeners = watchers();
14836 var fds = [];
14837
14838 var now = Date.now();
14839 var inc = function() {
14840 return ++now;
14841 };
14842
14843 fs.mkdir = function(key, mode, cb) {
14844 if (typeof mode === 'function') return fs.mkdir(key, null, mode);
14845 if (!mode) mode = 0777;
14846 if (!cb) cb = noop;
14847
14848 ps.follow(key, function(err, stat, key) {
14849 if (err && err.code !== 'ENOENT') return cb(err);
14850 if (stat) return cb(errno.EEXIST(key));
14851
14852 ps.put(key, {
14853 type:'directory',
14854 mode: mode,
14855 size: 4096
14856 }, listeners.cb(key, cb));
14857 });
14858 };
14859
14860 fs.rmdir = function(key, cb) {
14861 if (!cb) cb = noop;
14862 ps.follow(key, function(err, stat, key) {
14863 if (err) return cb(err);
14864 fs.readdir(key, function(err, files) {
14865 if (err) return cb(err);
14866 if (files.length) return cb(errno.ENOTEMPTY(key));
14867 ps.del(key, listeners.cb(key, cb));
14868 });
14869 });
14870
14871 };
14872
14873 fs.readdir = function(key, cb) {
14874 ps.follow(key, function(err, stat, key) {
14875 if (err) return cb(err);
14876 if (!stat) return cb(errno.ENOENT(key));
14877 if (!stat.isDirectory()) return cb(errno.ENOTDIR(key));
14878 ps.list(key, cb);
14879 });
14880 };
14881
14882 var stat = function(key, lookup, cb) {
14883 lookup(key, function(err, stat, key) {
14884 if (err) return cb(err);
14885 if (!stat.isFile()) return cb(null, stat);
14886 var blob = stat && stat.blob || key;
14887 bl.size(blob, function(err, size) {
14888 if (err) return cb(err);
14889 stat.size = size;
14890 cb(null, stat);
14891 });
14892 });
14893 };
14894
14895 fs.stat = function(key, cb) {
14896 stat(key, ps.follow, cb);
14897 };
14898
14899 fs.lstat = function(key, cb) {
14900 stat(key, ps.get, cb);
14901 };
14902
14903 fs.exists = function(key, cb) {
14904 ps.follow(key, function(err) {
14905 cb(!err);
14906 });
14907 };
14908
14909 var chmod = function(key, lookup, mode, cb) {
14910 if (!cb) cb = noop;
14911 lookup(key, function(err, stat, key) {
14912 if (err) return cb(err);
14913 ps.update(key, {mode:mode}, listeners.cb(key, cb));
14914 });
14915 };
14916
14917 fs.chmod = function(key, mode, cb) {
14918 chmod(key, ps.follow, mode, cb);
14919 };
14920
14921 fs.lchmod = function(key, mode, cb) {
14922 chmod(key, ps.get, mode, cb);
14923 };
14924
14925 var chown = function(key, lookup, uid, gid, cb) {
14926 if (!cb) cb = noop;
14927 lookup(key, function(err, stat, key) {
14928 if (err) return cb(err);
14929 ps.update(key, {uid:uid, gid:gid}, listeners.cb(key, cb));
14930 });
14931 };
14932
14933 fs.chown = function(key, uid, gid, cb) {
14934 chown(key, ps.follow, uid, gid, cb);
14935 };
14936
14937 fs.lchown = function(key, uid, gid, cb) {
14938 chown(key, ps.get, uid, gid, cb);
14939 };
14940
14941 fs.utimes = function(key, atime, mtime, cb) {
14942 if (!cb) cb = noop;
14943 ps.follow(key, function(err, stat, key) {
14944 if (err) return cb(err);
14945 var upd = {};
14946 if (atime) upd.atime = atime;
14947 if (mtime) upd.mtime = mtime;
14948 ps.update(key, upd, listeners.cb(key, cb));
14949 });
14950 };
14951
14952 fs.rename = function(from, to, cb) {
14953 if (!cb) cb = noop;
14954
14955 ps.follow(from, function(err, statFrom, from) {
14956 if (err) return cb(err);
14957
14958 var rename = function() {
14959 cb = listeners.cb(to, listeners.cb(from, cb));
14960 ps.put(to, statFrom, function(err) {
14961 if (err) return cb(err);
14962 ps.del(from, cb);
14963 });
14964 };
14965
14966 ps.follow(to, function(err, statTo, to) {
14967 if (err && err.code !== 'ENOENT') return cb(err);
14968 if (!statTo) return rename();
14969 if (statFrom.isDirectory() !== statTo.isDirectory()) return cb(errno.EISDIR(from));
14970
14971 if (statTo.isDirectory()) {
14972 fs.readdir(to, function(err, list) {
14973 if (err) return cb(err);
14974 if (list.length) return cb(errno.ENOTEMPTY(from));
14975 rename();
14976 });
14977 return;
14978 }
14979
14980 rename();
14981 });
14982 });
14983 };
14984
14985 fs.realpath = function(key, cache, cb) {
14986 if (typeof cache === 'function') return fs.realpath(key, null, cache);
14987 ps.follow(key, function(err, stat, key) {
14988 if (err) return cb(err);
14989 cb(null, key);
14990 });
14991 };
14992
14993 fs.writeFile = function(key, data, opts, cb) {
14994 if (typeof opts === 'function') return fs.writeFile(key, data, null, opts);
14995 if (typeof opts === 'string') opts = {encoding:opts};
14996 if (!opts) opts = {};
14997 if (!cb) cb = noop;
14998
14999 if (!Buffer.isBuffer(data)) data = new Buffer(data, opts.encoding || 'utf-8');
15000
15001 var flags = opts.flags || 'w';
15002 opts.append = flags[0] !== 'w';
15003
15004 ps.follow(key, function(err, stat, key) {
15005 if (err && err.code !== 'ENOENT') return cb(err);
15006 if (stat && stat.isDirectory()) return cb(errno.EISDIR(key));
15007 if (stat && flags[1] === 'x') return cb(errno.EEXIST(key));
15008
15009 var blob = stat && stat.blob || key;
15010 ps.writable(key, function(err) {
15011 if (err) return cb(err);
15012
15013 bl.write(blob, data, opts, function(err) {
15014 if (err) return cb(err);
15015
15016 ps.put(key, {
15017 ctime: stat && stat.ctime,
15018 mtime: new Date(),
15019 mode: opts.mode || 0666,
15020 type:'file'
15021 }, listeners.cb(key, cb));
15022 });
15023 });
15024 });
15025 };
15026
15027 fs.appendFile = function(key, data, opts, cb) {
15028 if (typeof opts === 'function') return fs.appendFile(key, data, null, opts);
15029 if (typeof opts === 'string') opts = {encoding:opts};
15030 if (!opts) opts = {};
15031
15032 opts.flags = 'a';
15033 fs.writeFile(key, data, opts, cb);
15034 };
15035
15036 fs.unlink = function(key, cb) {
15037 if (!cb) cb = noop;
15038
15039 ps.get(key, function(err, stat, key) {
15040 if (err) return cb(err);
15041 if (stat.isDirectory()) return cb(errno.EISDIR(key));
15042
15043 var clean = function(target) {
15044 peek(links, {start:target+'\xff', end:target+'\xff\xff'}, function(err) {
15045 if (err) return bl.remove(target, cb); // no more links
15046 cb();
15047 });
15048 };
15049
15050 var onlink = function() {
15051 var target = stat.link.slice(0, stat.link.indexOf('\xff'));
15052 links.del(stat.link, function(err) {
15053 if (err) return cb(err);
15054 clean(target);
15055 });
15056 };
15057
15058 ps.del(key, listeners.cb(key, function(err) {
15059 if (err) return cb(err);
15060 if (stat.link) return onlink();
15061 links.del(key+'\xff', function(err) {
15062 if (err) return cb(err);
15063 clean(key);
15064 });
15065 }));
15066 });
15067 };
15068
15069 fs.readFile = function(key, opts, cb) {
15070 if (typeof opts === 'function') return fs.readFile(key, null, opts);
15071 if (typeof opts === 'string') opts = {encoding:opts};
15072 if (!opts) opts = {};
15073
15074 var encoding = opts.encoding || 'binary';
15075 var flag = opts.flag || 'r';
15076
15077 ps.follow(key, function(err, stat, key) {
15078 if (err) return cb(err);
15079 if (stat.isDirectory()) return cb(errno.EISDIR(key));
15080
15081 var blob = stat && stat.blob || key;
15082 bl.read(blob, function(err, data) {
15083 if (err) return cb(err);
15084 cb(null, opts.encoding ? data.toString(opts.encoding) : data);
15085 });
15086 });
15087 };
15088
15089 fs.createReadStream = function(key, opts) {
15090 if (!opts) opts = {};
15091
15092 var closed = false;
15093 var rs = fwd.readable(function(cb) {
15094 ps.follow(key, function(err, stat, key) {
15095 if (err) return cb(err);
15096 if (stat.isDirectory()) return cb(errno.EISDIR(key));
15097
15098 var blob = stat && stat.blob || key;
15099 var r = bl.createReadStream(blob, opts);
15100
15101 rs.emit('open');
15102 r.on('end', function() {
15103 process.nextTick(function() {
15104 if (!closed) rs.emit('close');
15105 });
15106 });
15107
15108 cb(null, r);
15109 });
15110 });
15111
15112 rs.on('close', function() {
15113 closed = true;
15114 });
15115
15116 return rs;
15117 };
15118
15119 fs.createWriteStream = function(key, opts) {
15120 if (!opts) opts = {};
15121
15122 var flags = opts.flags || 'w';
15123 var closed = false;
15124 var mode = opts.mode || 0666;
15125
15126 opts.append = flags[0] === 'a';
15127
15128 var ws = fwd.writable(function(cb) {
15129 ps.follow(key, function(err, stat, key) {
15130 if (err && err.code !== 'ENOENT') return cb(err);
15131 if (stat && stat.isDirectory()) return cb(errno.EISDIR(key));
15132 if (stat && flags[1] === 'x') return cb(errno.EEXIST(key));
15133
15134 var blob = stat && stat.blob || key;
15135 ps.writable(blob, function(err) {
15136 if (err) return cb(err);
15137
15138 var ctime = stat ? stat.ctime : new Date();
15139 var s = {
15140 ctime: ctime,
15141 mtime: new Date(),
15142 mode: mode,
15143 type:'file'
15144 };
15145
15146 ps.put(key, s, function(err) {
15147 if (err) return cb(err);
15148
15149 var w = bl.createWriteStream(blob, opts);
15150
15151 ws.emit('open');
15152 w.on('finish', function() {
15153 s.mtime = new Date();
15154 ps.put(key, s, function() {
15155 listeners.change(key);
15156 if (!closed) ws.emit('close');
15157 });
15158 });
15159
15160 cb(null, w);
15161 });
15162 });
15163 });
15164 });
15165
15166 ws.on('close', function() {
15167 closed = true;
15168 });
15169
15170 return ws;
15171 };
15172
15173 fs.truncate = function(key, len, cb) {
15174 ps.follow(key, function(err, stat, key) {
15175 if (err) return cb(err);
15176
15177 var blob = stat && stat.blob || key;
15178 bl.size(blob, function(err, size) {
15179 if (err) return cb(err);
15180
15181 ps.writable(key, function(err) {
15182 if (err) return cb(err);
15183
15184 cb = once(listeners.cb(key, cb));
15185 if (!len) return bl.remove(blob, cb);
15186
15187 var ws = bl.createWriteStream(blob, {
15188 start:size < len ? len-1 : len
15189 });
15190
15191 ws.on('error', cb);
15192 ws.on('finish', cb);
15193
15194 if (size < len) ws.write(new Buffer([0]));
15195 ws.end();
15196 });
15197 });
15198 });
15199 };
15200
15201 fs.watchFile = function(key, opts, cb) {
15202 if (typeof opts === 'function') return fs.watchFile(key, null, opts);
15203 return listeners.watch(ps.normalize(key), cb);
15204 };
15205
15206 fs.unwatchFile = function(key, cb) {
15207 listeners.unwatch(ps.normalize(key), cb);
15208 };
15209
15210 fs.watch = function(key, opts, cb) {
15211 if (typeof opts === 'function') return fs.watch(key, null, opts)
15212 return listeners.watcher(ps.normalize(key), cb);
15213 };
15214
15215 fs.notify = function(cb) {
15216 listeners.on('change', cb)
15217 }
15218
15219 fs.open = function(key, flags, mode, cb) {
15220 if (typeof mode === 'function') return fs.open(key, flags, null, mode);
15221
15222 ps.follow(key, function(err, stat, key) {
15223 if (err && err.code !== 'ENOENT') return cb(err);
15224
15225 var fl = flags[0];
15226 var plus = flags[1] === '+' || flags[2] === '+';
15227 var blob = stat && stat.blob || key;
15228
15229 var f = {
15230 key: key,
15231 blob: blob,
15232 mode: mode || 0666,
15233 readable: fl === 'r' || ((fl === 'w' || fl === 'a') && plus),
15234 writable: fl === 'w' || fl === 'a' || (fl === 'r' && plus),
15235 append: fl === 'a'
15236 };
15237
15238 if (fl === 'r' && err) return cb(err);
15239 if (flags[1] === 'x' && stat) return cb(errno.EEXIST(key));
15240 if (stat && stat.isDirectory()) return cb(errno.EISDIR(key));
15241
15242 bl.size(blob, function(err, size) {
15243 if (err) return cb(err);
15244
15245 if (f.append) f.writePos = size;
15246
15247 ps.writable(key, function(err) {
15248 if (err) return cb(err);
15249
15250 var onready = function(err) {
15251 if (err) return cb(err);
15252
15253 var i = fds.indexOf(null);
15254 if (i === -1) i = 10+fds.push(fds.length+10)-1;
15255
15256 f.fd = i;
15257 fds[i] = f;
15258 listeners.change(key);
15259
15260 cb(null, f.fd);
15261 };
15262
15263 var ontruncate = function(err) {
15264 if (err) return cb(err);
15265 if (stat) return onready();
15266 ps.put(blob, {ctime:stat && stat.ctime, type:'file'}, onready);
15267 };
15268
15269 if (!f.append && f.writable) return bl.remove(blob, ontruncate);
15270 ontruncate();
15271 });
15272 });
15273 });
15274 };
15275
15276 fs.close = function(fd, cb) {
15277 var f = fds[fd];
15278 if (!f) return nextTick(cb, errno.EBADF());
15279
15280 fds[fd] = null;
15281 nextTick(listeners.cb(f.key, cb));
15282 };
15283
15284 fs.write = function(fd, buf, off, len, pos, cb) {
15285 var f = fds[fd];
15286 if (!cb) cb = noop;
15287 if (!f || !f.writable) return nextTick(cb, errno.EBADF());
15288
15289 if (pos === null) pos = f.writePos || 0;
15290
15291 var slice = buf.slice(off, off+len);
15292 f.writePos = pos + slice.length;
15293
15294 bl.write(f.blob, slice, {start:pos, append:true}, function(err) {
15295 if (err) return cb(err);
15296 cb(null, len, buf);
15297 });
15298 };
15299
15300 fs.read = function(fd, buf, off, len, pos, cb) {
15301 var f = fds[fd];
15302 if (!cb) cb = noop;
15303 if (!f || !f.readable) return nextTick(cb, errno.EBADF());
15304
15305 if (pos === null) pos = fs.readPos || 0;
15306
15307 bl.read(f.blob, {start:pos, end:pos+len-1}, function(err, read) {
15308 if (err) return cb(err);
15309 var slice = read.slice(0, len);
15310 slice.copy(buf, off);
15311 fs.readPos = pos+slice.length;
15312 cb(null, slice.length, buf);
15313 });
15314 };
15315
15316 fs.fsync = function(fd, cb) {
15317 var f = fds[fd];
15318 if (!cb) cb = noop;
15319 if (!f || !f.writable) return nextTick(cb, errno.EBADF());
15320
15321 nextTick(cb);
15322 };
15323
15324 fs.ftruncate = function(fd, len, cb) {
15325 var f = fds[fd];
15326 if (!cb) cb = noop;
15327 if (!f) return nextTick(cb, errno.EBADF());
15328
15329 fs.truncate(f.blob, len, cb);
15330 };
15331
15332 fs.fchown = function(fd, uid, gid, cb) {
15333 var f = fds[fd];
15334 if (!cb) cb = noop;
15335 if (!f) return nextTick(cb, errno.EBADF());
15336
15337 fs.chown(f.key, uid, gid, cb);
15338 };
15339
15340 fs.fchmod = function(fd, mode, cb) {
15341 var f = fds[fd];
15342 if (!cb) cb = noop;
15343 if (!f) return nextTick(cb, errno.EBADF());
15344
15345 fs.chmod(f.key, mode, cb);
15346 };
15347
15348 fs.futimes = function(fd, atime, mtime, cb) {
15349 var f = fds[fd];
15350 if (!cb) cb = noop;
15351 if (!f) return nextTick(cb, errno.EBADF());
15352
15353 fs.utimes(f.key, atime, mtime, cb);
15354 };
15355
15356 fs.fstat = function(fd, cb) {
15357 var f = fds[fd];
15358 if (!f) return nextTick(cb, errno.EBADF());
15359
15360 fs.stat(f.key, cb);
15361 };
15362
15363 fs.symlink = function(target, name, cb) {
15364 if (!cb) cb = noop;
15365 ps.follow(target, function(err, stat, target) {
15366 if (err) return cb(err);
15367 ps.get(name, function(err, stat) {
15368 if (err && err.code !== 'ENOENT') return cb(err);
15369 if (stat) return cb(errno.EEXIST(name));
15370 ps.put(name, {type:'symlink', target:target, mode:0777}, cb);
15371 });
15372 });
15373 };
15374
15375 fs.readlink = function(key, cb) {
15376 ps.get(key, function(err, stat) {
15377 if (err) return cb(err);
15378 if (!stat.target) return cb(errno.EINVAL(key));
15379 cb(null, stat.target);
15380 });
15381 };
15382
15383 fs.link = function(target, name, cb) {
15384 if (!cb) cb = noop;
15385 ps.follow(target, function(err, stat, target) {
15386 if (err) return cb(err);
15387 if (!stat.isFile()) return cb(errno.EINVAL(target));
15388 ps.get(name, function(err, st) {
15389 if (err && err.code !== 'ENOENT') return cb(err);
15390 if (st) return cb(errno.EEXIST(name));
15391 var link = target+'\xff'+inc();
15392 links.put(target+'\xff', target, function(err) {
15393 if (err) return cb(err);
15394 links.put(link, target, function(err) {
15395 if (err) return cb(err);
15396 ps.put(name, {type:'file', link:link, blob:target, mode:stat.mode}, cb);
15397 });
15398 });
15399 });
15400 });
15401 };
15402
15403 return fs;
15404};}, {"fwd-stream":84,"level-sublevel":96,"level-blobs":109,"level-peek":120,"once":122,"./errno":124,"./paths":128,"./watchers":145}],84: [function (exports, require, module, global) {var Writable = require('readable-stream/writable');
15405var Readable = require('readable-stream/readable');
15406var Duplex = require('readable-stream/duplex');
15407
15408var DUMMY = new Buffer(0);
15409var noop = function() {};
15410
15411var toFunction = function(fn) {
15412 if (typeof fn === 'function') return fn;
15413 return function(cb) {
15414 cb(null, fn);
15415 };
15416};
15417
15418var onreadable = function(rs, init) {
15419 var reading = false;
15420 var destroyed = false;
15421
15422 rs._read = function() {
15423 reading = true;
15424 };
15425
15426 rs.destroy = function() {
15427 destroyed = true;
15428 };
15429
15430 init(function(err, source) {
15431 if (err) return rs.emit('error', err);
15432
15433 var fwd = function() {
15434 var data;
15435 while ((data = source.read()) !== null) {
15436 reading = false;
15437 rs.push(data);
15438 }
15439 };
15440
15441 source.on('readable', function() {
15442 if (reading) fwd();
15443 });
15444
15445 source.on('end', function() {
15446 fwd();
15447 rs.push(null);
15448 });
15449
15450 source.on('error', function(err) {
15451 rs.emit('error', err);
15452 });
15453
15454 source.on('close', function() {
15455 fwd();
15456 process.nextTick(function() {
15457 rs.emit('close');
15458 });
15459 });
15460
15461 rs._read = function() {
15462 reading = true;
15463 fwd();
15464 };
15465
15466 rs.destroy = function() {
15467 if (destroyed) return;
15468 destroyed = true;
15469 if (source.destroy) source.destroy();
15470 };
15471
15472 if (destroyed) {
15473 destroyed = false;
15474 rs.destroy();
15475 return;
15476 }
15477
15478 if (reading) fwd();
15479 });
15480
15481 return rs;
15482};
15483
15484var onwritable = function(ws, init) {
15485 var ready = noop;
15486 var destroyed = false;
15487
15488 ws._write = function(data, enc, cb) {
15489 ready = cb;
15490 };
15491
15492 ws.destroy = function() {
15493 destroyed = true;
15494 };
15495
15496 ws.write(DUMMY);
15497
15498 init(function(err, source) {
15499 if (err) return ws.emit('error', err);
15500
15501 source.on('close', function() {
15502 ws.emit('close');
15503 });
15504
15505 source.on('error', function(err) {
15506 ws.emit('error', err);
15507 });
15508
15509 ws._write = function(data, enc, cb) {
15510 if (data === DUMMY) return cb();
15511 source.write(data, enc, cb);
15512 };
15513
15514 var emit = ws.emit;
15515
15516 source.on('finish', function() {
15517 emit.call(ws, 'finish');
15518 });
15519
15520 ws.destroy = function() {
15521 if (destroyed) return;
15522 destroyed = true;
15523 if (source.destroy) source.destroy();
15524 };
15525
15526 ws.emit = function(name) {
15527 if (name !== 'finish') return emit.apply(ws, arguments);
15528 source.end();
15529 };
15530
15531 if (destroyed) {
15532 destroyed = false;
15533 ws.destroy();
15534 return;
15535 }
15536
15537 ready();
15538 });
15539
15540 return ws;
15541};
15542
15543exports.readable = function(opts, init) {
15544 if (arguments.length === 1) return exports.readable(null, opts);
15545 if (!opts) opts = {};
15546 return onreadable(new Readable(opts), toFunction(init));
15547};
15548
15549exports.writable = function(opts, init) {
15550 if (arguments.length === 1) return exports.writable(null, opts);
15551 if (!opts) opts = {};
15552 return onwritable(new Writable(opts), toFunction(init));
15553};
15554
15555exports.duplex = function(opts, initWritable, initReadable) {
15556 if (arguments.length === 2) return exports.duplex(null, opts, initWritable);
15557 if (!opts) opts = {};
15558 var dupl = new Duplex(opts);
15559 onwritable(dupl, toFunction(initWritable));
15560 onreadable(dupl, toFunction(initReadable));
15561 return dupl;
15562};}, {"readable-stream/writable":85,"readable-stream/readable":92,"readable-stream/duplex":95}],85: [function (exports, require, module, global) {module.exports = require("./lib/_stream_writable.js")
15563}, {"./lib/_stream_writable.js":86}],86: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
15564//
15565// Permission is hereby granted, free of charge, to any person obtaining a
15566// copy of this software and associated documentation files (the
15567// "Software"), to deal in the Software without restriction, including
15568// without limitation the rights to use, copy, modify, merge, publish,
15569// distribute, sublicense, and/or sell copies of the Software, and to permit
15570// persons to whom the Software is furnished to do so, subject to the
15571// following conditions:
15572//
15573// The above copyright notice and this permission notice shall be included
15574// in all copies or substantial portions of the Software.
15575//
15576// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15577// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15578// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15579// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15580// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15581// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15582// USE OR OTHER DEALINGS IN THE SOFTWARE.
15583
15584// A bit simpler than readable streams.
15585// Implement an async ._write(chunk, cb), and it'll handle all
15586// the drain event emission and buffering.
15587
15588module.exports = Writable;
15589
15590/*<replacement>*/
15591var Buffer = require('buffer').Buffer;
15592/*</replacement>*/
15593
15594Writable.WritableState = WritableState;
15595
15596
15597/*<replacement>*/
15598var util = require('core-util-is');
15599util.inherits = require('inherits');
15600/*</replacement>*/
15601
15602var Stream = require('stream');
15603
15604util.inherits(Writable, Stream);
15605
15606function WriteReq(chunk, encoding, cb) {
15607 this.chunk = chunk;
15608 this.encoding = encoding;
15609 this.callback = cb;
15610}
15611
15612function WritableState(options, stream) {
15613 options = options || {};
15614
15615 // the point at which write() starts returning false
15616 // Note: 0 is a valid value, means that we always return false if
15617 // the entire buffer is not flushed immediately on write()
15618 var hwm = options.highWaterMark;
15619 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
15620
15621 // object stream flag to indicate whether or not this stream
15622 // contains buffers or objects.
15623 this.objectMode = !!options.objectMode;
15624
15625 // cast to ints.
15626 this.highWaterMark = ~~this.highWaterMark;
15627
15628 this.needDrain = false;
15629 // at the start of calling end()
15630 this.ending = false;
15631 // when end() has been called, and returned
15632 this.ended = false;
15633 // when 'finish' is emitted
15634 this.finished = false;
15635
15636 // should we decode strings into buffers before passing to _write?
15637 // this is here so that some node-core streams can optimize string
15638 // handling at a lower level.
15639 var noDecode = options.decodeStrings === false;
15640 this.decodeStrings = !noDecode;
15641
15642 // Crypto is kind of old and crusty. Historically, its default string
15643 // encoding is 'binary' so we have to make this configurable.
15644 // Everything else in the universe uses 'utf8', though.
15645 this.defaultEncoding = options.defaultEncoding || 'utf8';
15646
15647 // not an actual buffer we keep track of, but a measurement
15648 // of how much we're waiting to get pushed to some underlying
15649 // socket or file.
15650 this.length = 0;
15651
15652 // a flag to see when we're in the middle of a write.
15653 this.writing = false;
15654
15655 // a flag to be able to tell if the onwrite cb is called immediately,
15656 // or on a later tick. We set this to true at first, becuase any
15657 // actions that shouldn't happen until "later" should generally also
15658 // not happen before the first write call.
15659 this.sync = true;
15660
15661 // a flag to know if we're processing previously buffered items, which
15662 // may call the _write() callback in the same tick, so that we don't
15663 // end up in an overlapped onwrite situation.
15664 this.bufferProcessing = false;
15665
15666 // the callback that's passed to _write(chunk,cb)
15667 this.onwrite = function(er) {
15668 onwrite(stream, er);
15669 };
15670
15671 // the callback that the user supplies to write(chunk,encoding,cb)
15672 this.writecb = null;
15673
15674 // the amount that is being written when _write is called.
15675 this.writelen = 0;
15676
15677 this.buffer = [];
15678
15679 // True if the error was already emitted and should not be thrown again
15680 this.errorEmitted = false;
15681}
15682
15683function Writable(options) {
15684 var Duplex = require('./_stream_duplex');
15685
15686 // Writable ctor is applied to Duplexes, though they're not
15687 // instanceof Writable, they're instanceof Readable.
15688 if (!(this instanceof Writable) && !(this instanceof Duplex))
15689 return new Writable(options);
15690
15691 this._writableState = new WritableState(options, this);
15692
15693 // legacy.
15694 this.writable = true;
15695
15696 Stream.call(this);
15697}
15698
15699// Otherwise people can pipe Writable streams, which is just wrong.
15700Writable.prototype.pipe = function() {
15701 this.emit('error', new Error('Cannot pipe. Not readable.'));
15702};
15703
15704
15705function writeAfterEnd(stream, state, cb) {
15706 var er = new Error('write after end');
15707 // TODO: defer error events consistently everywhere, not just the cb
15708 stream.emit('error', er);
15709 process.nextTick(function() {
15710 cb(er);
15711 });
15712}
15713
15714// If we get something that is not a buffer, string, null, or undefined,
15715// and we're not in objectMode, then that's an error.
15716// Otherwise stream chunks are all considered to be of length=1, and the
15717// watermarks determine how many objects to keep in the buffer, rather than
15718// how many bytes or characters.
15719function validChunk(stream, state, chunk, cb) {
15720 var valid = true;
15721 if (!Buffer.isBuffer(chunk) &&
15722 'string' !== typeof chunk &&
15723 chunk !== null &&
15724 chunk !== undefined &&
15725 !state.objectMode) {
15726 var er = new TypeError('Invalid non-string/buffer chunk');
15727 stream.emit('error', er);
15728 process.nextTick(function() {
15729 cb(er);
15730 });
15731 valid = false;
15732 }
15733 return valid;
15734}
15735
15736Writable.prototype.write = function(chunk, encoding, cb) {
15737 var state = this._writableState;
15738 var ret = false;
15739
15740 if (typeof encoding === 'function') {
15741 cb = encoding;
15742 encoding = null;
15743 }
15744
15745 if (Buffer.isBuffer(chunk))
15746 encoding = 'buffer';
15747 else if (!encoding)
15748 encoding = state.defaultEncoding;
15749
15750 if (typeof cb !== 'function')
15751 cb = function() {};
15752
15753 if (state.ended)
15754 writeAfterEnd(this, state, cb);
15755 else if (validChunk(this, state, chunk, cb))
15756 ret = writeOrBuffer(this, state, chunk, encoding, cb);
15757
15758 return ret;
15759};
15760
15761function decodeChunk(state, chunk, encoding) {
15762 if (!state.objectMode &&
15763 state.decodeStrings !== false &&
15764 typeof chunk === 'string') {
15765 chunk = new Buffer(chunk, encoding);
15766 }
15767 return chunk;
15768}
15769
15770// if we're already writing something, then just put this
15771// in the queue, and wait our turn. Otherwise, call _write
15772// If we return false, then we need a drain event, so set that flag.
15773function writeOrBuffer(stream, state, chunk, encoding, cb) {
15774 chunk = decodeChunk(state, chunk, encoding);
15775 if (Buffer.isBuffer(chunk))
15776 encoding = 'buffer';
15777 var len = state.objectMode ? 1 : chunk.length;
15778
15779 state.length += len;
15780
15781 var ret = state.length < state.highWaterMark;
15782 // we must ensure that previous needDrain will not be reset to false.
15783 if (!ret)
15784 state.needDrain = true;
15785
15786 if (state.writing)
15787 state.buffer.push(new WriteReq(chunk, encoding, cb));
15788 else
15789 doWrite(stream, state, len, chunk, encoding, cb);
15790
15791 return ret;
15792}
15793
15794function doWrite(stream, state, len, chunk, encoding, cb) {
15795 state.writelen = len;
15796 state.writecb = cb;
15797 state.writing = true;
15798 state.sync = true;
15799 stream._write(chunk, encoding, state.onwrite);
15800 state.sync = false;
15801}
15802
15803function onwriteError(stream, state, sync, er, cb) {
15804 if (sync)
15805 process.nextTick(function() {
15806 cb(er);
15807 });
15808 else
15809 cb(er);
15810
15811 stream._writableState.errorEmitted = true;
15812 stream.emit('error', er);
15813}
15814
15815function onwriteStateUpdate(state) {
15816 state.writing = false;
15817 state.writecb = null;
15818 state.length -= state.writelen;
15819 state.writelen = 0;
15820}
15821
15822function onwrite(stream, er) {
15823 var state = stream._writableState;
15824 var sync = state.sync;
15825 var cb = state.writecb;
15826
15827 onwriteStateUpdate(state);
15828
15829 if (er)
15830 onwriteError(stream, state, sync, er, cb);
15831 else {
15832 // Check if we're actually ready to finish, but don't emit yet
15833 var finished = needFinish(stream, state);
15834
15835 if (!finished && !state.bufferProcessing && state.buffer.length)
15836 clearBuffer(stream, state);
15837
15838 if (sync) {
15839 process.nextTick(function() {
15840 afterWrite(stream, state, finished, cb);
15841 });
15842 } else {
15843 afterWrite(stream, state, finished, cb);
15844 }
15845 }
15846}
15847
15848function afterWrite(stream, state, finished, cb) {
15849 if (!finished)
15850 onwriteDrain(stream, state);
15851 cb();
15852 if (finished)
15853 finishMaybe(stream, state);
15854}
15855
15856// Must force callback to be called on nextTick, so that we don't
15857// emit 'drain' before the write() consumer gets the 'false' return
15858// value, and has a chance to attach a 'drain' listener.
15859function onwriteDrain(stream, state) {
15860 if (state.length === 0 && state.needDrain) {
15861 state.needDrain = false;
15862 stream.emit('drain');
15863 }
15864}
15865
15866
15867// if there's something in the buffer waiting, then process it
15868function clearBuffer(stream, state) {
15869 state.bufferProcessing = true;
15870
15871 for (var c = 0; c < state.buffer.length; c++) {
15872 var entry = state.buffer[c];
15873 var chunk = entry.chunk;
15874 var encoding = entry.encoding;
15875 var cb = entry.callback;
15876 var len = state.objectMode ? 1 : chunk.length;
15877
15878 doWrite(stream, state, len, chunk, encoding, cb);
15879
15880 // if we didn't call the onwrite immediately, then
15881 // it means that we need to wait until it does.
15882 // also, that means that the chunk and cb are currently
15883 // being processed, so move the buffer counter past them.
15884 if (state.writing) {
15885 c++;
15886 break;
15887 }
15888 }
15889
15890 state.bufferProcessing = false;
15891 if (c < state.buffer.length)
15892 state.buffer = state.buffer.slice(c);
15893 else
15894 state.buffer.length = 0;
15895}
15896
15897Writable.prototype._write = function(chunk, encoding, cb) {
15898 cb(new Error('not implemented'));
15899};
15900
15901Writable.prototype.end = function(chunk, encoding, cb) {
15902 var state = this._writableState;
15903
15904 if (typeof chunk === 'function') {
15905 cb = chunk;
15906 chunk = null;
15907 encoding = null;
15908 } else if (typeof encoding === 'function') {
15909 cb = encoding;
15910 encoding = null;
15911 }
15912
15913 if (typeof chunk !== 'undefined' && chunk !== null)
15914 this.write(chunk, encoding);
15915
15916 // ignore unnecessary end() calls.
15917 if (!state.ending && !state.finished)
15918 endWritable(this, state, cb);
15919};
15920
15921
15922function needFinish(stream, state) {
15923 return (state.ending &&
15924 state.length === 0 &&
15925 !state.finished &&
15926 !state.writing);
15927}
15928
15929function finishMaybe(stream, state) {
15930 var need = needFinish(stream, state);
15931 if (need) {
15932 state.finished = true;
15933 stream.emit('finish');
15934 }
15935 return need;
15936}
15937
15938function endWritable(stream, state, cb) {
15939 state.ending = true;
15940 finishMaybe(stream, state);
15941 if (cb) {
15942 if (state.finished)
15943 process.nextTick(cb);
15944 else
15945 stream.once('finish', cb);
15946 }
15947 state.ended = true;
15948}
15949}, {"buffer":29,"core-util-is":87,"inherits":88,"stream":52,"./_stream_duplex":89}],87: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
15950//
15951// Permission is hereby granted, free of charge, to any person obtaining a
15952// copy of this software and associated documentation files (the
15953// "Software"), to deal in the Software without restriction, including
15954// without limitation the rights to use, copy, modify, merge, publish,
15955// distribute, sublicense, and/or sell copies of the Software, and to permit
15956// persons to whom the Software is furnished to do so, subject to the
15957// following conditions:
15958//
15959// The above copyright notice and this permission notice shall be included
15960// in all copies or substantial portions of the Software.
15961//
15962// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15963// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15964// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15965// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15966// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15967// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15968// USE OR OTHER DEALINGS IN THE SOFTWARE.
15969
15970// NOTE: These type checking functions intentionally don't use `instanceof`
15971// because it is fragile and can be easily faked with `Object.create()`.
15972function isArray(ar) {
15973 return Array.isArray(ar);
15974}
15975exports.isArray = isArray;
15976
15977function isBoolean(arg) {
15978 return typeof arg === 'boolean';
15979}
15980exports.isBoolean = isBoolean;
15981
15982function isNull(arg) {
15983 return arg === null;
15984}
15985exports.isNull = isNull;
15986
15987function isNullOrUndefined(arg) {
15988 return arg == null;
15989}
15990exports.isNullOrUndefined = isNullOrUndefined;
15991
15992function isNumber(arg) {
15993 return typeof arg === 'number';
15994}
15995exports.isNumber = isNumber;
15996
15997function isString(arg) {
15998 return typeof arg === 'string';
15999}
16000exports.isString = isString;
16001
16002function isSymbol(arg) {
16003 return typeof arg === 'symbol';
16004}
16005exports.isSymbol = isSymbol;
16006
16007function isUndefined(arg) {
16008 return arg === void 0;
16009}
16010exports.isUndefined = isUndefined;
16011
16012function isRegExp(re) {
16013 return isObject(re) && objectToString(re) === '[object RegExp]';
16014}
16015exports.isRegExp = isRegExp;
16016
16017function isObject(arg) {
16018 return typeof arg === 'object' && arg !== null;
16019}
16020exports.isObject = isObject;
16021
16022function isDate(d) {
16023 return isObject(d) && objectToString(d) === '[object Date]';
16024}
16025exports.isDate = isDate;
16026
16027function isError(e) {
16028 return isObject(e) &&
16029 (objectToString(e) === '[object Error]' || e instanceof Error);
16030}
16031exports.isError = isError;
16032
16033function isFunction(arg) {
16034 return typeof arg === 'function';
16035}
16036exports.isFunction = isFunction;
16037
16038function isPrimitive(arg) {
16039 return arg === null ||
16040 typeof arg === 'boolean' ||
16041 typeof arg === 'number' ||
16042 typeof arg === 'string' ||
16043 typeof arg === 'symbol' || // ES6 symbol
16044 typeof arg === 'undefined';
16045}
16046exports.isPrimitive = isPrimitive;
16047
16048function isBuffer(arg) {
16049 return Buffer.isBuffer(arg);
16050}
16051exports.isBuffer = isBuffer;
16052
16053function objectToString(o) {
16054 return Object.prototype.toString.call(o);
16055}}, {}],88: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
16056 // implementation from standard node.js 'util' module
16057 module.exports = function inherits(ctor, superCtor) {
16058 ctor.super_ = superCtor
16059 ctor.prototype = Object.create(superCtor.prototype, {
16060 constructor: {
16061 value: ctor,
16062 enumerable: false,
16063 writable: true,
16064 configurable: true
16065 }
16066 });
16067 };
16068} else {
16069 // old school shim for old browsers
16070 module.exports = function inherits(ctor, superCtor) {
16071 ctor.super_ = superCtor
16072 var TempCtor = function () {}
16073 TempCtor.prototype = superCtor.prototype
16074 ctor.prototype = new TempCtor()
16075 ctor.prototype.constructor = ctor
16076 }
16077}
16078}, {}],89: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
16079//
16080// Permission is hereby granted, free of charge, to any person obtaining a
16081// copy of this software and associated documentation files (the
16082// "Software"), to deal in the Software without restriction, including
16083// without limitation the rights to use, copy, modify, merge, publish,
16084// distribute, sublicense, and/or sell copies of the Software, and to permit
16085// persons to whom the Software is furnished to do so, subject to the
16086// following conditions:
16087//
16088// The above copyright notice and this permission notice shall be included
16089// in all copies or substantial portions of the Software.
16090//
16091// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16092// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16093// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16094// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16095// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16096// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16097// USE OR OTHER DEALINGS IN THE SOFTWARE.
16098
16099// a duplex stream is just a stream that is both readable and writable.
16100// Since JS doesn't have multiple prototypal inheritance, this class
16101// prototypally inherits from Readable, and then parasitically from
16102// Writable.
16103
16104module.exports = Duplex;
16105
16106/*<replacement>*/
16107var objectKeys = Object.keys || function (obj) {
16108 var keys = [];
16109 for (var key in obj) keys.push(key);
16110 return keys;
16111}
16112/*</replacement>*/
16113
16114
16115/*<replacement>*/
16116var util = require('core-util-is');
16117util.inherits = require('inherits');
16118/*</replacement>*/
16119
16120var Readable = require('./_stream_readable');
16121var Writable = require('./_stream_writable');
16122
16123util.inherits(Duplex, Readable);
16124
16125forEach(objectKeys(Writable.prototype), function(method) {
16126 if (!Duplex.prototype[method])
16127 Duplex.prototype[method] = Writable.prototype[method];
16128});
16129
16130function Duplex(options) {
16131 if (!(this instanceof Duplex))
16132 return new Duplex(options);
16133
16134 Readable.call(this, options);
16135 Writable.call(this, options);
16136
16137 if (options && options.readable === false)
16138 this.readable = false;
16139
16140 if (options && options.writable === false)
16141 this.writable = false;
16142
16143 this.allowHalfOpen = true;
16144 if (options && options.allowHalfOpen === false)
16145 this.allowHalfOpen = false;
16146
16147 this.once('end', onend);
16148}
16149
16150// the no-half-open enforcer
16151function onend() {
16152 // if we allow half-open state, or if the writable side ended,
16153 // then we're ok.
16154 if (this.allowHalfOpen || this._writableState.ended)
16155 return;
16156
16157 // no more data can be written.
16158 // But allow more writes to happen in this tick.
16159 process.nextTick(this.end.bind(this));
16160}
16161
16162function forEach (xs, f) {
16163 for (var i = 0, l = xs.length; i < l; i++) {
16164 f(xs[i], i);
16165 }
16166}
16167}, {"core-util-is":87,"inherits":88,"./_stream_readable":90,"./_stream_writable":86}],90: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
16168//
16169// Permission is hereby granted, free of charge, to any person obtaining a
16170// copy of this software and associated documentation files (the
16171// "Software"), to deal in the Software without restriction, including
16172// without limitation the rights to use, copy, modify, merge, publish,
16173// distribute, sublicense, and/or sell copies of the Software, and to permit
16174// persons to whom the Software is furnished to do so, subject to the
16175// following conditions:
16176//
16177// The above copyright notice and this permission notice shall be included
16178// in all copies or substantial portions of the Software.
16179//
16180// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16181// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16182// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16183// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16184// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16185// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16186// USE OR OTHER DEALINGS IN THE SOFTWARE.
16187
16188module.exports = Readable;
16189
16190/*<replacement>*/
16191var isArray = require('isarray');
16192/*</replacement>*/
16193
16194
16195/*<replacement>*/
16196var Buffer = require('buffer').Buffer;
16197/*</replacement>*/
16198
16199Readable.ReadableState = ReadableState;
16200
16201var EE = require('events').EventEmitter;
16202
16203/*<replacement>*/
16204if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
16205 return emitter.listeners(type).length;
16206};
16207/*</replacement>*/
16208
16209var Stream = require('stream');
16210
16211/*<replacement>*/
16212var util = require('core-util-is');
16213util.inherits = require('inherits');
16214/*</replacement>*/
16215
16216var StringDecoder;
16217
16218util.inherits(Readable, Stream);
16219
16220function ReadableState(options, stream) {
16221 options = options || {};
16222
16223 // the point at which it stops calling _read() to fill the buffer
16224 // Note: 0 is a valid value, means "don't call _read preemptively ever"
16225 var hwm = options.highWaterMark;
16226 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
16227
16228 // cast to ints.
16229 this.highWaterMark = ~~this.highWaterMark;
16230
16231 this.buffer = [];
16232 this.length = 0;
16233 this.pipes = null;
16234 this.pipesCount = 0;
16235 this.flowing = false;
16236 this.ended = false;
16237 this.endEmitted = false;
16238 this.reading = false;
16239
16240 // In streams that never have any data, and do push(null) right away,
16241 // the consumer can miss the 'end' event if they do some I/O before
16242 // consuming the stream. So, we don't emit('end') until some reading
16243 // happens.
16244 this.calledRead = false;
16245
16246 // a flag to be able to tell if the onwrite cb is called immediately,
16247 // or on a later tick. We set this to true at first, becuase any
16248 // actions that shouldn't happen until "later" should generally also
16249 // not happen before the first write call.
16250 this.sync = true;
16251
16252 // whenever we return null, then we set a flag to say
16253 // that we're awaiting a 'readable' event emission.
16254 this.needReadable = false;
16255 this.emittedReadable = false;
16256 this.readableListening = false;
16257
16258
16259 // object stream flag. Used to make read(n) ignore n and to
16260 // make all the buffer merging and length checks go away
16261 this.objectMode = !!options.objectMode;
16262
16263 // Crypto is kind of old and crusty. Historically, its default string
16264 // encoding is 'binary' so we have to make this configurable.
16265 // Everything else in the universe uses 'utf8', though.
16266 this.defaultEncoding = options.defaultEncoding || 'utf8';
16267
16268 // when piping, we only care about 'readable' events that happen
16269 // after read()ing all the bytes and not getting any pushback.
16270 this.ranOut = false;
16271
16272 // the number of writers that are awaiting a drain event in .pipe()s
16273 this.awaitDrain = 0;
16274
16275 // if true, a maybeReadMore has been scheduled
16276 this.readingMore = false;
16277
16278 this.decoder = null;
16279 this.encoding = null;
16280 if (options.encoding) {
16281 if (!StringDecoder)
16282 StringDecoder = require('string_decoder/').StringDecoder;
16283 this.decoder = new StringDecoder(options.encoding);
16284 this.encoding = options.encoding;
16285 }
16286}
16287
16288function Readable(options) {
16289 if (!(this instanceof Readable))
16290 return new Readable(options);
16291
16292 this._readableState = new ReadableState(options, this);
16293
16294 // legacy
16295 this.readable = true;
16296
16297 Stream.call(this);
16298}
16299
16300// Manually shove something into the read() buffer.
16301// This returns true if the highWaterMark has not been hit yet,
16302// similar to how Writable.write() returns true if you should
16303// write() some more.
16304Readable.prototype.push = function(chunk, encoding) {
16305 var state = this._readableState;
16306
16307 if (typeof chunk === 'string' && !state.objectMode) {
16308 encoding = encoding || state.defaultEncoding;
16309 if (encoding !== state.encoding) {
16310 chunk = new Buffer(chunk, encoding);
16311 encoding = '';
16312 }
16313 }
16314
16315 return readableAddChunk(this, state, chunk, encoding, false);
16316};
16317
16318// Unshift should *always* be something directly out of read()
16319Readable.prototype.unshift = function(chunk) {
16320 var state = this._readableState;
16321 return readableAddChunk(this, state, chunk, '', true);
16322};
16323
16324function readableAddChunk(stream, state, chunk, encoding, addToFront) {
16325 var er = chunkInvalid(state, chunk);
16326 if (er) {
16327 stream.emit('error', er);
16328 } else if (chunk === null || chunk === undefined) {
16329 state.reading = false;
16330 if (!state.ended)
16331 onEofChunk(stream, state);
16332 } else if (state.objectMode || chunk && chunk.length > 0) {
16333 if (state.ended && !addToFront) {
16334 var e = new Error('stream.push() after EOF');
16335 stream.emit('error', e);
16336 } else if (state.endEmitted && addToFront) {
16337 var e = new Error('stream.unshift() after end event');
16338 stream.emit('error', e);
16339 } else {
16340 if (state.decoder && !addToFront && !encoding)
16341 chunk = state.decoder.write(chunk);
16342
16343 // update the buffer info.
16344 state.length += state.objectMode ? 1 : chunk.length;
16345 if (addToFront) {
16346 state.buffer.unshift(chunk);
16347 } else {
16348 state.reading = false;
16349 state.buffer.push(chunk);
16350 }
16351
16352 if (state.needReadable)
16353 emitReadable(stream);
16354
16355 maybeReadMore(stream, state);
16356 }
16357 } else if (!addToFront) {
16358 state.reading = false;
16359 }
16360
16361 return needMoreData(state);
16362}
16363
16364
16365
16366// if it's past the high water mark, we can push in some more.
16367// Also, if we have no data yet, we can stand some
16368// more bytes. This is to work around cases where hwm=0,
16369// such as the repl. Also, if the push() triggered a
16370// readable event, and the user called read(largeNumber) such that
16371// needReadable was set, then we ought to push more, so that another
16372// 'readable' event will be triggered.
16373function needMoreData(state) {
16374 return !state.ended &&
16375 (state.needReadable ||
16376 state.length < state.highWaterMark ||
16377 state.length === 0);
16378}
16379
16380// backwards compatibility.
16381Readable.prototype.setEncoding = function(enc) {
16382 if (!StringDecoder)
16383 StringDecoder = require('string_decoder/').StringDecoder;
16384 this._readableState.decoder = new StringDecoder(enc);
16385 this._readableState.encoding = enc;
16386};
16387
16388// Don't raise the hwm > 128MB
16389var MAX_HWM = 0x800000;
16390function roundUpToNextPowerOf2(n) {
16391 if (n >= MAX_HWM) {
16392 n = MAX_HWM;
16393 } else {
16394 // Get the next highest power of 2
16395 n--;
16396 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
16397 n++;
16398 }
16399 return n;
16400}
16401
16402function howMuchToRead(n, state) {
16403 if (state.length === 0 && state.ended)
16404 return 0;
16405
16406 if (state.objectMode)
16407 return n === 0 ? 0 : 1;
16408
16409 if (n === null || isNaN(n)) {
16410 // only flow one buffer at a time
16411 if (state.flowing && state.buffer.length)
16412 return state.buffer[0].length;
16413 else
16414 return state.length;
16415 }
16416
16417 if (n <= 0)
16418 return 0;
16419
16420 // If we're asking for more than the target buffer level,
16421 // then raise the water mark. Bump up to the next highest
16422 // power of 2, to prevent increasing it excessively in tiny
16423 // amounts.
16424 if (n > state.highWaterMark)
16425 state.highWaterMark = roundUpToNextPowerOf2(n);
16426
16427 // don't have that much. return null, unless we've ended.
16428 if (n > state.length) {
16429 if (!state.ended) {
16430 state.needReadable = true;
16431 return 0;
16432 } else
16433 return state.length;
16434 }
16435
16436 return n;
16437}
16438
16439// you can override either this method, or the async _read(n) below.
16440Readable.prototype.read = function(n) {
16441 var state = this._readableState;
16442 state.calledRead = true;
16443 var nOrig = n;
16444 var ret;
16445
16446 if (typeof n !== 'number' || n > 0)
16447 state.emittedReadable = false;
16448
16449 // if we're doing read(0) to trigger a readable event, but we
16450 // already have a bunch of data in the buffer, then just trigger
16451 // the 'readable' event and move on.
16452 if (n === 0 &&
16453 state.needReadable &&
16454 (state.length >= state.highWaterMark || state.ended)) {
16455 emitReadable(this);
16456 return null;
16457 }
16458
16459 n = howMuchToRead(n, state);
16460
16461 // if we've ended, and we're now clear, then finish it up.
16462 if (n === 0 && state.ended) {
16463 ret = null;
16464
16465 // In cases where the decoder did not receive enough data
16466 // to produce a full chunk, then immediately received an
16467 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
16468 // howMuchToRead will see this and coerce the amount to
16469 // read to zero (because it's looking at the length of the
16470 // first <Buffer > in state.buffer), and we'll end up here.
16471 //
16472 // This can only happen via state.decoder -- no other venue
16473 // exists for pushing a zero-length chunk into state.buffer
16474 // and triggering this behavior. In this case, we return our
16475 // remaining data and end the stream, if appropriate.
16476 if (state.length > 0 && state.decoder) {
16477 ret = fromList(n, state);
16478 state.length -= ret.length;
16479 }
16480
16481 if (state.length === 0)
16482 endReadable(this);
16483
16484 return ret;
16485 }
16486
16487 // All the actual chunk generation logic needs to be
16488 // *below* the call to _read. The reason is that in certain
16489 // synthetic stream cases, such as passthrough streams, _read
16490 // may be a completely synchronous operation which may change
16491 // the state of the read buffer, providing enough data when
16492 // before there was *not* enough.
16493 //
16494 // So, the steps are:
16495 // 1. Figure out what the state of things will be after we do
16496 // a read from the buffer.
16497 //
16498 // 2. If that resulting state will trigger a _read, then call _read.
16499 // Note that this may be asynchronous, or synchronous. Yes, it is
16500 // deeply ugly to write APIs this way, but that still doesn't mean
16501 // that the Readable class should behave improperly, as streams are
16502 // designed to be sync/async agnostic.
16503 // Take note if the _read call is sync or async (ie, if the read call
16504 // has returned yet), so that we know whether or not it's safe to emit
16505 // 'readable' etc.
16506 //
16507 // 3. Actually pull the requested chunks out of the buffer and return.
16508
16509 // if we need a readable event, then we need to do some reading.
16510 var doRead = state.needReadable;
16511
16512 // if we currently have less than the highWaterMark, then also read some
16513 if (state.length - n <= state.highWaterMark)
16514 doRead = true;
16515
16516 // however, if we've ended, then there's no point, and if we're already
16517 // reading, then it's unnecessary.
16518 if (state.ended || state.reading)
16519 doRead = false;
16520
16521 if (doRead) {
16522 state.reading = true;
16523 state.sync = true;
16524 // if the length is currently zero, then we *need* a readable event.
16525 if (state.length === 0)
16526 state.needReadable = true;
16527 // call internal read method
16528 this._read(state.highWaterMark);
16529 state.sync = false;
16530 }
16531
16532 // If _read called its callback synchronously, then `reading`
16533 // will be false, and we need to re-evaluate how much data we
16534 // can return to the user.
16535 if (doRead && !state.reading)
16536 n = howMuchToRead(nOrig, state);
16537
16538 if (n > 0)
16539 ret = fromList(n, state);
16540 else
16541 ret = null;
16542
16543 if (ret === null) {
16544 state.needReadable = true;
16545 n = 0;
16546 }
16547
16548 state.length -= n;
16549
16550 // If we have nothing in the buffer, then we want to know
16551 // as soon as we *do* get something into the buffer.
16552 if (state.length === 0 && !state.ended)
16553 state.needReadable = true;
16554
16555 // If we happened to read() exactly the remaining amount in the
16556 // buffer, and the EOF has been seen at this point, then make sure
16557 // that we emit 'end' on the very next tick.
16558 if (state.ended && !state.endEmitted && state.length === 0)
16559 endReadable(this);
16560
16561 return ret;
16562};
16563
16564function chunkInvalid(state, chunk) {
16565 var er = null;
16566 if (!Buffer.isBuffer(chunk) &&
16567 'string' !== typeof chunk &&
16568 chunk !== null &&
16569 chunk !== undefined &&
16570 !state.objectMode) {
16571 er = new TypeError('Invalid non-string/buffer chunk');
16572 }
16573 return er;
16574}
16575
16576
16577function onEofChunk(stream, state) {
16578 if (state.decoder && !state.ended) {
16579 var chunk = state.decoder.end();
16580 if (chunk && chunk.length) {
16581 state.buffer.push(chunk);
16582 state.length += state.objectMode ? 1 : chunk.length;
16583 }
16584 }
16585 state.ended = true;
16586
16587 // if we've ended and we have some data left, then emit
16588 // 'readable' now to make sure it gets picked up.
16589 if (state.length > 0)
16590 emitReadable(stream);
16591 else
16592 endReadable(stream);
16593}
16594
16595// Don't emit readable right away in sync mode, because this can trigger
16596// another read() call => stack overflow. This way, it might trigger
16597// a nextTick recursion warning, but that's not so bad.
16598function emitReadable(stream) {
16599 var state = stream._readableState;
16600 state.needReadable = false;
16601 if (state.emittedReadable)
16602 return;
16603
16604 state.emittedReadable = true;
16605 if (state.sync)
16606 process.nextTick(function() {
16607 emitReadable_(stream);
16608 });
16609 else
16610 emitReadable_(stream);
16611}
16612
16613function emitReadable_(stream) {
16614 stream.emit('readable');
16615}
16616
16617
16618// at this point, the user has presumably seen the 'readable' event,
16619// and called read() to consume some data. that may have triggered
16620// in turn another _read(n) call, in which case reading = true if
16621// it's in progress.
16622// However, if we're not ended, or reading, and the length < hwm,
16623// then go ahead and try to read some more preemptively.
16624function maybeReadMore(stream, state) {
16625 if (!state.readingMore) {
16626 state.readingMore = true;
16627 process.nextTick(function() {
16628 maybeReadMore_(stream, state);
16629 });
16630 }
16631}
16632
16633function maybeReadMore_(stream, state) {
16634 var len = state.length;
16635 while (!state.reading && !state.flowing && !state.ended &&
16636 state.length < state.highWaterMark) {
16637 stream.read(0);
16638 if (len === state.length)
16639 // didn't get any data, stop spinning.
16640 break;
16641 else
16642 len = state.length;
16643 }
16644 state.readingMore = false;
16645}
16646
16647// abstract method. to be overridden in specific implementation classes.
16648// call cb(er, data) where data is <= n in length.
16649// for virtual (non-string, non-buffer) streams, "length" is somewhat
16650// arbitrary, and perhaps not very meaningful.
16651Readable.prototype._read = function(n) {
16652 this.emit('error', new Error('not implemented'));
16653};
16654
16655Readable.prototype.pipe = function(dest, pipeOpts) {
16656 var src = this;
16657 var state = this._readableState;
16658
16659 switch (state.pipesCount) {
16660 case 0:
16661 state.pipes = dest;
16662 break;
16663 case 1:
16664 state.pipes = [state.pipes, dest];
16665 break;
16666 default:
16667 state.pipes.push(dest);
16668 break;
16669 }
16670 state.pipesCount += 1;
16671
16672 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
16673 dest !== process.stdout &&
16674 dest !== process.stderr;
16675
16676 var endFn = doEnd ? onend : cleanup;
16677 if (state.endEmitted)
16678 process.nextTick(endFn);
16679 else
16680 src.once('end', endFn);
16681
16682 dest.on('unpipe', onunpipe);
16683 function onunpipe(readable) {
16684 if (readable !== src) return;
16685 cleanup();
16686 }
16687
16688 function onend() {
16689 dest.end();
16690 }
16691
16692 // when the dest drains, it reduces the awaitDrain counter
16693 // on the source. This would be more elegant with a .once()
16694 // handler in flow(), but adding and removing repeatedly is
16695 // too slow.
16696 var ondrain = pipeOnDrain(src);
16697 dest.on('drain', ondrain);
16698
16699 function cleanup() {
16700 // cleanup event handlers once the pipe is broken
16701 dest.removeListener('close', onclose);
16702 dest.removeListener('finish', onfinish);
16703 dest.removeListener('drain', ondrain);
16704 dest.removeListener('error', onerror);
16705 dest.removeListener('unpipe', onunpipe);
16706 src.removeListener('end', onend);
16707 src.removeListener('end', cleanup);
16708
16709 // if the reader is waiting for a drain event from this
16710 // specific writer, then it would cause it to never start
16711 // flowing again.
16712 // So, if this is awaiting a drain, then we just call it now.
16713 // If we don't know, then assume that we are waiting for one.
16714 if (!dest._writableState || dest._writableState.needDrain)
16715 ondrain();
16716 }
16717
16718 // if the dest has an error, then stop piping into it.
16719 // however, don't suppress the throwing behavior for this.
16720 function onerror(er) {
16721 unpipe();
16722 dest.removeListener('error', onerror);
16723 if (EE.listenerCount(dest, 'error') === 0)
16724 dest.emit('error', er);
16725 }
16726 // This is a brutally ugly hack to make sure that our error handler
16727 // is attached before any userland ones. NEVER DO THIS.
16728 if (!dest._events || !dest._events.error)
16729 dest.on('error', onerror);
16730 else if (isArray(dest._events.error))
16731 dest._events.error.unshift(onerror);
16732 else
16733 dest._events.error = [onerror, dest._events.error];
16734
16735
16736
16737 // Both close and finish should trigger unpipe, but only once.
16738 function onclose() {
16739 dest.removeListener('finish', onfinish);
16740 unpipe();
16741 }
16742 dest.once('close', onclose);
16743 function onfinish() {
16744 dest.removeListener('close', onclose);
16745 unpipe();
16746 }
16747 dest.once('finish', onfinish);
16748
16749 function unpipe() {
16750 src.unpipe(dest);
16751 }
16752
16753 // tell the dest that it's being piped to
16754 dest.emit('pipe', src);
16755
16756 // start the flow if it hasn't been started already.
16757 if (!state.flowing) {
16758 // the handler that waits for readable events after all
16759 // the data gets sucked out in flow.
16760 // This would be easier to follow with a .once() handler
16761 // in flow(), but that is too slow.
16762 this.on('readable', pipeOnReadable);
16763
16764 state.flowing = true;
16765 process.nextTick(function() {
16766 flow(src);
16767 });
16768 }
16769
16770 return dest;
16771};
16772
16773function pipeOnDrain(src) {
16774 return function() {
16775 var dest = this;
16776 var state = src._readableState;
16777 state.awaitDrain--;
16778 if (state.awaitDrain === 0)
16779 flow(src);
16780 };
16781}
16782
16783function flow(src) {
16784 var state = src._readableState;
16785 var chunk;
16786 state.awaitDrain = 0;
16787
16788 function write(dest, i, list) {
16789 var written = dest.write(chunk);
16790 if (false === written) {
16791 state.awaitDrain++;
16792 }
16793 }
16794
16795 while (state.pipesCount && null !== (chunk = src.read())) {
16796
16797 if (state.pipesCount === 1)
16798 write(state.pipes, 0, null);
16799 else
16800 forEach(state.pipes, write);
16801
16802 src.emit('data', chunk);
16803
16804 // if anyone needs a drain, then we have to wait for that.
16805 if (state.awaitDrain > 0)
16806 return;
16807 }
16808
16809 // if every destination was unpiped, either before entering this
16810 // function, or in the while loop, then stop flowing.
16811 //
16812 // NB: This is a pretty rare edge case.
16813 if (state.pipesCount === 0) {
16814 state.flowing = false;
16815
16816 // if there were data event listeners added, then switch to old mode.
16817 if (EE.listenerCount(src, 'data') > 0)
16818 emitDataEvents(src);
16819 return;
16820 }
16821
16822 // at this point, no one needed a drain, so we just ran out of data
16823 // on the next readable event, start it over again.
16824 state.ranOut = true;
16825}
16826
16827function pipeOnReadable() {
16828 if (this._readableState.ranOut) {
16829 this._readableState.ranOut = false;
16830 flow(this);
16831 }
16832}
16833
16834
16835Readable.prototype.unpipe = function(dest) {
16836 var state = this._readableState;
16837
16838 // if we're not piping anywhere, then do nothing.
16839 if (state.pipesCount === 0)
16840 return this;
16841
16842 // just one destination. most common case.
16843 if (state.pipesCount === 1) {
16844 // passed in one, but it's not the right one.
16845 if (dest && dest !== state.pipes)
16846 return this;
16847
16848 if (!dest)
16849 dest = state.pipes;
16850
16851 // got a match.
16852 state.pipes = null;
16853 state.pipesCount = 0;
16854 this.removeListener('readable', pipeOnReadable);
16855 state.flowing = false;
16856 if (dest)
16857 dest.emit('unpipe', this);
16858 return this;
16859 }
16860
16861 // slow case. multiple pipe destinations.
16862
16863 if (!dest) {
16864 // remove all.
16865 var dests = state.pipes;
16866 var len = state.pipesCount;
16867 state.pipes = null;
16868 state.pipesCount = 0;
16869 this.removeListener('readable', pipeOnReadable);
16870 state.flowing = false;
16871
16872 for (var i = 0; i < len; i++)
16873 dests[i].emit('unpipe', this);
16874 return this;
16875 }
16876
16877 // try to find the right one.
16878 var i = indexOf(state.pipes, dest);
16879 if (i === -1)
16880 return this;
16881
16882 state.pipes.splice(i, 1);
16883 state.pipesCount -= 1;
16884 if (state.pipesCount === 1)
16885 state.pipes = state.pipes[0];
16886
16887 dest.emit('unpipe', this);
16888
16889 return this;
16890};
16891
16892// set up data events if they are asked for
16893// Ensure readable listeners eventually get something
16894Readable.prototype.on = function(ev, fn) {
16895 var res = Stream.prototype.on.call(this, ev, fn);
16896
16897 if (ev === 'data' && !this._readableState.flowing)
16898 emitDataEvents(this);
16899
16900 if (ev === 'readable' && this.readable) {
16901 var state = this._readableState;
16902 if (!state.readableListening) {
16903 state.readableListening = true;
16904 state.emittedReadable = false;
16905 state.needReadable = true;
16906 if (!state.reading) {
16907 this.read(0);
16908 } else if (state.length) {
16909 emitReadable(this, state);
16910 }
16911 }
16912 }
16913
16914 return res;
16915};
16916Readable.prototype.addListener = Readable.prototype.on;
16917
16918// pause() and resume() are remnants of the legacy readable stream API
16919// If the user uses them, then switch into old mode.
16920Readable.prototype.resume = function() {
16921 emitDataEvents(this);
16922 this.read(0);
16923 this.emit('resume');
16924};
16925
16926Readable.prototype.pause = function() {
16927 emitDataEvents(this, true);
16928 this.emit('pause');
16929};
16930
16931function emitDataEvents(stream, startPaused) {
16932 var state = stream._readableState;
16933
16934 if (state.flowing) {
16935 // https://github.com/isaacs/readable-stream/issues/16
16936 throw new Error('Cannot switch to old mode now.');
16937 }
16938
16939 var paused = startPaused || false;
16940 var readable = false;
16941
16942 // convert to an old-style stream.
16943 stream.readable = true;
16944 stream.pipe = Stream.prototype.pipe;
16945 stream.on = stream.addListener = Stream.prototype.on;
16946
16947 stream.on('readable', function() {
16948 readable = true;
16949
16950 var c;
16951 while (!paused && (null !== (c = stream.read())))
16952 stream.emit('data', c);
16953
16954 if (c === null) {
16955 readable = false;
16956 stream._readableState.needReadable = true;
16957 }
16958 });
16959
16960 stream.pause = function() {
16961 paused = true;
16962 this.emit('pause');
16963 };
16964
16965 stream.resume = function() {
16966 paused = false;
16967 if (readable)
16968 process.nextTick(function() {
16969 stream.emit('readable');
16970 });
16971 else
16972 this.read(0);
16973 this.emit('resume');
16974 };
16975
16976 // now make it start, just in case it hadn't already.
16977 stream.emit('readable');
16978}
16979
16980// wrap an old-style stream as the async data source.
16981// This is *not* part of the readable stream interface.
16982// It is an ugly unfortunate mess of history.
16983Readable.prototype.wrap = function(stream) {
16984 var state = this._readableState;
16985 var paused = false;
16986
16987 var self = this;
16988 stream.on('end', function() {
16989 if (state.decoder && !state.ended) {
16990 var chunk = state.decoder.end();
16991 if (chunk && chunk.length)
16992 self.push(chunk);
16993 }
16994
16995 self.push(null);
16996 });
16997
16998 stream.on('data', function(chunk) {
16999 if (state.decoder)
17000 chunk = state.decoder.write(chunk);
17001
17002 // don't skip over falsy values in objectMode
17003 //if (state.objectMode && util.isNullOrUndefined(chunk))
17004 if (state.objectMode && (chunk === null || chunk === undefined))
17005 return;
17006 else if (!state.objectMode && (!chunk || !chunk.length))
17007 return;
17008
17009 var ret = self.push(chunk);
17010 if (!ret) {
17011 paused = true;
17012 stream.pause();
17013 }
17014 });
17015
17016 // proxy all the other methods.
17017 // important when wrapping filters and duplexes.
17018 for (var i in stream) {
17019 if (typeof stream[i] === 'function' &&
17020 typeof this[i] === 'undefined') {
17021 this[i] = function(method) { return function() {
17022 return stream[method].apply(stream, arguments);
17023 }}(i);
17024 }
17025 }
17026
17027 // proxy certain important events.
17028 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
17029 forEach(events, function(ev) {
17030 stream.on(ev, self.emit.bind(self, ev));
17031 });
17032
17033 // when we try to consume some more bytes, simply unpause the
17034 // underlying stream.
17035 self._read = function(n) {
17036 if (paused) {
17037 paused = false;
17038 stream.resume();
17039 }
17040 };
17041
17042 return self;
17043};
17044
17045
17046
17047// exposed for testing purposes only.
17048Readable._fromList = fromList;
17049
17050// Pluck off n bytes from an array of buffers.
17051// Length is the combined lengths of all the buffers in the list.
17052function fromList(n, state) {
17053 var list = state.buffer;
17054 var length = state.length;
17055 var stringMode = !!state.decoder;
17056 var objectMode = !!state.objectMode;
17057 var ret;
17058
17059 // nothing in the list, definitely empty.
17060 if (list.length === 0)
17061 return null;
17062
17063 if (length === 0)
17064 ret = null;
17065 else if (objectMode)
17066 ret = list.shift();
17067 else if (!n || n >= length) {
17068 // read it all, truncate the array.
17069 if (stringMode)
17070 ret = list.join('');
17071 else
17072 ret = Buffer.concat(list, length);
17073 list.length = 0;
17074 } else {
17075 // read just some of it.
17076 if (n < list[0].length) {
17077 // just take a part of the first list item.
17078 // slice is the same for buffers and strings.
17079 var buf = list[0];
17080 ret = buf.slice(0, n);
17081 list[0] = buf.slice(n);
17082 } else if (n === list[0].length) {
17083 // first list is a perfect match
17084 ret = list.shift();
17085 } else {
17086 // complex case.
17087 // we have enough to cover it, but it spans past the first buffer.
17088 if (stringMode)
17089 ret = '';
17090 else
17091 ret = new Buffer(n);
17092
17093 var c = 0;
17094 for (var i = 0, l = list.length; i < l && c < n; i++) {
17095 var buf = list[0];
17096 var cpy = Math.min(n - c, buf.length);
17097
17098 if (stringMode)
17099 ret += buf.slice(0, cpy);
17100 else
17101 buf.copy(ret, c, 0, cpy);
17102
17103 if (cpy < buf.length)
17104 list[0] = buf.slice(cpy);
17105 else
17106 list.shift();
17107
17108 c += cpy;
17109 }
17110 }
17111 }
17112
17113 return ret;
17114}
17115
17116function endReadable(stream) {
17117 var state = stream._readableState;
17118
17119 // If we get here before consuming all the bytes, then that is a
17120 // bug in node. Should never happen.
17121 if (state.length > 0)
17122 throw new Error('endReadable called on non-empty stream');
17123
17124 if (!state.endEmitted && state.calledRead) {
17125 state.ended = true;
17126 process.nextTick(function() {
17127 // Check that we didn't get one last unshift.
17128 if (!state.endEmitted && state.length === 0) {
17129 state.endEmitted = true;
17130 stream.readable = false;
17131 stream.emit('end');
17132 }
17133 });
17134 }
17135}
17136
17137function forEach (xs, f) {
17138 for (var i = 0, l = xs.length; i < l; i++) {
17139 f(xs[i], i);
17140 }
17141}
17142
17143function indexOf (xs, x) {
17144 for (var i = 0, l = xs.length; i < l; i++) {
17145 if (xs[i] === x) return i;
17146 }
17147 return -1;
17148}
17149}, {"isarray":91,"buffer":29,"events":3,"stream":52,"core-util-is":87,"inherits":88,"string_decoder/":62}],91: [function (exports, require, module, global) {module.exports = Array.isArray || function (arr) {
17150 return Object.prototype.toString.call(arr) == '[object Array]';
17151};
17152}, {}],92: [function (exports, require, module, global) {var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify
17153exports = module.exports = require('./lib/_stream_readable.js');
17154exports.Stream = Stream;
17155exports.Readable = exports;
17156exports.Writable = require('./lib/_stream_writable.js');
17157exports.Duplex = require('./lib/_stream_duplex.js');
17158exports.Transform = require('./lib/_stream_transform.js');
17159exports.PassThrough = require('./lib/_stream_passthrough.js');
17160}, {"stream":52,"./lib/_stream_readable.js":90,"./lib/_stream_writable.js":86,"./lib/_stream_duplex.js":89,"./lib/_stream_transform.js":93,"./lib/_stream_passthrough.js":94}],93: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
17161//
17162// Permission is hereby granted, free of charge, to any person obtaining a
17163// copy of this software and associated documentation files (the
17164// "Software"), to deal in the Software without restriction, including
17165// without limitation the rights to use, copy, modify, merge, publish,
17166// distribute, sublicense, and/or sell copies of the Software, and to permit
17167// persons to whom the Software is furnished to do so, subject to the
17168// following conditions:
17169//
17170// The above copyright notice and this permission notice shall be included
17171// in all copies or substantial portions of the Software.
17172//
17173// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17174// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17175// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17176// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17177// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17178// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17179// USE OR OTHER DEALINGS IN THE SOFTWARE.
17180
17181
17182// a transform stream is a readable/writable stream where you do
17183// something with the data. Sometimes it's called a "filter",
17184// but that's not a great name for it, since that implies a thing where
17185// some bits pass through, and others are simply ignored. (That would
17186// be a valid example of a transform, of course.)
17187//
17188// While the output is causally related to the input, it's not a
17189// necessarily symmetric or synchronous transformation. For example,
17190// a zlib stream might take multiple plain-text writes(), and then
17191// emit a single compressed chunk some time in the future.
17192//
17193// Here's how this works:
17194//
17195// The Transform stream has all the aspects of the readable and writable
17196// stream classes. When you write(chunk), that calls _write(chunk,cb)
17197// internally, and returns false if there's a lot of pending writes
17198// buffered up. When you call read(), that calls _read(n) until
17199// there's enough pending readable data buffered up.
17200//
17201// In a transform stream, the written data is placed in a buffer. When
17202// _read(n) is called, it transforms the queued up data, calling the
17203// buffered _write cb's as it consumes chunks. If consuming a single
17204// written chunk would result in multiple output chunks, then the first
17205// outputted bit calls the readcb, and subsequent chunks just go into
17206// the read buffer, and will cause it to emit 'readable' if necessary.
17207//
17208// This way, back-pressure is actually determined by the reading side,
17209// since _read has to be called to start processing a new chunk. However,
17210// a pathological inflate type of transform can cause excessive buffering
17211// here. For example, imagine a stream where every byte of input is
17212// interpreted as an integer from 0-255, and then results in that many
17213// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
17214// 1kb of data being output. In this case, you could write a very small
17215// amount of input, and end up with a very large amount of output. In
17216// such a pathological inflating mechanism, there'd be no way to tell
17217// the system to stop doing the transform. A single 4MB write could
17218// cause the system to run out of memory.
17219//
17220// However, even in such a pathological case, only a single written chunk
17221// would be consumed, and then the rest would wait (un-transformed) until
17222// the results of the previous transformed chunk were consumed.
17223
17224module.exports = Transform;
17225
17226var Duplex = require('./_stream_duplex');
17227
17228/*<replacement>*/
17229var util = require('core-util-is');
17230util.inherits = require('inherits');
17231/*</replacement>*/
17232
17233util.inherits(Transform, Duplex);
17234
17235
17236function TransformState(options, stream) {
17237 this.afterTransform = function(er, data) {
17238 return afterTransform(stream, er, data);
17239 };
17240
17241 this.needTransform = false;
17242 this.transforming = false;
17243 this.writecb = null;
17244 this.writechunk = null;
17245}
17246
17247function afterTransform(stream, er, data) {
17248 var ts = stream._transformState;
17249 ts.transforming = false;
17250
17251 var cb = ts.writecb;
17252
17253 if (!cb)
17254 return stream.emit('error', new Error('no writecb in Transform class'));
17255
17256 ts.writechunk = null;
17257 ts.writecb = null;
17258
17259 if (data !== null && data !== undefined)
17260 stream.push(data);
17261
17262 if (cb)
17263 cb(er);
17264
17265 var rs = stream._readableState;
17266 rs.reading = false;
17267 if (rs.needReadable || rs.length < rs.highWaterMark) {
17268 stream._read(rs.highWaterMark);
17269 }
17270}
17271
17272
17273function Transform(options) {
17274 if (!(this instanceof Transform))
17275 return new Transform(options);
17276
17277 Duplex.call(this, options);
17278
17279 var ts = this._transformState = new TransformState(options, this);
17280
17281 // when the writable side finishes, then flush out anything remaining.
17282 var stream = this;
17283
17284 // start out asking for a readable event once data is transformed.
17285 this._readableState.needReadable = true;
17286
17287 // we have implemented the _read method, and done the other things
17288 // that Readable wants before the first _read call, so unset the
17289 // sync guard flag.
17290 this._readableState.sync = false;
17291
17292 this.once('finish', function() {
17293 if ('function' === typeof this._flush)
17294 this._flush(function(er) {
17295 done(stream, er);
17296 });
17297 else
17298 done(stream);
17299 });
17300}
17301
17302Transform.prototype.push = function(chunk, encoding) {
17303 this._transformState.needTransform = false;
17304 return Duplex.prototype.push.call(this, chunk, encoding);
17305};
17306
17307// This is the part where you do stuff!
17308// override this function in implementation classes.
17309// 'chunk' is an input chunk.
17310//
17311// Call `push(newChunk)` to pass along transformed output
17312// to the readable side. You may call 'push' zero or more times.
17313//
17314// Call `cb(err)` when you are done with this chunk. If you pass
17315// an error, then that'll put the hurt on the whole operation. If you
17316// never call cb(), then you'll never get another chunk.
17317Transform.prototype._transform = function(chunk, encoding, cb) {
17318 throw new Error('not implemented');
17319};
17320
17321Transform.prototype._write = function(chunk, encoding, cb) {
17322 var ts = this._transformState;
17323 ts.writecb = cb;
17324 ts.writechunk = chunk;
17325 ts.writeencoding = encoding;
17326 if (!ts.transforming) {
17327 var rs = this._readableState;
17328 if (ts.needTransform ||
17329 rs.needReadable ||
17330 rs.length < rs.highWaterMark)
17331 this._read(rs.highWaterMark);
17332 }
17333};
17334
17335// Doesn't matter what the args are here.
17336// _transform does all the work.
17337// That we got here means that the readable side wants more data.
17338Transform.prototype._read = function(n) {
17339 var ts = this._transformState;
17340
17341 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
17342 ts.transforming = true;
17343 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
17344 } else {
17345 // mark that we need a transform, so that any data that comes in
17346 // will get processed, now that we've asked for it.
17347 ts.needTransform = true;
17348 }
17349};
17350
17351
17352function done(stream, er) {
17353 if (er)
17354 return stream.emit('error', er);
17355
17356 // if there's nothing in the write buffer, then that means
17357 // that nothing more will ever be provided
17358 var ws = stream._writableState;
17359 var rs = stream._readableState;
17360 var ts = stream._transformState;
17361
17362 if (ws.length)
17363 throw new Error('calling transform done when ws.length != 0');
17364
17365 if (ts.transforming)
17366 throw new Error('calling transform done when still transforming');
17367
17368 return stream.push(null);
17369}
17370}, {"./_stream_duplex":89,"core-util-is":87,"inherits":88}],94: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
17371//
17372// Permission is hereby granted, free of charge, to any person obtaining a
17373// copy of this software and associated documentation files (the
17374// "Software"), to deal in the Software without restriction, including
17375// without limitation the rights to use, copy, modify, merge, publish,
17376// distribute, sublicense, and/or sell copies of the Software, and to permit
17377// persons to whom the Software is furnished to do so, subject to the
17378// following conditions:
17379//
17380// The above copyright notice and this permission notice shall be included
17381// in all copies or substantial portions of the Software.
17382//
17383// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17384// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17385// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17386// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17387// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17388// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17389// USE OR OTHER DEALINGS IN THE SOFTWARE.
17390
17391// a passthrough stream.
17392// basically just the most minimal sort of Transform stream.
17393// Every written chunk gets output as-is.
17394
17395module.exports = PassThrough;
17396
17397var Transform = require('./_stream_transform');
17398
17399/*<replacement>*/
17400var util = require('core-util-is');
17401util.inherits = require('inherits');
17402/*</replacement>*/
17403
17404util.inherits(PassThrough, Transform);
17405
17406function PassThrough(options) {
17407 if (!(this instanceof PassThrough))
17408 return new PassThrough(options);
17409
17410 Transform.call(this, options);
17411}
17412
17413PassThrough.prototype._transform = function(chunk, encoding, cb) {
17414 cb(null, chunk);
17415};
17416}, {"./_stream_transform":93,"core-util-is":87,"inherits":88}],95: [function (exports, require, module, global) {module.exports = require("./lib/_stream_duplex.js")
17417}, {"./lib/_stream_duplex.js":89}],96: [function (exports, require, module, global) {var EventEmitter = require('events').EventEmitter
17418var next = process.nextTick
17419var SubDb = require('./sub')
17420var Batch = require('./batch')
17421var fixRange = require('level-fix-range')
17422
17423var Hooks = require('level-hooks')
17424
17425module.exports = function (_db, options) {
17426 function DB () {}
17427 DB.prototype = _db
17428 var db = new DB()
17429
17430 if (db.sublevel) return db
17431
17432 options = options || {}
17433
17434 //use \xff (255) as the seperator,
17435 //so that sections of the database will sort after the regular keys
17436 var sep = options.sep = options.sep || '\xff'
17437 db._options = options
17438
17439 Hooks(db)
17440
17441 db.sublevels = {}
17442
17443 db.sublevel = function (prefix, options) {
17444 if(db.sublevels[prefix])
17445 return db.sublevels[prefix]
17446 return new SubDb(db, prefix, options || this._options)
17447 }
17448
17449 db.methods = {}
17450
17451 db.prefix = function (key) {
17452 return '' + (key || '')
17453 }
17454
17455 db.pre = function (range, hook) {
17456 if(!hook)
17457 hook = range, range = {
17458 max : sep
17459 }
17460 return db.hooks.pre(range, hook)
17461 }
17462
17463 db.post = function (range, hook) {
17464 if(!hook)
17465 hook = range, range = {
17466 max : sep
17467 }
17468 return db.hooks.post(range, hook)
17469 }
17470
17471 function safeRange(fun) {
17472 return function (opts) {
17473 opts = opts || {}
17474 opts = fixRange(opts)
17475
17476 if(opts.reverse) opts.start = opts.start || sep
17477 else opts.end = opts.end || sep
17478
17479 return fun.call(db, opts)
17480 }
17481 }
17482
17483 db.readStream =
17484 db.createReadStream = safeRange(db.createReadStream)
17485 db.keyStream =
17486 db.createKeyStream = safeRange(db.createKeyStream)
17487 db.valuesStream =
17488 db.createValueStream = safeRange(db.createValueStream)
17489
17490 var batch = db.batch
17491 db.batch = function (changes, opts, cb) {
17492 if(!Array.isArray(changes))
17493 return new Batch(db)
17494 changes.forEach(function (e) {
17495 if(e.prefix) {
17496 if('function' === typeof e.prefix.prefix)
17497 e.key = e.prefix.prefix(e.key)
17498 else if('string' === typeof e.prefix)
17499 e.key = e.prefix + e.key
17500 }
17501 })
17502 batch.call(db, changes, opts, cb)
17503 }
17504 return db
17505}
17506
17507}, {"events":3,"./sub":97,"./batch":107,"level-fix-range":99,"level-hooks":108}],97: [function (exports, require, module, global) {var EventEmitter = require('events').EventEmitter
17508var inherits = require('util').inherits
17509var ranges = require('string-range')
17510var fixRange = require('level-fix-range')
17511var xtend = require('xtend')
17512var Batch = require('./batch')
17513
17514inherits(SubDB, EventEmitter)
17515
17516function SubDB (db, prefix, options) {
17517 if('string' === typeof options) {
17518 console.error('db.sublevel(name, seperator<string>) is depreciated')
17519 console.error('use db.sublevel(name, {sep: separator})) if you must')
17520 options = {sep: options}
17521 }
17522 if(!(this instanceof SubDB)) return new SubDB(db, prefix, options)
17523 if(!db) throw new Error('must provide db')
17524 if(!prefix) throw new Error('must provide prefix')
17525
17526 options = options || {}
17527 options.sep = options.sep || '\xff'
17528
17529 this._parent = db
17530 this._options = options
17531 this.options = options
17532 this._prefix = prefix
17533 this._root = root(this)
17534 db.sublevels[prefix] = this
17535 this.sublevels = {}
17536 this.methods = {}
17537 var self = this
17538 this.hooks = {
17539 pre: function () {
17540 return self.pre.apply(self, arguments)
17541 },
17542 post: function () {
17543 return self.post.apply(self, arguments)
17544 }
17545 }
17546}
17547
17548var SDB = SubDB.prototype
17549
17550SDB._key = function (key) {
17551 var sep = this._options.sep
17552 return sep
17553 + this._prefix
17554 + sep
17555 + key
17556}
17557
17558SDB._getOptsAndCb = function (opts, cb) {
17559 if (typeof opts == 'function') {
17560 cb = opts
17561 opts = {}
17562 }
17563 return { opts: xtend(opts, this._options), cb: cb }
17564}
17565
17566SDB.sublevel = function (prefix, options) {
17567 if(this.sublevels[prefix])
17568 return this.sublevels[prefix]
17569 return new SubDB(this, prefix, options || this._options)
17570}
17571
17572SDB.put = function (key, value, opts, cb) {
17573 var res = this._getOptsAndCb(opts, cb)
17574 this._root.put(this.prefix(key), value, res.opts, res.cb)
17575}
17576
17577SDB.get = function (key, opts, cb) {
17578 var res = this._getOptsAndCb(opts, cb)
17579 this._root.get(this.prefix(key), res.opts, res.cb)
17580}
17581
17582SDB.del = function (key, opts, cb) {
17583 var res = this._getOptsAndCb(opts, cb)
17584 this._root.del(this.prefix(key), res.opts, res.cb)
17585}
17586
17587SDB.batch = function (changes, opts, cb) {
17588 if(!Array.isArray(changes))
17589 return new Batch(this)
17590 var self = this,
17591 res = this._getOptsAndCb(opts, cb)
17592 changes.forEach(function (ch) {
17593
17594 //OH YEAH, WE NEED TO VALIDATE THAT UPDATING THIS KEY/PREFIX IS ALLOWED
17595 if('string' === typeof ch.prefix)
17596 ch.key = ch.prefix + ch.key
17597 else
17598 ch.key = (ch.prefix || self).prefix(ch.key)
17599
17600 if(ch.prefix) ch.prefix = null
17601 })
17602 this._root.batch(changes, res.opts, res.cb)
17603}
17604
17605SDB._getKeyEncoding = function () {
17606 if(this.options.keyEncoding)
17607 return this.options.keyEncoding
17608 if(this._parent && this._parent._getKeyEncoding)
17609 return this._parent._getKeyEncoding()
17610}
17611
17612SDB._getValueEncoding = function () {
17613 if(this.options.valueEncoding)
17614 return this.options.valueEncoding
17615 if(this._parent && this._parent._getValueEncoding)
17616 return this._parent._getValueEncoding()
17617}
17618
17619SDB.prefix = function (key) {
17620 var sep = this._options.sep
17621 return this._parent.prefix() + sep + this._prefix + sep + (key || '')
17622}
17623
17624SDB.keyStream =
17625SDB.createKeyStream = function (opts) {
17626 opts = opts || {}
17627 opts.keys = true
17628 opts.values = false
17629 return this.createReadStream(opts)
17630}
17631
17632SDB.valueStream =
17633SDB.createValueStream = function (opts) {
17634 opts = opts || {}
17635 opts.keys = false
17636 opts.values = true
17637 opts.keys = false
17638 return this.createReadStream(opts)
17639}
17640
17641function selectivelyMerge(_opts, opts) {
17642 [ 'valueEncoding'
17643 , 'encoding'
17644 , 'keyEncoding'
17645 , 'reverse'
17646 , 'values'
17647 , 'keys'
17648 , 'limit'
17649 , 'fillCache'
17650 ]
17651 .forEach(function (k) {
17652 if (opts.hasOwnProperty(k)) _opts[k] = opts[k]
17653 })
17654}
17655
17656SDB.readStream =
17657SDB.createReadStream = function (opts) {
17658 opts = opts || {}
17659 var r = root(this)
17660 var p = this.prefix()
17661
17662 var _opts = ranges.prefix(opts, p)
17663 selectivelyMerge(_opts, xtend(opts, this._options))
17664
17665 var s = r.createReadStream(_opts)
17666
17667 if(_opts.values === false) {
17668 var read = s.read
17669 if (read) {
17670 s.read = function (size) {
17671 var val = read.call(this, size)
17672 if (val) val = val.substring(p.length)
17673 return val
17674 }
17675 } else {
17676 var emit = s.emit
17677 s.emit = function (event, val) {
17678 if(event === 'data') {
17679 emit.call(this, 'data', val.substring(p.length))
17680 } else
17681 emit.call(this, event, val)
17682 }
17683 }
17684 return s
17685 } else if(_opts.keys === false)
17686 return s
17687 else {
17688 var read = s.read
17689 if (read) {
17690 s.read = function (size) {
17691 var d = read.call(this, size)
17692 if (d) d.key = d.key.substring(p.length)
17693 return d
17694 }
17695 } else {
17696 s.on('data', function (d) {
17697 //mutate the prefix!
17698 //this doesn't work for createKeyStream admittedly.
17699 d.key = d.key.substring(p.length)
17700 })
17701 }
17702 return s
17703 }
17704}
17705
17706
17707SDB.writeStream =
17708SDB.createWriteStream = function () {
17709 var r = root(this)
17710 var p = this.prefix()
17711 var ws = r.createWriteStream.apply(r, arguments)
17712 var write = ws.write
17713
17714 var encoding = this._options.encoding
17715 var valueEncoding = this._options.valueEncoding
17716 var keyEncoding = this._options.keyEncoding
17717
17718 // slight optimization, if no encoding was specified at all,
17719 // which will be the case most times, make write not check at all
17720 var nocheck = !encoding && !valueEncoding && !keyEncoding
17721
17722 ws.write = nocheck
17723 ? function (data) {
17724 data.key = p + data.key
17725 return write.call(ws, data)
17726 }
17727 : function (data) {
17728 data.key = p + data.key
17729
17730 // not merging all options here since this happens on every write and things could get slowed down
17731 // at this point we only consider encoding important to propagate
17732 if (encoding && typeof data.encoding === 'undefined')
17733 data.encoding = encoding
17734 if (valueEncoding && typeof data.valueEncoding === 'undefined')
17735 data.valueEncoding = valueEncoding
17736 if (keyEncoding && typeof data.keyEncoding === 'undefined')
17737 data.keyEncoding = keyEncoding
17738
17739 return write.call(ws, data)
17740 }
17741 return ws
17742}
17743
17744SDB.approximateSize = function () {
17745 var r = root(db)
17746 return r.approximateSize.apply(r, arguments)
17747}
17748
17749function root(db) {
17750 if(!db._parent) return db
17751 return root(db._parent)
17752}
17753
17754SDB.pre = function (range, hook) {
17755 if(!hook) hook = range, range = null
17756 range = ranges.prefix(range, this.prefix(), this._options.sep)
17757 var r = root(this._parent)
17758 var p = this.prefix()
17759 return r.hooks.pre(fixRange(range), function (ch, add, batch) {
17760 hook({
17761 key: ch.key.substring(p.length),
17762 value: ch.value,
17763 type: ch.type
17764 }, function (ch, _p) {
17765 //maybe remove the second add arg now
17766 //that op can have prefix?
17767 add(ch, ch.prefix ? _p : (_p || p))
17768 }, batch)
17769 })
17770}
17771
17772SDB.post = function (range, hook) {
17773 if(!hook) hook = range, range = null
17774 var r = root(this._parent)
17775 var p = this.prefix()
17776 range = ranges.prefix(range, p, this._options.sep)
17777 return r.hooks.post(fixRange(range), function (data) {
17778 hook({key: data.key.substring(p.length), value: data.value, type: data.type})
17779 })
17780}
17781
17782var exports = module.exports = SubDB
17783
17784}, {"events":3,"util":23,"string-range":98,"level-fix-range":99,"xtend":101,"./batch":107}],98: [function (exports, require, module, global) {
17785//force to a valid range
17786var range = exports.range = function (obj) {
17787 return null == obj ? {} : 'string' === typeof range ? {
17788 min: range, max: range + '\xff'
17789 } : obj
17790}
17791
17792//turn into a sub range.
17793var prefix = exports.prefix = function (range, within, term) {
17794 range = exports.range(range)
17795 var _range = {}
17796 term = term || '\xff'
17797 if(range instanceof RegExp || 'function' == typeof range) {
17798 _range.min = within
17799 _range.max = within + term,
17800 _range.inner = function (k) {
17801 var j = k.substring(within.length)
17802 if(range.test)
17803 return range.test(j)
17804 return range(j)
17805 }
17806 }
17807 else if('object' === typeof range) {
17808 _range.min = within + (range.min || range.start || '')
17809 _range.max = within + (range.max || range.end || (term || '~'))
17810 _range.reverse = !!range.reverse
17811 }
17812 return _range
17813}
17814
17815//return a function that checks a range
17816var checker = exports.checker = function (range) {
17817 if(!range) range = {}
17818
17819 if ('string' === typeof range)
17820 return function (key) {
17821 return key.indexOf(range) == 0
17822 }
17823 else if(range instanceof RegExp)
17824 return function (key) {
17825 return range.test(key)
17826 }
17827 else if('object' === typeof range)
17828 return function (key) {
17829 var min = range.min || range.start
17830 var max = range.max || range.end
17831
17832 // fixes keys passed as ints from sublevels
17833 key = String(key)
17834
17835 return (
17836 !min || key >= min
17837 ) && (
17838 !max || key <= max
17839 ) && (
17840 !range.inner || (
17841 range.inner.test
17842 ? range.inner.test(key)
17843 : range.inner(key)
17844 )
17845 )
17846 }
17847 else if('function' === typeof range)
17848 return range
17849}
17850//check if a key is within a range.
17851var satifies = exports.satisfies = function (key, range) {
17852 return checker(range)(key)
17853}
17854
17855
17856}, {}],99: [function (exports, require, module, global) {var clone = require('clone')
17857
17858module.exports =
17859function fixRange(opts) {
17860 opts = clone(opts)
17861
17862 var reverse = opts.reverse
17863 var end = opts.max || opts.end
17864 var start = opts.min || opts.start
17865
17866 var range = [start, end]
17867 if(start != null && end != null)
17868 range.sort()
17869 if(reverse)
17870 range = range.reverse()
17871
17872 opts.start = range[0]
17873 opts.end = range[1]
17874
17875 delete opts.min
17876 delete opts.max
17877
17878 return opts
17879}
17880}, {"clone":100}],100: [function (exports, require, module, global) {'use strict';
17881
17882function objectToString(o) {
17883 return Object.prototype.toString.call(o);
17884}
17885
17886// shim for Node's 'util' package
17887// DO NOT REMOVE THIS! It is required for compatibility with EnderJS (http://enderjs.com/).
17888var util = {
17889 isArray: function (ar) {
17890 return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]');
17891 },
17892 isDate: function (d) {
17893 return typeof d === 'object' && objectToString(d) === '[object Date]';
17894 },
17895 isRegExp: function (re) {
17896 return typeof re === 'object' && objectToString(re) === '[object RegExp]';
17897 },
17898 getRegExpFlags: function (re) {
17899 var flags = '';
17900 re.global && (flags += 'g');
17901 re.ignoreCase && (flags += 'i');
17902 re.multiline && (flags += 'm');
17903 return flags;
17904 }
17905};
17906
17907
17908if (typeof module === 'object')
17909 module.exports = clone;
17910
17911/**
17912 * Clones (copies) an Object using deep copying.
17913 *
17914 * This function supports circular references by default, but if you are certain
17915 * there are no circular references in your object, you can save some CPU time
17916 * by calling clone(obj, false).
17917 *
17918 * Caution: if `circular` is false and `parent` contains circular references,
17919 * your program may enter an infinite loop and crash.
17920 *
17921 * @param `parent` - the object to be cloned
17922 * @param `circular` - set to true if the object to be cloned may contain
17923 * circular references. (optional - true by default)
17924 * @param `depth` - set to a number if the object is only to be cloned to
17925 * a particular depth. (optional - defaults to Infinity)
17926 * @param `prototype` - sets the prototype to be used when cloning an object.
17927 * (optional - defaults to parent prototype).
17928*/
17929
17930function clone(parent, circular, depth, prototype) {
17931 // maintain two arrays for circular references, where corresponding parents
17932 // and children have the same index
17933 var allParents = [];
17934 var allChildren = [];
17935
17936 var useBuffer = typeof Buffer != 'undefined';
17937
17938 if (typeof circular == 'undefined')
17939 circular = true;
17940
17941 if (typeof depth == 'undefined')
17942 depth = Infinity;
17943
17944 // recurse this function so we don't reset allParents and allChildren
17945 function _clone(parent, depth) {
17946 // cloning null always returns null
17947 if (parent === null)
17948 return null;
17949
17950 if (depth == 0)
17951 return parent;
17952
17953 var child;
17954 var proto;
17955 if (typeof parent != 'object') {
17956 return parent;
17957 }
17958
17959 if (util.isArray(parent)) {
17960 child = [];
17961 } else if (util.isRegExp(parent)) {
17962 child = new RegExp(parent.source, util.getRegExpFlags(parent));
17963 if (parent.lastIndex) child.lastIndex = parent.lastIndex;
17964 } else if (util.isDate(parent)) {
17965 child = new Date(parent.getTime());
17966 } else if (useBuffer && Buffer.isBuffer(parent)) {
17967 child = new Buffer(parent.length);
17968 parent.copy(child);
17969 return child;
17970 } else {
17971 if (typeof prototype == 'undefined') {
17972 proto = Object.getPrototypeOf(parent);
17973 child = Object.create(proto);
17974 }
17975 else {
17976 child = Object.create(prototype);
17977 proto = prototype;
17978 }
17979 }
17980
17981 if (circular) {
17982 var index = allParents.indexOf(parent);
17983
17984 if (index != -1) {
17985 return allChildren[index];
17986 }
17987 allParents.push(parent);
17988 allChildren.push(child);
17989 }
17990
17991 for (var i in parent) {
17992 var attrs;
17993 if (proto) {
17994 attrs = Object.getOwnPropertyDescriptor(proto, i);
17995 }
17996
17997 if (attrs && attrs.set == null) {
17998 continue;
17999 }
18000 child[i] = _clone(parent[i], depth - 1);
18001 }
18002
18003 return child;
18004 }
18005
18006 return _clone(parent, depth);
18007}
18008
18009/**
18010 * Simple flat clone using prototype, accepts only objects, usefull for property
18011 * override on FLAT configuration object (no nested props).
18012 *
18013 * USE WITH CAUTION! This may not behave as you wish if you do not know how this
18014 * works.
18015 */
18016clone.clonePrototype = function(parent) {
18017 if (parent === null)
18018 return null;
18019
18020 var c = function () {};
18021 c.prototype = parent;
18022 return new c();
18023};
18024}, {}],101: [function (exports, require, module, global) {var Keys = require("object-keys")
18025var hasKeys = require("./has-keys")
18026
18027module.exports = extend
18028
18029function extend() {
18030 var target = {}
18031
18032 for (var i = 0; i < arguments.length; i++) {
18033 var source = arguments[i]
18034
18035 if (!hasKeys(source)) {
18036 continue
18037 }
18038
18039 var keys = Keys(source)
18040
18041 for (var j = 0; j < keys.length; j++) {
18042 var name = keys[j]
18043 target[name] = source[name]
18044 }
18045 }
18046
18047 return target
18048}
18049}, {"object-keys":102,"./has-keys":106}],102: [function (exports, require, module, global) {module.exports = Object.keys || require('./shim');
18050
18051}, {"./shim":103}],103: [function (exports, require, module, global) {(function () {
18052 "use strict";
18053
18054 // modified from https://github.com/kriskowal/es5-shim
18055 var has = Object.prototype.hasOwnProperty,
18056 is = require('is'),
18057 forEach = require('foreach'),
18058 hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
18059 dontEnums = [
18060 "toString",
18061 "toLocaleString",
18062 "valueOf",
18063 "hasOwnProperty",
18064 "isPrototypeOf",
18065 "propertyIsEnumerable",
18066 "constructor"
18067 ],
18068 keysShim;
18069
18070 keysShim = function keys(object) {
18071 if (!is.object(object) && !is.array(object)) {
18072 throw new TypeError("Object.keys called on a non-object");
18073 }
18074
18075 var name, theKeys = [];
18076 for (name in object) {
18077 if (has.call(object, name)) {
18078 theKeys.push(name);
18079 }
18080 }
18081
18082 if (hasDontEnumBug) {
18083 forEach(dontEnums, function (dontEnum) {
18084 if (has.call(object, dontEnum)) {
18085 theKeys.push(dontEnum);
18086 }
18087 });
18088 }
18089 return theKeys;
18090 };
18091
18092 module.exports = keysShim;
18093}());
18094
18095}, {"is":104,"foreach":105}],104: [function (exports, require, module, global) {
18096/**!
18097 * is
18098 * the definitive JavaScript type testing library
18099 *
18100 * @copyright 2013 Enrico Marino
18101 * @license MIT
18102 */
18103
18104var objProto = Object.prototype;
18105var owns = objProto.hasOwnProperty;
18106var toString = objProto.toString;
18107var isActualNaN = function (value) {
18108 return value !== value;
18109};
18110var NON_HOST_TYPES = {
18111 "boolean": 1,
18112 "number": 1,
18113 "string": 1,
18114 "undefined": 1
18115};
18116
18117/**
18118 * Expose `is`
18119 */
18120
18121var is = module.exports = {};
18122
18123/**
18124 * Test general.
18125 */
18126
18127/**
18128 * is.type
18129 * Test if `value` is a type of `type`.
18130 *
18131 * @param {Mixed} value value to test
18132 * @param {String} type type
18133 * @return {Boolean} true if `value` is a type of `type`, false otherwise
18134 * @api public
18135 */
18136
18137is.a =
18138is.type = function (value, type) {
18139 return typeof value === type;
18140};
18141
18142/**
18143 * is.defined
18144 * Test if `value` is defined.
18145 *
18146 * @param {Mixed} value value to test
18147 * @return {Boolean} true if 'value' is defined, false otherwise
18148 * @api public
18149 */
18150
18151is.defined = function (value) {
18152 return value !== undefined;
18153};
18154
18155/**
18156 * is.empty
18157 * Test if `value` is empty.
18158 *
18159 * @param {Mixed} value value to test
18160 * @return {Boolean} true if `value` is empty, false otherwise
18161 * @api public
18162 */
18163
18164is.empty = function (value) {
18165 var type = toString.call(value);
18166 var key;
18167
18168 if ('[object Array]' === type || '[object Arguments]' === type) {
18169 return value.length === 0;
18170 }
18171
18172 if ('[object Object]' === type) {
18173 for (key in value) if (owns.call(value, key)) return false;
18174 return true;
18175 }
18176
18177 if ('[object String]' === type) {
18178 return '' === value;
18179 }
18180
18181 return false;
18182};
18183
18184/**
18185 * is.equal
18186 * Test if `value` is equal to `other`.
18187 *
18188 * @param {Mixed} value value to test
18189 * @param {Mixed} other value to compare with
18190 * @return {Boolean} true if `value` is equal to `other`, false otherwise
18191 */
18192
18193is.equal = function (value, other) {
18194 var type = toString.call(value)
18195 var key;
18196
18197 if (type !== toString.call(other)) {
18198 return false;
18199 }
18200
18201 if ('[object Object]' === type) {
18202 for (key in value) {
18203 if (!is.equal(value[key], other[key])) {
18204 return false;
18205 }
18206 }
18207 return true;
18208 }
18209
18210 if ('[object Array]' === type) {
18211 key = value.length;
18212 if (key !== other.length) {
18213 return false;
18214 }
18215 while (--key) {
18216 if (!is.equal(value[key], other[key])) {
18217 return false;
18218 }
18219 }
18220 return true;
18221 }
18222
18223 if ('[object Function]' === type) {
18224 return value.prototype === other.prototype;
18225 }
18226
18227 if ('[object Date]' === type) {
18228 return value.getTime() === other.getTime();
18229 }
18230
18231 return value === other;
18232};
18233
18234/**
18235 * is.hosted
18236 * Test if `value` is hosted by `host`.
18237 *
18238 * @param {Mixed} value to test
18239 * @param {Mixed} host host to test with
18240 * @return {Boolean} true if `value` is hosted by `host`, false otherwise
18241 * @api public
18242 */
18243
18244is.hosted = function (value, host) {
18245 var type = typeof host[value];
18246 return type === 'object' ? !!host[value] : !NON_HOST_TYPES[type];
18247};
18248
18249/**
18250 * is.instance
18251 * Test if `value` is an instance of `constructor`.
18252 *
18253 * @param {Mixed} value value to test
18254 * @return {Boolean} true if `value` is an instance of `constructor`
18255 * @api public
18256 */
18257
18258is.instance = is['instanceof'] = function (value, constructor) {
18259 return value instanceof constructor;
18260};
18261
18262/**
18263 * is.null
18264 * Test if `value` is null.
18265 *
18266 * @param {Mixed} value value to test
18267 * @return {Boolean} true if `value` is null, false otherwise
18268 * @api public
18269 */
18270
18271is['null'] = function (value) {
18272 return value === null;
18273};
18274
18275/**
18276 * is.undefined
18277 * Test if `value` is undefined.
18278 *
18279 * @param {Mixed} value value to test
18280 * @return {Boolean} true if `value` is undefined, false otherwise
18281 * @api public
18282 */
18283
18284is.undefined = function (value) {
18285 return value === undefined;
18286};
18287
18288/**
18289 * Test arguments.
18290 */
18291
18292/**
18293 * is.arguments
18294 * Test if `value` is an arguments object.
18295 *
18296 * @param {Mixed} value value to test
18297 * @return {Boolean} true if `value` is an arguments object, false otherwise
18298 * @api public
18299 */
18300
18301is.arguments = function (value) {
18302 var isStandardArguments = '[object Arguments]' === toString.call(value);
18303 var isOldArguments = !is.array(value) && is.arraylike(value) && is.object(value) && is.fn(value.callee);
18304 return isStandardArguments || isOldArguments;
18305};
18306
18307/**
18308 * Test array.
18309 */
18310
18311/**
18312 * is.array
18313 * Test if 'value' is an array.
18314 *
18315 * @param {Mixed} value value to test
18316 * @return {Boolean} true if `value` is an array, false otherwise
18317 * @api public
18318 */
18319
18320is.array = function (value) {
18321 return '[object Array]' === toString.call(value);
18322};
18323
18324/**
18325 * is.arguments.empty
18326 * Test if `value` is an empty arguments object.
18327 *
18328 * @param {Mixed} value value to test
18329 * @return {Boolean} true if `value` is an empty arguments object, false otherwise
18330 * @api public
18331 */
18332is.arguments.empty = function (value) {
18333 return is.arguments(value) && value.length === 0;
18334};
18335
18336/**
18337 * is.array.empty
18338 * Test if `value` is an empty array.
18339 *
18340 * @param {Mixed} value value to test
18341 * @return {Boolean} true if `value` is an empty array, false otherwise
18342 * @api public
18343 */
18344is.array.empty = function (value) {
18345 return is.array(value) && value.length === 0;
18346};
18347
18348/**
18349 * is.arraylike
18350 * Test if `value` is an arraylike object.
18351 *
18352 * @param {Mixed} value value to test
18353 * @return {Boolean} true if `value` is an arguments object, false otherwise
18354 * @api public
18355 */
18356
18357is.arraylike = function (value) {
18358 return !!value && !is.boolean(value)
18359 && owns.call(value, 'length')
18360 && isFinite(value.length)
18361 && is.number(value.length)
18362 && value.length >= 0;
18363};
18364
18365/**
18366 * Test boolean.
18367 */
18368
18369/**
18370 * is.boolean
18371 * Test if `value` is a boolean.
18372 *
18373 * @param {Mixed} value value to test
18374 * @return {Boolean} true if `value` is a boolean, false otherwise
18375 * @api public
18376 */
18377
18378is.boolean = function (value) {
18379 return '[object Boolean]' === toString.call(value);
18380};
18381
18382/**
18383 * is.false
18384 * Test if `value` is false.
18385 *
18386 * @param {Mixed} value value to test
18387 * @return {Boolean} true if `value` is false, false otherwise
18388 * @api public
18389 */
18390
18391is['false'] = function (value) {
18392 return is.boolean(value) && (value === false || value.valueOf() === false);
18393};
18394
18395/**
18396 * is.true
18397 * Test if `value` is true.
18398 *
18399 * @param {Mixed} value value to test
18400 * @return {Boolean} true if `value` is true, false otherwise
18401 * @api public
18402 */
18403
18404is['true'] = function (value) {
18405 return is.boolean(value) && (value === true || value.valueOf() === true);
18406};
18407
18408/**
18409 * Test date.
18410 */
18411
18412/**
18413 * is.date
18414 * Test if `value` is a date.
18415 *
18416 * @param {Mixed} value value to test
18417 * @return {Boolean} true if `value` is a date, false otherwise
18418 * @api public
18419 */
18420
18421is.date = function (value) {
18422 return '[object Date]' === toString.call(value);
18423};
18424
18425/**
18426 * Test element.
18427 */
18428
18429/**
18430 * is.element
18431 * Test if `value` is an html element.
18432 *
18433 * @param {Mixed} value value to test
18434 * @return {Boolean} true if `value` is an HTML Element, false otherwise
18435 * @api public
18436 */
18437
18438is.element = function (value) {
18439 return value !== undefined
18440 && typeof HTMLElement !== 'undefined'
18441 && value instanceof HTMLElement
18442 && value.nodeType === 1;
18443};
18444
18445/**
18446 * Test error.
18447 */
18448
18449/**
18450 * is.error
18451 * Test if `value` is an error object.
18452 *
18453 * @param {Mixed} value value to test
18454 * @return {Boolean} true if `value` is an error object, false otherwise
18455 * @api public
18456 */
18457
18458is.error = function (value) {
18459 return '[object Error]' === toString.call(value);
18460};
18461
18462/**
18463 * Test function.
18464 */
18465
18466/**
18467 * is.fn / is.function (deprecated)
18468 * Test if `value` is a function.
18469 *
18470 * @param {Mixed} value value to test
18471 * @return {Boolean} true if `value` is a function, false otherwise
18472 * @api public
18473 */
18474
18475is.fn = is['function'] = function (value) {
18476 var isAlert = typeof window !== 'undefined' && value === window.alert;
18477 return isAlert || '[object Function]' === toString.call(value);
18478};
18479
18480/**
18481 * Test number.
18482 */
18483
18484/**
18485 * is.number
18486 * Test if `value` is a number.
18487 *
18488 * @param {Mixed} value value to test
18489 * @return {Boolean} true if `value` is a number, false otherwise
18490 * @api public
18491 */
18492
18493is.number = function (value) {
18494 return '[object Number]' === toString.call(value);
18495};
18496
18497/**
18498 * is.infinite
18499 * Test if `value` is positive or negative infinity.
18500 *
18501 * @param {Mixed} value value to test
18502 * @return {Boolean} true if `value` is positive or negative Infinity, false otherwise
18503 * @api public
18504 */
18505is.infinite = function (value) {
18506 return value === Infinity || value === -Infinity;
18507};
18508
18509/**
18510 * is.decimal
18511 * Test if `value` is a decimal number.
18512 *
18513 * @param {Mixed} value value to test
18514 * @return {Boolean} true if `value` is a decimal number, false otherwise
18515 * @api public
18516 */
18517
18518is.decimal = function (value) {
18519 return is.number(value) && !isActualNaN(value) && !is.infinite(value) && value % 1 !== 0;
18520};
18521
18522/**
18523 * is.divisibleBy
18524 * Test if `value` is divisible by `n`.
18525 *
18526 * @param {Number} value value to test
18527 * @param {Number} n dividend
18528 * @return {Boolean} true if `value` is divisible by `n`, false otherwise
18529 * @api public
18530 */
18531
18532is.divisibleBy = function (value, n) {
18533 var isDividendInfinite = is.infinite(value);
18534 var isDivisorInfinite = is.infinite(n);
18535 var isNonZeroNumber = is.number(value) && !isActualNaN(value) && is.number(n) && !isActualNaN(n) && n !== 0;
18536 return isDividendInfinite || isDivisorInfinite || (isNonZeroNumber && value % n === 0);
18537};
18538
18539/**
18540 * is.int
18541 * Test if `value` is an integer.
18542 *
18543 * @param value to test
18544 * @return {Boolean} true if `value` is an integer, false otherwise
18545 * @api public
18546 */
18547
18548is.int = function (value) {
18549 return is.number(value) && !isActualNaN(value) && value % 1 === 0;
18550};
18551
18552/**
18553 * is.maximum
18554 * Test if `value` is greater than 'others' values.
18555 *
18556 * @param {Number} value value to test
18557 * @param {Array} others values to compare with
18558 * @return {Boolean} true if `value` is greater than `others` values
18559 * @api public
18560 */
18561
18562is.maximum = function (value, others) {
18563 if (isActualNaN(value)) {
18564 throw new TypeError('NaN is not a valid value');
18565 } else if (!is.arraylike(others)) {
18566 throw new TypeError('second argument must be array-like');
18567 }
18568 var len = others.length;
18569
18570 while (--len >= 0) {
18571 if (value < others[len]) {
18572 return false;
18573 }
18574 }
18575
18576 return true;
18577};
18578
18579/**
18580 * is.minimum
18581 * Test if `value` is less than `others` values.
18582 *
18583 * @param {Number} value value to test
18584 * @param {Array} others values to compare with
18585 * @return {Boolean} true if `value` is less than `others` values
18586 * @api public
18587 */
18588
18589is.minimum = function (value, others) {
18590 if (isActualNaN(value)) {
18591 throw new TypeError('NaN is not a valid value');
18592 } else if (!is.arraylike(others)) {
18593 throw new TypeError('second argument must be array-like');
18594 }
18595 var len = others.length;
18596
18597 while (--len >= 0) {
18598 if (value > others[len]) {
18599 return false;
18600 }
18601 }
18602
18603 return true;
18604};
18605
18606/**
18607 * is.nan
18608 * Test if `value` is not a number.
18609 *
18610 * @param {Mixed} value value to test
18611 * @return {Boolean} true if `value` is not a number, false otherwise
18612 * @api public
18613 */
18614
18615is.nan = function (value) {
18616 return !is.number(value) || value !== value;
18617};
18618
18619/**
18620 * is.even
18621 * Test if `value` is an even number.
18622 *
18623 * @param {Number} value value to test
18624 * @return {Boolean} true if `value` is an even number, false otherwise
18625 * @api public
18626 */
18627
18628is.even = function (value) {
18629 return is.infinite(value) || (is.number(value) && value === value && value % 2 === 0);
18630};
18631
18632/**
18633 * is.odd
18634 * Test if `value` is an odd number.
18635 *
18636 * @param {Number} value value to test
18637 * @return {Boolean} true if `value` is an odd number, false otherwise
18638 * @api public
18639 */
18640
18641is.odd = function (value) {
18642 return is.infinite(value) || (is.number(value) && value === value && value % 2 !== 0);
18643};
18644
18645/**
18646 * is.ge
18647 * Test if `value` is greater than or equal to `other`.
18648 *
18649 * @param {Number} value value to test
18650 * @param {Number} other value to compare with
18651 * @return {Boolean}
18652 * @api public
18653 */
18654
18655is.ge = function (value, other) {
18656 if (isActualNaN(value) || isActualNaN(other)) {
18657 throw new TypeError('NaN is not a valid value');
18658 }
18659 return !is.infinite(value) && !is.infinite(other) && value >= other;
18660};
18661
18662/**
18663 * is.gt
18664 * Test if `value` is greater than `other`.
18665 *
18666 * @param {Number} value value to test
18667 * @param {Number} other value to compare with
18668 * @return {Boolean}
18669 * @api public
18670 */
18671
18672is.gt = function (value, other) {
18673 if (isActualNaN(value) || isActualNaN(other)) {
18674 throw new TypeError('NaN is not a valid value');
18675 }
18676 return !is.infinite(value) && !is.infinite(other) && value > other;
18677};
18678
18679/**
18680 * is.le
18681 * Test if `value` is less than or equal to `other`.
18682 *
18683 * @param {Number} value value to test
18684 * @param {Number} other value to compare with
18685 * @return {Boolean} if 'value' is less than or equal to 'other'
18686 * @api public
18687 */
18688
18689is.le = function (value, other) {
18690 if (isActualNaN(value) || isActualNaN(other)) {
18691 throw new TypeError('NaN is not a valid value');
18692 }
18693 return !is.infinite(value) && !is.infinite(other) && value <= other;
18694};
18695
18696/**
18697 * is.lt
18698 * Test if `value` is less than `other`.
18699 *
18700 * @param {Number} value value to test
18701 * @param {Number} other value to compare with
18702 * @return {Boolean} if `value` is less than `other`
18703 * @api public
18704 */
18705
18706is.lt = function (value, other) {
18707 if (isActualNaN(value) || isActualNaN(other)) {
18708 throw new TypeError('NaN is not a valid value');
18709 }
18710 return !is.infinite(value) && !is.infinite(other) && value < other;
18711};
18712
18713/**
18714 * is.within
18715 * Test if `value` is within `start` and `finish`.
18716 *
18717 * @param {Number} value value to test
18718 * @param {Number} start lower bound
18719 * @param {Number} finish upper bound
18720 * @return {Boolean} true if 'value' is is within 'start' and 'finish'
18721 * @api public
18722 */
18723is.within = function (value, start, finish) {
18724 if (isActualNaN(value) || isActualNaN(start) || isActualNaN(finish)) {
18725 throw new TypeError('NaN is not a valid value');
18726 } else if (!is.number(value) || !is.number(start) || !is.number(finish)) {
18727 throw new TypeError('all arguments must be numbers');
18728 }
18729 var isAnyInfinite = is.infinite(value) || is.infinite(start) || is.infinite(finish);
18730 return isAnyInfinite || (value >= start && value <= finish);
18731};
18732
18733/**
18734 * Test object.
18735 */
18736
18737/**
18738 * is.object
18739 * Test if `value` is an object.
18740 *
18741 * @param {Mixed} value value to test
18742 * @return {Boolean} true if `value` is an object, false otherwise
18743 * @api public
18744 */
18745
18746is.object = function (value) {
18747 return value && '[object Object]' === toString.call(value);
18748};
18749
18750/**
18751 * is.hash
18752 * Test if `value` is a hash - a plain object literal.
18753 *
18754 * @param {Mixed} value value to test
18755 * @return {Boolean} true if `value` is a hash, false otherwise
18756 * @api public
18757 */
18758
18759is.hash = function (value) {
18760 return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval;
18761};
18762
18763/**
18764 * Test regexp.
18765 */
18766
18767/**
18768 * is.regexp
18769 * Test if `value` is a regular expression.
18770 *
18771 * @param {Mixed} value value to test
18772 * @return {Boolean} true if `value` is a regexp, false otherwise
18773 * @api public
18774 */
18775
18776is.regexp = function (value) {
18777 return '[object RegExp]' === toString.call(value);
18778};
18779
18780/**
18781 * Test string.
18782 */
18783
18784/**
18785 * is.string
18786 * Test if `value` is a string.
18787 *
18788 * @param {Mixed} value value to test
18789 * @return {Boolean} true if 'value' is a string, false otherwise
18790 * @api public
18791 */
18792
18793is.string = function (value) {
18794 return '[object String]' === toString.call(value);
18795};
18796
18797}, {}],105: [function (exports, require, module, global) {
18798var hasOwn = Object.prototype.hasOwnProperty;
18799var toString = Object.prototype.toString;
18800
18801module.exports = function forEach (obj, fn, ctx) {
18802 if (toString.call(fn) !== '[object Function]') {
18803 throw new TypeError('iterator must be a function');
18804 }
18805 var l = obj.length;
18806 if (l === +l) {
18807 for (var i = 0; i < l; i++) {
18808 fn.call(ctx, obj[i], i, obj);
18809 }
18810 } else {
18811 for (var k in obj) {
18812 if (hasOwn.call(obj, k)) {
18813 fn.call(ctx, obj[k], k, obj);
18814 }
18815 }
18816 }
18817};
18818
18819}, {}],106: [function (exports, require, module, global) {module.exports = hasKeys
18820
18821function hasKeys(source) {
18822 return source !== null &&
18823 (typeof source === "object" ||
18824 typeof source === "function")
18825}
18826}, {}],107: [function (exports, require, module, global) {function addOperation (type, key, value, options) {
18827 var operation = {
18828 type: type,
18829 key: key,
18830 value: value,
18831 options: options
18832 }
18833
18834 if (options && options.prefix) {
18835 operation.prefix = options.prefix
18836 delete options.prefix
18837 }
18838
18839 this._operations.push(operation)
18840
18841 return this
18842}
18843
18844function Batch(sdb) {
18845 this._operations = []
18846 this._sdb = sdb
18847
18848 this.put = addOperation.bind(this, 'put')
18849 this.del = addOperation.bind(this, 'del')
18850}
18851
18852var B = Batch.prototype
18853
18854
18855B.clear = function () {
18856 this._operations = []
18857}
18858
18859B.write = function (cb) {
18860 this._sdb.batch(this._operations, cb)
18861}
18862
18863module.exports = Batch
18864}, {}],108: [function (exports, require, module, global) {var ranges = require('string-range')
18865
18866module.exports = function (db) {
18867
18868 if(db.hooks) {
18869 return
18870 }
18871
18872 var posthooks = []
18873 var prehooks = []
18874
18875 function getPrefix (p) {
18876 return p && (
18877 'string' === typeof p ? p
18878 : 'string' === typeof p.prefix ? p.prefix
18879 : 'function' === typeof p.prefix ? p.prefix()
18880 : ''
18881 )
18882 }
18883
18884 function getKeyEncoding (db) {
18885 if(db && db._getKeyEncoding)
18886 return db._getKeyEncoding(db)
18887 }
18888
18889 function getValueEncoding (db) {
18890 if(db && db._getValueEncoding)
18891 return db._getValueEncoding(db)
18892 }
18893
18894 function remover (array, item) {
18895 return function () {
18896 var i = array.indexOf(item)
18897 if(!~i) return false
18898 array.splice(i, 1)
18899 return true
18900 }
18901 }
18902
18903 db.hooks = {
18904 post: function (prefix, hook) {
18905 if(!hook) hook = prefix, prefix = ''
18906 var h = {test: ranges.checker(prefix), hook: hook}
18907 posthooks.push(h)
18908 return remover(posthooks, h)
18909 },
18910 pre: function (prefix, hook) {
18911 if(!hook) hook = prefix, prefix = ''
18912 var h = {
18913 test: ranges.checker(prefix),
18914 hook: hook,
18915 safe: false !== prefix.safe
18916 }
18917 prehooks.push(h)
18918 return remover(prehooks, h)
18919 },
18920 posthooks: posthooks,
18921 prehooks: prehooks
18922 }
18923
18924 //POST HOOKS
18925
18926 function each (e) {
18927 if(e && e.type) {
18928 posthooks.forEach(function (h) {
18929 if(h.test(e.key)) h.hook(e)
18930 })
18931 }
18932 }
18933
18934 db.on('put', function (key, val) {
18935 each({type: 'put', key: key, value: val})
18936 })
18937 db.on('del', function (key, val) {
18938 each({type: 'del', key: key, value: val})
18939 })
18940 db.on('batch', function onBatch (ary) {
18941 ary.forEach(each)
18942 })
18943
18944 //PRE HOOKS
18945
18946 var put = db.put
18947 var del = db.del
18948 var batch = db.batch
18949
18950 function callHooks (isBatch, b, opts, cb) {
18951 try {
18952 b.forEach(function hook(e, i) {
18953 prehooks.forEach(function (h) {
18954 if(h.test(String(e.key))) {
18955 //optimize this?
18956 //maybe faster to not create a new object each time?
18957 //have one object and expose scope to it?
18958 var context = {
18959 add: function (ch, db) {
18960 if(typeof ch === 'undefined') {
18961 return this
18962 }
18963 if(ch === false)
18964 return delete b[i]
18965 var prefix = (
18966 getPrefix(ch.prefix) ||
18967 getPrefix(db) ||
18968 h.prefix || ''
18969 )
18970 //don't leave a circular json object there incase using multilevel.
18971 if(prefix) ch.prefix = prefix
18972 ch.key = prefix + ch.key
18973 if(h.safe && h.test(String(ch.key))) {
18974 //this usually means a stack overflow.
18975 throw new Error('prehook cannot insert into own range')
18976 }
18977 var ke = ch.keyEncoding || getKeyEncoding(ch.prefix)
18978 var ve = ch.valueEncoding || getValueEncoding(ch.prefix)
18979 if(ke) ch.keyEncoding = ke
18980 if(ve) ch.valueEncoding = ve
18981
18982 b.push(ch)
18983 hook(ch, b.length - 1)
18984 return this
18985 },
18986 put: function (ch, db) {
18987 if('object' === typeof ch) ch.type = 'put'
18988 return this.add(ch, db)
18989 },
18990 del: function (ch, db) {
18991 if('object' === typeof ch) ch.type = 'del'
18992 return this.add(ch, db)
18993 },
18994 veto: function () {
18995 return this.add(false)
18996 }
18997 }
18998 h.hook.call(context, e, context.add, b)
18999 }
19000 })
19001 })
19002 } catch (err) {
19003 return (cb || opts)(err)
19004 }
19005 b = b.filter(function (e) {
19006 return e && e.type //filter out empty items
19007 })
19008
19009 if(b.length == 1 && !isBatch) {
19010 var change = b[0]
19011 return change.type == 'put'
19012 ? put.call(db, change.key, change.value, opts, cb)
19013 : del.call(db, change.key, opts, cb)
19014 }
19015 return batch.call(db, b, opts, cb)
19016 }
19017
19018 db.put = function (key, value, opts, cb ) {
19019 var batch = [{key: key, value: value, type: 'put'}]
19020 return callHooks(false, batch, opts, cb)
19021 }
19022
19023 db.del = function (key, opts, cb) {
19024 var batch = [{key: key, type: 'del'}]
19025 return callHooks(false, batch, opts, cb)
19026 }
19027
19028 db.batch = function (batch, opts, cb) {
19029 return callHooks(true, batch, opts, cb)
19030 }
19031}
19032}, {"string-range":98}],109: [function (exports, require, module, global) {var Writable = require('readable-stream/writable');
19033var Readable = require('readable-stream/readable');
19034var peek = require('level-peek');
19035var util = require('util');
19036var once = require('once');
19037
19038var EMPTY = new Buffer(0);
19039var ENCODER = {
19040 encode: function(data) {
19041 return typeof data === 'string' ? data = new Buffer(data) : data;
19042 },
19043 decode: function(data) {
19044 return Buffer.isBuffer(data) ? data : new Buffer(data);
19045 },
19046 buffer: true,
19047 type: 'raw'
19048};
19049
19050var noop = function() {};
19051
19052var pad = function(n) {
19053 n = n.toString(16);
19054 return '00000000'.slice(0, -n.length)+n;
19055};
19056
19057var expand = function(buf, len) {
19058 var tmp = new Buffer(len);
19059 buf.copy(tmp);
19060 return tmp;
19061};
19062
19063module.exports = function(db, opts) {
19064 if (!opts) opts = {};
19065
19066 var blobs = {};
19067
19068 var blockSize = opts.blockSize || 65536;
19069 var maxBatch = opts.batch || 100;
19070 var blank = new Buffer(blockSize);
19071
19072 db.put('\x00', 'ignore', noop); // memdown#12 workaround
19073
19074 var reservations = {};
19075 var mutateBlock = function(key, offset, block, append, cb) {
19076 var release = function() {
19077 if (!--reservations[key].locks) delete reservations[key];
19078 };
19079
19080 var onreservation = function(r) {
19081 r.locks++;
19082
19083 if (!r.block && !offset) {
19084 r.block = block;
19085 cb(null, r.block, release);
19086 return;
19087 }
19088
19089 if (!r.block) r.block = new Buffer(blockSize);
19090 if (r.block.length < offset + block.length) r.block = expand(r.block, offset + block.length);
19091
19092 block.copy(r.block, offset);
19093
19094 if (!append && offset + block.length < r.block.length) r.block = r.block.slice(0, offset+block.length);
19095 cb(null, r.block, release);
19096 };
19097
19098 if (reservations[key]) return onreservation(reservations[key]);
19099
19100 db.get(key, {valueEncoding:ENCODER}, function(err, block) {
19101 if (err && !err.notFound) return cb(err);
19102 if (!reservations[key]) reservations[key] = {locks:0, block:block};
19103 onreservation(reservations[key]);
19104 });
19105 };
19106
19107 var WriteStream = function(name, opts) {
19108 if (!(this instanceof WriteStream)) return new WriteStream(name, opts);
19109 if (!opts) opts = {};
19110
19111 this.name = name;
19112 this.blocks = [];
19113 this.batch = [];
19114 this.bytesWritten = 0;
19115 this.truncate = !opts.append;
19116 this.append = opts.append;
19117
19118 this._shouldInitAppend = this.append && opts.start === undefined;
19119 this._destroyed = false;
19120 this._init(opts.start || 0);
19121
19122 Writable.call(this);
19123 };
19124
19125 util.inherits(WriteStream, Writable);
19126
19127 WriteStream.prototype._init = function(start) {
19128 this.blockIndex = (start / blockSize) | 0;
19129 this.blockOffset = start - this.blockIndex * blockSize;
19130 this.blockLength = this.blockOffset;
19131 };
19132
19133 WriteStream.prototype._flush = function(cb) {
19134 if (!this.batch.length) return cb();
19135
19136 var key = this.batch[this.batch.length-1].key;
19137 var batch = this.batch;
19138 this.batch = [];
19139
19140 if (!this.truncate) return db.batch(batch, cb);
19141 this.truncate = false;
19142 this._truncate(batch, key, cb);
19143 };
19144
19145 WriteStream.prototype._truncate = function(batch, key, cb) {
19146 cb = once(cb);
19147
19148 var dels = [];
19149 var keys = db.createKeyStream({
19150 start: key,
19151 end: this.name+'\xff\xff'
19152 });
19153
19154 keys.on('error', cb);
19155
19156 keys.on('data', function(key) {
19157 dels.push({type:'del', key:key});
19158 });
19159
19160 keys.on('end', function() {
19161 dels.push.apply(dels, batch);
19162 db.batch(dels, cb);
19163 });
19164 };
19165
19166 WriteStream.prototype._writeBlock = function(cb) {
19167 var block = this.blocks.length === 1 ? this.blocks[0] : Buffer.concat(this.blocks, this.blockLength - this.blockOffset);
19168 var index = this.blockIndex;
19169 var offset = this.blockOffset;
19170 var self = this;
19171
19172 this.blockOffset = 0;
19173 this.blockLength = 0;
19174 this.blockIndex++;
19175 this.blocks = [];
19176
19177 var key = this.name+'\xff'+pad(index);
19178
19179 var append = function(block, force, cb) {
19180 if (block.length) {
19181 self.batch.push({
19182 type: 'put',
19183 key: key,
19184 value: block,
19185 valueEncoding: ENCODER
19186 });
19187 }
19188
19189 if (!force && self.batch.length < maxBatch) return cb();
19190 return self._flush(cb);
19191 };
19192
19193 if (!offset && block.length === blockSize) return append(block, false, cb);
19194 if (!offset && !this.append) return append(block, false, cb);
19195
19196 // partial write
19197 mutateBlock(key, offset, block, this.append, function(err, block, release) {
19198 if (err) return cb(err);
19199 append(block, true, function(err) {
19200 release();
19201 cb(err);
19202 });
19203 });
19204 };
19205
19206 WriteStream.prototype._initAppend = function(data, enc, cb) {
19207 var self = this;
19208 this._shouldInitAppend = false;
19209 blobs.size(this.name, function(err, size) {
19210 if (err) return cb(err);
19211 self._init(size);
19212 self._write(data, enc, cb);
19213 });
19214 };
19215
19216 WriteStream.prototype._write = function(data, enc, cb) {
19217 if (!data.length || this._destroyed) return cb();
19218 if (this._shouldInitAppend) return this._initAppend(data, enc, cb);
19219
19220 var self = this;
19221 var overflow;
19222 var free = blockSize - this.blockLength;
19223
19224 var done = function(err) {
19225 if (err) return cb(err);
19226 if (overflow) return self._write(overflow, enc, cb);
19227 cb();
19228 };
19229
19230 if (data.length > free) {
19231 overflow = data.slice(free);
19232 data = data.slice(0, free);
19233 }
19234
19235 this.bytesWritten += data.length;
19236 this.blockLength += data.length;
19237 this.blocks.push(data);
19238
19239 if (data.length < free) return done();
19240 this._writeBlock(done);
19241 };
19242
19243 WriteStream.prototype.destroy = function() {
19244 if (this._destroyed) return;
19245 this._destroyed = true;
19246 process.nextTick(this.emit.bind(this, 'close'));
19247 };
19248
19249 WriteStream.prototype.end = function(data) {
19250 var self = this;
19251 var args = arguments;
19252
19253 if (data && typeof data !== 'function') {
19254 this.write(data);
19255 data = EMPTY;
19256 }
19257
19258 this.write(EMPTY, function() {
19259 self._writeBlock(function(err) {
19260 if (err) return self.emit('error', err);
19261 self._flush(function(err) {
19262 if (err) return self.emit('error', err);
19263 Writable.prototype.end.apply(self, args);
19264 });
19265 });
19266 });
19267 };
19268
19269 var ReadStream = function(name, opts) {
19270 if (!opts) opts = {};
19271
19272 var self = this;
19273
19274 var start = opts.start || 0;
19275 var blockIndex = (start / blockSize) | 0;
19276 var blockOffset = start - blockIndex * blockSize;
19277 var key = name+'\xff'+pad(blockIndex);
19278
19279 this.name = name;
19280 this._missing = (typeof opts.end === 'number' ? opts.end : Infinity) - start + 1;
19281 this._paused = false;
19282 this._destroyed = false;
19283
19284 this._reader = db.createReadStream({
19285 start: key,
19286 end: name+'\xff\xff',
19287 valueEncoding: ENCODER
19288 });
19289
19290 var onblock = function(val) {
19291 key = name+'\xff'+pad(++blockIndex);
19292
19293 if (!self._missing) return false;
19294
19295 if (blockOffset) {
19296 val = val.slice(blockOffset);
19297 blockOffset = 0;
19298 if (!val.length) return true;
19299 }
19300
19301 if (val.length > self._missing) val = val.slice(0, self._missing);
19302
19303 self._missing -= val.length;
19304 self._pause(!self.push(val));
19305
19306 return !!self._missing;
19307 };
19308
19309 this._reader.on('data', function(data) {
19310 while (data.key > key) {
19311 if (!onblock(blank)) return;
19312 }
19313
19314 onblock(data.value);
19315 });
19316
19317 this._reader.on('error', function(err) {
19318 self.emit('error', err);
19319 });
19320
19321 this._reader.on('end', function() {
19322 self.push(null);
19323 });
19324
19325 Readable.call(this);
19326 };
19327
19328 util.inherits(ReadStream, Readable);
19329
19330 ReadStream.prototype.destroy = function() {
19331 if (this._destroyed) return;
19332 this._destroyed = true;
19333 this._reader.destroy();
19334 process.nextTick(this.emit.bind(this, 'close'));
19335 };
19336
19337 ReadStream.prototype._pause = function(paused) {
19338 if (this._paused === paused) return;
19339 this._paused = paused;
19340 if (this._paused) this._reader.pause();
19341 else this._reader.resume();
19342 };
19343
19344 ReadStream.prototype._read = function() {
19345 this._pause(false);
19346 };
19347
19348 blobs.remove = function(name, cb) {
19349 cb = once(cb || noop);
19350
19351 var batch = [];
19352 var keys = db.createKeyStream({
19353 start: name+'\xff',
19354 end: name+'\xff\xff'
19355 });
19356
19357 keys.on('error', cb);
19358
19359 keys.on('data', function(key) {
19360 batch.push({type:'del', key:key});
19361 });
19362
19363 keys.on('end', function() {
19364 db.batch(batch, cb);
19365 });
19366 };
19367
19368 blobs.size = function(name, cb) {
19369 peek.last(db, {
19370 start: name+'\xff',
19371 end: name+'\xff\xff',
19372 valueEncoding:ENCODER
19373 }, function(err, latest, val) {
19374 if (err && err.message === 'range not found') return cb(null, 0);
19375 if (err) return cb(err);
19376 if (latest.slice(0, name.length+1) !== name+'\xff') return cb(null, 0);
19377
19378 cb(null, parseInt(latest.toString().slice(name.length+1), 16) * blockSize + val.length);
19379 });
19380 };
19381
19382 blobs.write = function(name, data, opts, cb) {
19383 if (typeof opts === 'function') return blobs.write(name, data, null, opts);
19384 if (!opts) opts = {};
19385 if (!cb) cb = noop;
19386
19387 var ws = blobs.createWriteStream(name, opts);
19388
19389 ws.on('error', cb);
19390 ws.on('finish', function() {
19391 cb();
19392 });
19393
19394 ws.write(data);
19395 ws.end();
19396 }
19397
19398 blobs.read = function(name, opts, cb) {
19399 if (typeof opts === 'function') return blobs.read(name, null, opts);
19400 if (!opts) opts = {};
19401
19402 var rs = blobs.createReadStream(name, opts);
19403 var list = [];
19404
19405 rs.on('error', cb);
19406 rs.on('data', function(data) {
19407 list.push(data);
19408 });
19409 rs.on('end', function() {
19410 cb(null, list.length === 1 ? list[0] : Buffer.concat(list));
19411 });
19412 };
19413
19414 blobs.createReadStream = function(name, opts) {
19415 return new ReadStream(name, opts);
19416 };
19417
19418 blobs.createWriteStream = function(name, opts) {
19419 return new WriteStream(name, opts);
19420 };
19421
19422 return blobs;
19423};}, {"readable-stream/writable":110,"readable-stream/readable":117,"level-peek":120,"util":23,"once":122}],110: [function (exports, require, module, global) {module.exports = require("./lib/_stream_writable.js")
19424}, {"./lib/_stream_writable.js":111}],111: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
19425//
19426// Permission is hereby granted, free of charge, to any person obtaining a
19427// copy of this software and associated documentation files (the
19428// "Software"), to deal in the Software without restriction, including
19429// without limitation the rights to use, copy, modify, merge, publish,
19430// distribute, sublicense, and/or sell copies of the Software, and to permit
19431// persons to whom the Software is furnished to do so, subject to the
19432// following conditions:
19433//
19434// The above copyright notice and this permission notice shall be included
19435// in all copies or substantial portions of the Software.
19436//
19437// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19438// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19439// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
19440// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
19441// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19442// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19443// USE OR OTHER DEALINGS IN THE SOFTWARE.
19444
19445// A bit simpler than readable streams.
19446// Implement an async ._write(chunk, cb), and it'll handle all
19447// the drain event emission and buffering.
19448
19449module.exports = Writable;
19450
19451/*<replacement>*/
19452var Buffer = require('buffer').Buffer;
19453/*</replacement>*/
19454
19455Writable.WritableState = WritableState;
19456
19457
19458/*<replacement>*/
19459var util = require('core-util-is');
19460util.inherits = require('inherits');
19461/*</replacement>*/
19462
19463var Stream = require('stream');
19464
19465util.inherits(Writable, Stream);
19466
19467function WriteReq(chunk, encoding, cb) {
19468 this.chunk = chunk;
19469 this.encoding = encoding;
19470 this.callback = cb;
19471}
19472
19473function WritableState(options, stream) {
19474 var Duplex = require('./_stream_duplex');
19475
19476 options = options || {};
19477
19478 // the point at which write() starts returning false
19479 // Note: 0 is a valid value, means that we always return false if
19480 // the entire buffer is not flushed immediately on write()
19481 var hwm = options.highWaterMark;
19482 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
19483 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
19484
19485 // object stream flag to indicate whether or not this stream
19486 // contains buffers or objects.
19487 this.objectMode = !!options.objectMode;
19488
19489 if (stream instanceof Duplex)
19490 this.objectMode = this.objectMode || !!options.writableObjectMode;
19491
19492 // cast to ints.
19493 this.highWaterMark = ~~this.highWaterMark;
19494
19495 this.needDrain = false;
19496 // at the start of calling end()
19497 this.ending = false;
19498 // when end() has been called, and returned
19499 this.ended = false;
19500 // when 'finish' is emitted
19501 this.finished = false;
19502
19503 // should we decode strings into buffers before passing to _write?
19504 // this is here so that some node-core streams can optimize string
19505 // handling at a lower level.
19506 var noDecode = options.decodeStrings === false;
19507 this.decodeStrings = !noDecode;
19508
19509 // Crypto is kind of old and crusty. Historically, its default string
19510 // encoding is 'binary' so we have to make this configurable.
19511 // Everything else in the universe uses 'utf8', though.
19512 this.defaultEncoding = options.defaultEncoding || 'utf8';
19513
19514 // not an actual buffer we keep track of, but a measurement
19515 // of how much we're waiting to get pushed to some underlying
19516 // socket or file.
19517 this.length = 0;
19518
19519 // a flag to see when we're in the middle of a write.
19520 this.writing = false;
19521
19522 // when true all writes will be buffered until .uncork() call
19523 this.corked = 0;
19524
19525 // a flag to be able to tell if the onwrite cb is called immediately,
19526 // or on a later tick. We set this to true at first, because any
19527 // actions that shouldn't happen until "later" should generally also
19528 // not happen before the first write call.
19529 this.sync = true;
19530
19531 // a flag to know if we're processing previously buffered items, which
19532 // may call the _write() callback in the same tick, so that we don't
19533 // end up in an overlapped onwrite situation.
19534 this.bufferProcessing = false;
19535
19536 // the callback that's passed to _write(chunk,cb)
19537 this.onwrite = function(er) {
19538 onwrite(stream, er);
19539 };
19540
19541 // the callback that the user supplies to write(chunk,encoding,cb)
19542 this.writecb = null;
19543
19544 // the amount that is being written when _write is called.
19545 this.writelen = 0;
19546
19547 this.buffer = [];
19548
19549 // number of pending user-supplied write callbacks
19550 // this must be 0 before 'finish' can be emitted
19551 this.pendingcb = 0;
19552
19553 // emit prefinish if the only thing we're waiting for is _write cbs
19554 // This is relevant for synchronous Transform streams
19555 this.prefinished = false;
19556
19557 // True if the error was already emitted and should not be thrown again
19558 this.errorEmitted = false;
19559}
19560
19561function Writable(options) {
19562 var Duplex = require('./_stream_duplex');
19563
19564 // Writable ctor is applied to Duplexes, though they're not
19565 // instanceof Writable, they're instanceof Readable.
19566 if (!(this instanceof Writable) && !(this instanceof Duplex))
19567 return new Writable(options);
19568
19569 this._writableState = new WritableState(options, this);
19570
19571 // legacy.
19572 this.writable = true;
19573
19574 Stream.call(this);
19575}
19576
19577// Otherwise people can pipe Writable streams, which is just wrong.
19578Writable.prototype.pipe = function() {
19579 this.emit('error', new Error('Cannot pipe. Not readable.'));
19580};
19581
19582
19583function writeAfterEnd(stream, state, cb) {
19584 var er = new Error('write after end');
19585 // TODO: defer error events consistently everywhere, not just the cb
19586 stream.emit('error', er);
19587 process.nextTick(function() {
19588 cb(er);
19589 });
19590}
19591
19592// If we get something that is not a buffer, string, null, or undefined,
19593// and we're not in objectMode, then that's an error.
19594// Otherwise stream chunks are all considered to be of length=1, and the
19595// watermarks determine how many objects to keep in the buffer, rather than
19596// how many bytes or characters.
19597function validChunk(stream, state, chunk, cb) {
19598 var valid = true;
19599 if (!util.isBuffer(chunk) &&
19600 !util.isString(chunk) &&
19601 !util.isNullOrUndefined(chunk) &&
19602 !state.objectMode) {
19603 var er = new TypeError('Invalid non-string/buffer chunk');
19604 stream.emit('error', er);
19605 process.nextTick(function() {
19606 cb(er);
19607 });
19608 valid = false;
19609 }
19610 return valid;
19611}
19612
19613Writable.prototype.write = function(chunk, encoding, cb) {
19614 var state = this._writableState;
19615 var ret = false;
19616
19617 if (util.isFunction(encoding)) {
19618 cb = encoding;
19619 encoding = null;
19620 }
19621
19622 if (util.isBuffer(chunk))
19623 encoding = 'buffer';
19624 else if (!encoding)
19625 encoding = state.defaultEncoding;
19626
19627 if (!util.isFunction(cb))
19628 cb = function() {};
19629
19630 if (state.ended)
19631 writeAfterEnd(this, state, cb);
19632 else if (validChunk(this, state, chunk, cb)) {
19633 state.pendingcb++;
19634 ret = writeOrBuffer(this, state, chunk, encoding, cb);
19635 }
19636
19637 return ret;
19638};
19639
19640Writable.prototype.cork = function() {
19641 var state = this._writableState;
19642
19643 state.corked++;
19644};
19645
19646Writable.prototype.uncork = function() {
19647 var state = this._writableState;
19648
19649 if (state.corked) {
19650 state.corked--;
19651
19652 if (!state.writing &&
19653 !state.corked &&
19654 !state.finished &&
19655 !state.bufferProcessing &&
19656 state.buffer.length)
19657 clearBuffer(this, state);
19658 }
19659};
19660
19661function decodeChunk(state, chunk, encoding) {
19662 if (!state.objectMode &&
19663 state.decodeStrings !== false &&
19664 util.isString(chunk)) {
19665 chunk = new Buffer(chunk, encoding);
19666 }
19667 return chunk;
19668}
19669
19670// if we're already writing something, then just put this
19671// in the queue, and wait our turn. Otherwise, call _write
19672// If we return false, then we need a drain event, so set that flag.
19673function writeOrBuffer(stream, state, chunk, encoding, cb) {
19674 chunk = decodeChunk(state, chunk, encoding);
19675 if (util.isBuffer(chunk))
19676 encoding = 'buffer';
19677 var len = state.objectMode ? 1 : chunk.length;
19678
19679 state.length += len;
19680
19681 var ret = state.length < state.highWaterMark;
19682 // we must ensure that previous needDrain will not be reset to false.
19683 if (!ret)
19684 state.needDrain = true;
19685
19686 if (state.writing || state.corked)
19687 state.buffer.push(new WriteReq(chunk, encoding, cb));
19688 else
19689 doWrite(stream, state, false, len, chunk, encoding, cb);
19690
19691 return ret;
19692}
19693
19694function doWrite(stream, state, writev, len, chunk, encoding, cb) {
19695 state.writelen = len;
19696 state.writecb = cb;
19697 state.writing = true;
19698 state.sync = true;
19699 if (writev)
19700 stream._writev(chunk, state.onwrite);
19701 else
19702 stream._write(chunk, encoding, state.onwrite);
19703 state.sync = false;
19704}
19705
19706function onwriteError(stream, state, sync, er, cb) {
19707 if (sync)
19708 process.nextTick(function() {
19709 state.pendingcb--;
19710 cb(er);
19711 });
19712 else {
19713 state.pendingcb--;
19714 cb(er);
19715 }
19716
19717 stream._writableState.errorEmitted = true;
19718 stream.emit('error', er);
19719}
19720
19721function onwriteStateUpdate(state) {
19722 state.writing = false;
19723 state.writecb = null;
19724 state.length -= state.writelen;
19725 state.writelen = 0;
19726}
19727
19728function onwrite(stream, er) {
19729 var state = stream._writableState;
19730 var sync = state.sync;
19731 var cb = state.writecb;
19732
19733 onwriteStateUpdate(state);
19734
19735 if (er)
19736 onwriteError(stream, state, sync, er, cb);
19737 else {
19738 // Check if we're actually ready to finish, but don't emit yet
19739 var finished = needFinish(stream, state);
19740
19741 if (!finished &&
19742 !state.corked &&
19743 !state.bufferProcessing &&
19744 state.buffer.length) {
19745 clearBuffer(stream, state);
19746 }
19747
19748 if (sync) {
19749 process.nextTick(function() {
19750 afterWrite(stream, state, finished, cb);
19751 });
19752 } else {
19753 afterWrite(stream, state, finished, cb);
19754 }
19755 }
19756}
19757
19758function afterWrite(stream, state, finished, cb) {
19759 if (!finished)
19760 onwriteDrain(stream, state);
19761 state.pendingcb--;
19762 cb();
19763 finishMaybe(stream, state);
19764}
19765
19766// Must force callback to be called on nextTick, so that we don't
19767// emit 'drain' before the write() consumer gets the 'false' return
19768// value, and has a chance to attach a 'drain' listener.
19769function onwriteDrain(stream, state) {
19770 if (state.length === 0 && state.needDrain) {
19771 state.needDrain = false;
19772 stream.emit('drain');
19773 }
19774}
19775
19776
19777// if there's something in the buffer waiting, then process it
19778function clearBuffer(stream, state) {
19779 state.bufferProcessing = true;
19780
19781 if (stream._writev && state.buffer.length > 1) {
19782 // Fast case, write everything using _writev()
19783 var cbs = [];
19784 for (var c = 0; c < state.buffer.length; c++)
19785 cbs.push(state.buffer[c].callback);
19786
19787 // count the one we are adding, as well.
19788 // TODO(isaacs) clean this up
19789 state.pendingcb++;
19790 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
19791 for (var i = 0; i < cbs.length; i++) {
19792 state.pendingcb--;
19793 cbs[i](err);
19794 }
19795 });
19796
19797 // Clear buffer
19798 state.buffer = [];
19799 } else {
19800 // Slow case, write chunks one-by-one
19801 for (var c = 0; c < state.buffer.length; c++) {
19802 var entry = state.buffer[c];
19803 var chunk = entry.chunk;
19804 var encoding = entry.encoding;
19805 var cb = entry.callback;
19806 var len = state.objectMode ? 1 : chunk.length;
19807
19808 doWrite(stream, state, false, len, chunk, encoding, cb);
19809
19810 // if we didn't call the onwrite immediately, then
19811 // it means that we need to wait until it does.
19812 // also, that means that the chunk and cb are currently
19813 // being processed, so move the buffer counter past them.
19814 if (state.writing) {
19815 c++;
19816 break;
19817 }
19818 }
19819
19820 if (c < state.buffer.length)
19821 state.buffer = state.buffer.slice(c);
19822 else
19823 state.buffer.length = 0;
19824 }
19825
19826 state.bufferProcessing = false;
19827}
19828
19829Writable.prototype._write = function(chunk, encoding, cb) {
19830 cb(new Error('not implemented'));
19831
19832};
19833
19834Writable.prototype._writev = null;
19835
19836Writable.prototype.end = function(chunk, encoding, cb) {
19837 var state = this._writableState;
19838
19839 if (util.isFunction(chunk)) {
19840 cb = chunk;
19841 chunk = null;
19842 encoding = null;
19843 } else if (util.isFunction(encoding)) {
19844 cb = encoding;
19845 encoding = null;
19846 }
19847
19848 if (!util.isNullOrUndefined(chunk))
19849 this.write(chunk, encoding);
19850
19851 // .end() fully uncorks
19852 if (state.corked) {
19853 state.corked = 1;
19854 this.uncork();
19855 }
19856
19857 // ignore unnecessary end() calls.
19858 if (!state.ending && !state.finished)
19859 endWritable(this, state, cb);
19860};
19861
19862
19863function needFinish(stream, state) {
19864 return (state.ending &&
19865 state.length === 0 &&
19866 !state.finished &&
19867 !state.writing);
19868}
19869
19870function prefinish(stream, state) {
19871 if (!state.prefinished) {
19872 state.prefinished = true;
19873 stream.emit('prefinish');
19874 }
19875}
19876
19877function finishMaybe(stream, state) {
19878 var need = needFinish(stream, state);
19879 if (need) {
19880 if (state.pendingcb === 0) {
19881 prefinish(stream, state);
19882 state.finished = true;
19883 stream.emit('finish');
19884 } else
19885 prefinish(stream, state);
19886 }
19887 return need;
19888}
19889
19890function endWritable(stream, state, cb) {
19891 state.ending = true;
19892 finishMaybe(stream, state);
19893 if (cb) {
19894 if (state.finished)
19895 process.nextTick(cb);
19896 else
19897 stream.once('finish', cb);
19898 }
19899 state.ended = true;
19900}
19901}, {"buffer":29,"core-util-is":112,"inherits":113,"stream":52,"./_stream_duplex":114}],112: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
19902//
19903// Permission is hereby granted, free of charge, to any person obtaining a
19904// copy of this software and associated documentation files (the
19905// "Software"), to deal in the Software without restriction, including
19906// without limitation the rights to use, copy, modify, merge, publish,
19907// distribute, sublicense, and/or sell copies of the Software, and to permit
19908// persons to whom the Software is furnished to do so, subject to the
19909// following conditions:
19910//
19911// The above copyright notice and this permission notice shall be included
19912// in all copies or substantial portions of the Software.
19913//
19914// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19915// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19916// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
19917// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
19918// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19919// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19920// USE OR OTHER DEALINGS IN THE SOFTWARE.
19921
19922// NOTE: These type checking functions intentionally don't use `instanceof`
19923// because it is fragile and can be easily faked with `Object.create()`.
19924function isArray(ar) {
19925 return Array.isArray(ar);
19926}
19927exports.isArray = isArray;
19928
19929function isBoolean(arg) {
19930 return typeof arg === 'boolean';
19931}
19932exports.isBoolean = isBoolean;
19933
19934function isNull(arg) {
19935 return arg === null;
19936}
19937exports.isNull = isNull;
19938
19939function isNullOrUndefined(arg) {
19940 return arg == null;
19941}
19942exports.isNullOrUndefined = isNullOrUndefined;
19943
19944function isNumber(arg) {
19945 return typeof arg === 'number';
19946}
19947exports.isNumber = isNumber;
19948
19949function isString(arg) {
19950 return typeof arg === 'string';
19951}
19952exports.isString = isString;
19953
19954function isSymbol(arg) {
19955 return typeof arg === 'symbol';
19956}
19957exports.isSymbol = isSymbol;
19958
19959function isUndefined(arg) {
19960 return arg === void 0;
19961}
19962exports.isUndefined = isUndefined;
19963
19964function isRegExp(re) {
19965 return isObject(re) && objectToString(re) === '[object RegExp]';
19966}
19967exports.isRegExp = isRegExp;
19968
19969function isObject(arg) {
19970 return typeof arg === 'object' && arg !== null;
19971}
19972exports.isObject = isObject;
19973
19974function isDate(d) {
19975 return isObject(d) && objectToString(d) === '[object Date]';
19976}
19977exports.isDate = isDate;
19978
19979function isError(e) {
19980 return isObject(e) &&
19981 (objectToString(e) === '[object Error]' || e instanceof Error);
19982}
19983exports.isError = isError;
19984
19985function isFunction(arg) {
19986 return typeof arg === 'function';
19987}
19988exports.isFunction = isFunction;
19989
19990function isPrimitive(arg) {
19991 return arg === null ||
19992 typeof arg === 'boolean' ||
19993 typeof arg === 'number' ||
19994 typeof arg === 'string' ||
19995 typeof arg === 'symbol' || // ES6 symbol
19996 typeof arg === 'undefined';
19997}
19998exports.isPrimitive = isPrimitive;
19999
20000function isBuffer(arg) {
20001 return Buffer.isBuffer(arg);
20002}
20003exports.isBuffer = isBuffer;
20004
20005function objectToString(o) {
20006 return Object.prototype.toString.call(o);
20007}}, {}],113: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
20008 // implementation from standard node.js 'util' module
20009 module.exports = function inherits(ctor, superCtor) {
20010 ctor.super_ = superCtor
20011 ctor.prototype = Object.create(superCtor.prototype, {
20012 constructor: {
20013 value: ctor,
20014 enumerable: false,
20015 writable: true,
20016 configurable: true
20017 }
20018 });
20019 };
20020} else {
20021 // old school shim for old browsers
20022 module.exports = function inherits(ctor, superCtor) {
20023 ctor.super_ = superCtor
20024 var TempCtor = function () {}
20025 TempCtor.prototype = superCtor.prototype
20026 ctor.prototype = new TempCtor()
20027 ctor.prototype.constructor = ctor
20028 }
20029}
20030}, {}],114: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
20031//
20032// Permission is hereby granted, free of charge, to any person obtaining a
20033// copy of this software and associated documentation files (the
20034// "Software"), to deal in the Software without restriction, including
20035// without limitation the rights to use, copy, modify, merge, publish,
20036// distribute, sublicense, and/or sell copies of the Software, and to permit
20037// persons to whom the Software is furnished to do so, subject to the
20038// following conditions:
20039//
20040// The above copyright notice and this permission notice shall be included
20041// in all copies or substantial portions of the Software.
20042//
20043// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20044// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20045// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
20046// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
20047// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20048// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20049// USE OR OTHER DEALINGS IN THE SOFTWARE.
20050
20051// a duplex stream is just a stream that is both readable and writable.
20052// Since JS doesn't have multiple prototypal inheritance, this class
20053// prototypally inherits from Readable, and then parasitically from
20054// Writable.
20055
20056module.exports = Duplex;
20057
20058/*<replacement>*/
20059var objectKeys = Object.keys || function (obj) {
20060 var keys = [];
20061 for (var key in obj) keys.push(key);
20062 return keys;
20063}
20064/*</replacement>*/
20065
20066
20067/*<replacement>*/
20068var util = require('core-util-is');
20069util.inherits = require('inherits');
20070/*</replacement>*/
20071
20072var Readable = require('./_stream_readable');
20073var Writable = require('./_stream_writable');
20074
20075util.inherits(Duplex, Readable);
20076
20077forEach(objectKeys(Writable.prototype), function(method) {
20078 if (!Duplex.prototype[method])
20079 Duplex.prototype[method] = Writable.prototype[method];
20080});
20081
20082function Duplex(options) {
20083 if (!(this instanceof Duplex))
20084 return new Duplex(options);
20085
20086 Readable.call(this, options);
20087 Writable.call(this, options);
20088
20089 if (options && options.readable === false)
20090 this.readable = false;
20091
20092 if (options && options.writable === false)
20093 this.writable = false;
20094
20095 this.allowHalfOpen = true;
20096 if (options && options.allowHalfOpen === false)
20097 this.allowHalfOpen = false;
20098
20099 this.once('end', onend);
20100}
20101
20102// the no-half-open enforcer
20103function onend() {
20104 // if we allow half-open state, or if the writable side ended,
20105 // then we're ok.
20106 if (this.allowHalfOpen || this._writableState.ended)
20107 return;
20108
20109 // no more data can be written.
20110 // But allow more writes to happen in this tick.
20111 process.nextTick(this.end.bind(this));
20112}
20113
20114function forEach (xs, f) {
20115 for (var i = 0, l = xs.length; i < l; i++) {
20116 f(xs[i], i);
20117 }
20118}
20119}, {"core-util-is":112,"inherits":113,"./_stream_readable":115,"./_stream_writable":111}],115: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
20120//
20121// Permission is hereby granted, free of charge, to any person obtaining a
20122// copy of this software and associated documentation files (the
20123// "Software"), to deal in the Software without restriction, including
20124// without limitation the rights to use, copy, modify, merge, publish,
20125// distribute, sublicense, and/or sell copies of the Software, and to permit
20126// persons to whom the Software is furnished to do so, subject to the
20127// following conditions:
20128//
20129// The above copyright notice and this permission notice shall be included
20130// in all copies or substantial portions of the Software.
20131//
20132// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20133// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20134// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
20135// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
20136// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20137// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20138// USE OR OTHER DEALINGS IN THE SOFTWARE.
20139
20140module.exports = Readable;
20141
20142/*<replacement>*/
20143var isArray = require('isarray');
20144/*</replacement>*/
20145
20146
20147/*<replacement>*/
20148var Buffer = require('buffer').Buffer;
20149/*</replacement>*/
20150
20151Readable.ReadableState = ReadableState;
20152
20153var EE = require('events').EventEmitter;
20154
20155/*<replacement>*/
20156if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
20157 return emitter.listeners(type).length;
20158};
20159/*</replacement>*/
20160
20161var Stream = require('stream');
20162
20163/*<replacement>*/
20164var util = require('core-util-is');
20165util.inherits = require('inherits');
20166/*</replacement>*/
20167
20168var StringDecoder;
20169
20170
20171/*<replacement>*/
20172var debug = require('util');
20173if (debug && debug.debuglog) {
20174 debug = debug.debuglog('stream');
20175} else {
20176 debug = function () {};
20177}
20178/*</replacement>*/
20179
20180
20181util.inherits(Readable, Stream);
20182
20183function ReadableState(options, stream) {
20184 var Duplex = require('./_stream_duplex');
20185
20186 options = options || {};
20187
20188 // the point at which it stops calling _read() to fill the buffer
20189 // Note: 0 is a valid value, means "don't call _read preemptively ever"
20190 var hwm = options.highWaterMark;
20191 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
20192 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
20193
20194 // cast to ints.
20195 this.highWaterMark = ~~this.highWaterMark;
20196
20197 this.buffer = [];
20198 this.length = 0;
20199 this.pipes = null;
20200 this.pipesCount = 0;
20201 this.flowing = null;
20202 this.ended = false;
20203 this.endEmitted = false;
20204 this.reading = false;
20205
20206 // a flag to be able to tell if the onwrite cb is called immediately,
20207 // or on a later tick. We set this to true at first, because any
20208 // actions that shouldn't happen until "later" should generally also
20209 // not happen before the first write call.
20210 this.sync = true;
20211
20212 // whenever we return null, then we set a flag to say
20213 // that we're awaiting a 'readable' event emission.
20214 this.needReadable = false;
20215 this.emittedReadable = false;
20216 this.readableListening = false;
20217
20218
20219 // object stream flag. Used to make read(n) ignore n and to
20220 // make all the buffer merging and length checks go away
20221 this.objectMode = !!options.objectMode;
20222
20223 if (stream instanceof Duplex)
20224 this.objectMode = this.objectMode || !!options.readableObjectMode;
20225
20226 // Crypto is kind of old and crusty. Historically, its default string
20227 // encoding is 'binary' so we have to make this configurable.
20228 // Everything else in the universe uses 'utf8', though.
20229 this.defaultEncoding = options.defaultEncoding || 'utf8';
20230
20231 // when piping, we only care about 'readable' events that happen
20232 // after read()ing all the bytes and not getting any pushback.
20233 this.ranOut = false;
20234
20235 // the number of writers that are awaiting a drain event in .pipe()s
20236 this.awaitDrain = 0;
20237
20238 // if true, a maybeReadMore has been scheduled
20239 this.readingMore = false;
20240
20241 this.decoder = null;
20242 this.encoding = null;
20243 if (options.encoding) {
20244 if (!StringDecoder)
20245 StringDecoder = require('string_decoder/').StringDecoder;
20246 this.decoder = new StringDecoder(options.encoding);
20247 this.encoding = options.encoding;
20248 }
20249}
20250
20251function Readable(options) {
20252 var Duplex = require('./_stream_duplex');
20253
20254 if (!(this instanceof Readable))
20255 return new Readable(options);
20256
20257 this._readableState = new ReadableState(options, this);
20258
20259 // legacy
20260 this.readable = true;
20261
20262 Stream.call(this);
20263}
20264
20265// Manually shove something into the read() buffer.
20266// This returns true if the highWaterMark has not been hit yet,
20267// similar to how Writable.write() returns true if you should
20268// write() some more.
20269Readable.prototype.push = function(chunk, encoding) {
20270 var state = this._readableState;
20271
20272 if (util.isString(chunk) && !state.objectMode) {
20273 encoding = encoding || state.defaultEncoding;
20274 if (encoding !== state.encoding) {
20275 chunk = new Buffer(chunk, encoding);
20276 encoding = '';
20277 }
20278 }
20279
20280 return readableAddChunk(this, state, chunk, encoding, false);
20281};
20282
20283// Unshift should *always* be something directly out of read()
20284Readable.prototype.unshift = function(chunk) {
20285 var state = this._readableState;
20286 return readableAddChunk(this, state, chunk, '', true);
20287};
20288
20289function readableAddChunk(stream, state, chunk, encoding, addToFront) {
20290 var er = chunkInvalid(state, chunk);
20291 if (er) {
20292 stream.emit('error', er);
20293 } else if (util.isNullOrUndefined(chunk)) {
20294 state.reading = false;
20295 if (!state.ended)
20296 onEofChunk(stream, state);
20297 } else if (state.objectMode || chunk && chunk.length > 0) {
20298 if (state.ended && !addToFront) {
20299 var e = new Error('stream.push() after EOF');
20300 stream.emit('error', e);
20301 } else if (state.endEmitted && addToFront) {
20302 var e = new Error('stream.unshift() after end event');
20303 stream.emit('error', e);
20304 } else {
20305 if (state.decoder && !addToFront && !encoding)
20306 chunk = state.decoder.write(chunk);
20307
20308 if (!addToFront)
20309 state.reading = false;
20310
20311 // if we want the data now, just emit it.
20312 if (state.flowing && state.length === 0 && !state.sync) {
20313 stream.emit('data', chunk);
20314 stream.read(0);
20315 } else {
20316 // update the buffer info.
20317 state.length += state.objectMode ? 1 : chunk.length;
20318 if (addToFront)
20319 state.buffer.unshift(chunk);
20320 else
20321 state.buffer.push(chunk);
20322
20323 if (state.needReadable)
20324 emitReadable(stream);
20325 }
20326
20327 maybeReadMore(stream, state);
20328 }
20329 } else if (!addToFront) {
20330 state.reading = false;
20331 }
20332
20333 return needMoreData(state);
20334}
20335
20336
20337
20338// if it's past the high water mark, we can push in some more.
20339// Also, if we have no data yet, we can stand some
20340// more bytes. This is to work around cases where hwm=0,
20341// such as the repl. Also, if the push() triggered a
20342// readable event, and the user called read(largeNumber) such that
20343// needReadable was set, then we ought to push more, so that another
20344// 'readable' event will be triggered.
20345function needMoreData(state) {
20346 return !state.ended &&
20347 (state.needReadable ||
20348 state.length < state.highWaterMark ||
20349 state.length === 0);
20350}
20351
20352// backwards compatibility.
20353Readable.prototype.setEncoding = function(enc) {
20354 if (!StringDecoder)
20355 StringDecoder = require('string_decoder/').StringDecoder;
20356 this._readableState.decoder = new StringDecoder(enc);
20357 this._readableState.encoding = enc;
20358 return this;
20359};
20360
20361// Don't raise the hwm > 128MB
20362var MAX_HWM = 0x800000;
20363function roundUpToNextPowerOf2(n) {
20364 if (n >= MAX_HWM) {
20365 n = MAX_HWM;
20366 } else {
20367 // Get the next highest power of 2
20368 n--;
20369 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
20370 n++;
20371 }
20372 return n;
20373}
20374
20375function howMuchToRead(n, state) {
20376 if (state.length === 0 && state.ended)
20377 return 0;
20378
20379 if (state.objectMode)
20380 return n === 0 ? 0 : 1;
20381
20382 if (isNaN(n) || util.isNull(n)) {
20383 // only flow one buffer at a time
20384 if (state.flowing && state.buffer.length)
20385 return state.buffer[0].length;
20386 else
20387 return state.length;
20388 }
20389
20390 if (n <= 0)
20391 return 0;
20392
20393 // If we're asking for more than the target buffer level,
20394 // then raise the water mark. Bump up to the next highest
20395 // power of 2, to prevent increasing it excessively in tiny
20396 // amounts.
20397 if (n > state.highWaterMark)
20398 state.highWaterMark = roundUpToNextPowerOf2(n);
20399
20400 // don't have that much. return null, unless we've ended.
20401 if (n > state.length) {
20402 if (!state.ended) {
20403 state.needReadable = true;
20404 return 0;
20405 } else
20406 return state.length;
20407 }
20408
20409 return n;
20410}
20411
20412// you can override either this method, or the async _read(n) below.
20413Readable.prototype.read = function(n) {
20414 debug('read', n);
20415 var state = this._readableState;
20416 var nOrig = n;
20417
20418 if (!util.isNumber(n) || n > 0)
20419 state.emittedReadable = false;
20420
20421 // if we're doing read(0) to trigger a readable event, but we
20422 // already have a bunch of data in the buffer, then just trigger
20423 // the 'readable' event and move on.
20424 if (n === 0 &&
20425 state.needReadable &&
20426 (state.length >= state.highWaterMark || state.ended)) {
20427 debug('read: emitReadable', state.length, state.ended);
20428 if (state.length === 0 && state.ended)
20429 endReadable(this);
20430 else
20431 emitReadable(this);
20432 return null;
20433 }
20434
20435 n = howMuchToRead(n, state);
20436
20437 // if we've ended, and we're now clear, then finish it up.
20438 if (n === 0 && state.ended) {
20439 if (state.length === 0)
20440 endReadable(this);
20441 return null;
20442 }
20443
20444 // All the actual chunk generation logic needs to be
20445 // *below* the call to _read. The reason is that in certain
20446 // synthetic stream cases, such as passthrough streams, _read
20447 // may be a completely synchronous operation which may change
20448 // the state of the read buffer, providing enough data when
20449 // before there was *not* enough.
20450 //
20451 // So, the steps are:
20452 // 1. Figure out what the state of things will be after we do
20453 // a read from the buffer.
20454 //
20455 // 2. If that resulting state will trigger a _read, then call _read.
20456 // Note that this may be asynchronous, or synchronous. Yes, it is
20457 // deeply ugly to write APIs this way, but that still doesn't mean
20458 // that the Readable class should behave improperly, as streams are
20459 // designed to be sync/async agnostic.
20460 // Take note if the _read call is sync or async (ie, if the read call
20461 // has returned yet), so that we know whether or not it's safe to emit
20462 // 'readable' etc.
20463 //
20464 // 3. Actually pull the requested chunks out of the buffer and return.
20465
20466 // if we need a readable event, then we need to do some reading.
20467 var doRead = state.needReadable;
20468 debug('need readable', doRead);
20469
20470 // if we currently have less than the highWaterMark, then also read some
20471 if (state.length === 0 || state.length - n < state.highWaterMark) {
20472 doRead = true;
20473 debug('length less than watermark', doRead);
20474 }
20475
20476 // however, if we've ended, then there's no point, and if we're already
20477 // reading, then it's unnecessary.
20478 if (state.ended || state.reading) {
20479 doRead = false;
20480 debug('reading or ended', doRead);
20481 }
20482
20483 if (doRead) {
20484 debug('do read');
20485 state.reading = true;
20486 state.sync = true;
20487 // if the length is currently zero, then we *need* a readable event.
20488 if (state.length === 0)
20489 state.needReadable = true;
20490 // call internal read method
20491 this._read(state.highWaterMark);
20492 state.sync = false;
20493 }
20494
20495 // If _read pushed data synchronously, then `reading` will be false,
20496 // and we need to re-evaluate how much data we can return to the user.
20497 if (doRead && !state.reading)
20498 n = howMuchToRead(nOrig, state);
20499
20500 var ret;
20501 if (n > 0)
20502 ret = fromList(n, state);
20503 else
20504 ret = null;
20505
20506 if (util.isNull(ret)) {
20507 state.needReadable = true;
20508 n = 0;
20509 }
20510
20511 state.length -= n;
20512
20513 // If we have nothing in the buffer, then we want to know
20514 // as soon as we *do* get something into the buffer.
20515 if (state.length === 0 && !state.ended)
20516 state.needReadable = true;
20517
20518 // If we tried to read() past the EOF, then emit end on the next tick.
20519 if (nOrig !== n && state.ended && state.length === 0)
20520 endReadable(this);
20521
20522 if (!util.isNull(ret))
20523 this.emit('data', ret);
20524
20525 return ret;
20526};
20527
20528function chunkInvalid(state, chunk) {
20529 var er = null;
20530 if (!util.isBuffer(chunk) &&
20531 !util.isString(chunk) &&
20532 !util.isNullOrUndefined(chunk) &&
20533 !state.objectMode) {
20534 er = new TypeError('Invalid non-string/buffer chunk');
20535 }
20536 return er;
20537}
20538
20539
20540function onEofChunk(stream, state) {
20541 if (state.decoder && !state.ended) {
20542 var chunk = state.decoder.end();
20543 if (chunk && chunk.length) {
20544 state.buffer.push(chunk);
20545 state.length += state.objectMode ? 1 : chunk.length;
20546 }
20547 }
20548 state.ended = true;
20549
20550 // emit 'readable' now to make sure it gets picked up.
20551 emitReadable(stream);
20552}
20553
20554// Don't emit readable right away in sync mode, because this can trigger
20555// another read() call => stack overflow. This way, it might trigger
20556// a nextTick recursion warning, but that's not so bad.
20557function emitReadable(stream) {
20558 var state = stream._readableState;
20559 state.needReadable = false;
20560 if (!state.emittedReadable) {
20561 debug('emitReadable', state.flowing);
20562 state.emittedReadable = true;
20563 if (state.sync)
20564 process.nextTick(function() {
20565 emitReadable_(stream);
20566 });
20567 else
20568 emitReadable_(stream);
20569 }
20570}
20571
20572function emitReadable_(stream) {
20573 debug('emit readable');
20574 stream.emit('readable');
20575 flow(stream);
20576}
20577
20578
20579// at this point, the user has presumably seen the 'readable' event,
20580// and called read() to consume some data. that may have triggered
20581// in turn another _read(n) call, in which case reading = true if
20582// it's in progress.
20583// However, if we're not ended, or reading, and the length < hwm,
20584// then go ahead and try to read some more preemptively.
20585function maybeReadMore(stream, state) {
20586 if (!state.readingMore) {
20587 state.readingMore = true;
20588 process.nextTick(function() {
20589 maybeReadMore_(stream, state);
20590 });
20591 }
20592}
20593
20594function maybeReadMore_(stream, state) {
20595 var len = state.length;
20596 while (!state.reading && !state.flowing && !state.ended &&
20597 state.length < state.highWaterMark) {
20598 debug('maybeReadMore read 0');
20599 stream.read(0);
20600 if (len === state.length)
20601 // didn't get any data, stop spinning.
20602 break;
20603 else
20604 len = state.length;
20605 }
20606 state.readingMore = false;
20607}
20608
20609// abstract method. to be overridden in specific implementation classes.
20610// call cb(er, data) where data is <= n in length.
20611// for virtual (non-string, non-buffer) streams, "length" is somewhat
20612// arbitrary, and perhaps not very meaningful.
20613Readable.prototype._read = function(n) {
20614 this.emit('error', new Error('not implemented'));
20615};
20616
20617Readable.prototype.pipe = function(dest, pipeOpts) {
20618 var src = this;
20619 var state = this._readableState;
20620
20621 switch (state.pipesCount) {
20622 case 0:
20623 state.pipes = dest;
20624 break;
20625 case 1:
20626 state.pipes = [state.pipes, dest];
20627 break;
20628 default:
20629 state.pipes.push(dest);
20630 break;
20631 }
20632 state.pipesCount += 1;
20633 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
20634
20635 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
20636 dest !== process.stdout &&
20637 dest !== process.stderr;
20638
20639 var endFn = doEnd ? onend : cleanup;
20640 if (state.endEmitted)
20641 process.nextTick(endFn);
20642 else
20643 src.once('end', endFn);
20644
20645 dest.on('unpipe', onunpipe);
20646 function onunpipe(readable) {
20647 debug('onunpipe');
20648 if (readable === src) {
20649 cleanup();
20650 }
20651 }
20652
20653 function onend() {
20654 debug('onend');
20655 dest.end();
20656 }
20657
20658 // when the dest drains, it reduces the awaitDrain counter
20659 // on the source. This would be more elegant with a .once()
20660 // handler in flow(), but adding and removing repeatedly is
20661 // too slow.
20662 var ondrain = pipeOnDrain(src);
20663 dest.on('drain', ondrain);
20664
20665 function cleanup() {
20666 debug('cleanup');
20667 // cleanup event handlers once the pipe is broken
20668 dest.removeListener('close', onclose);
20669 dest.removeListener('finish', onfinish);
20670 dest.removeListener('drain', ondrain);
20671 dest.removeListener('error', onerror);
20672 dest.removeListener('unpipe', onunpipe);
20673 src.removeListener('end', onend);
20674 src.removeListener('end', cleanup);
20675 src.removeListener('data', ondata);
20676
20677 // if the reader is waiting for a drain event from this
20678 // specific writer, then it would cause it to never start
20679 // flowing again.
20680 // So, if this is awaiting a drain, then we just call it now.
20681 // If we don't know, then assume that we are waiting for one.
20682 if (state.awaitDrain &&
20683 (!dest._writableState || dest._writableState.needDrain))
20684 ondrain();
20685 }
20686
20687 src.on('data', ondata);
20688 function ondata(chunk) {
20689 debug('ondata');
20690 var ret = dest.write(chunk);
20691 if (false === ret) {
20692 debug('false write response, pause',
20693 src._readableState.awaitDrain);
20694 src._readableState.awaitDrain++;
20695 src.pause();
20696 }
20697 }
20698
20699 // if the dest has an error, then stop piping into it.
20700 // however, don't suppress the throwing behavior for this.
20701 function onerror(er) {
20702 debug('onerror', er);
20703 unpipe();
20704 dest.removeListener('error', onerror);
20705 if (EE.listenerCount(dest, 'error') === 0)
20706 dest.emit('error', er);
20707 }
20708 // This is a brutally ugly hack to make sure that our error handler
20709 // is attached before any userland ones. NEVER DO THIS.
20710 if (!dest._events || !dest._events.error)
20711 dest.on('error', onerror);
20712 else if (isArray(dest._events.error))
20713 dest._events.error.unshift(onerror);
20714 else
20715 dest._events.error = [onerror, dest._events.error];
20716
20717
20718
20719 // Both close and finish should trigger unpipe, but only once.
20720 function onclose() {
20721 dest.removeListener('finish', onfinish);
20722 unpipe();
20723 }
20724 dest.once('close', onclose);
20725 function onfinish() {
20726 debug('onfinish');
20727 dest.removeListener('close', onclose);
20728 unpipe();
20729 }
20730 dest.once('finish', onfinish);
20731
20732 function unpipe() {
20733 debug('unpipe');
20734 src.unpipe(dest);
20735 }
20736
20737 // tell the dest that it's being piped to
20738 dest.emit('pipe', src);
20739
20740 // start the flow if it hasn't been started already.
20741 if (!state.flowing) {
20742 debug('pipe resume');
20743 src.resume();
20744 }
20745
20746 return dest;
20747};
20748
20749function pipeOnDrain(src) {
20750 return function() {
20751 var state = src._readableState;
20752 debug('pipeOnDrain', state.awaitDrain);
20753 if (state.awaitDrain)
20754 state.awaitDrain--;
20755 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
20756 state.flowing = true;
20757 flow(src);
20758 }
20759 };
20760}
20761
20762
20763Readable.prototype.unpipe = function(dest) {
20764 var state = this._readableState;
20765
20766 // if we're not piping anywhere, then do nothing.
20767 if (state.pipesCount === 0)
20768 return this;
20769
20770 // just one destination. most common case.
20771 if (state.pipesCount === 1) {
20772 // passed in one, but it's not the right one.
20773 if (dest && dest !== state.pipes)
20774 return this;
20775
20776 if (!dest)
20777 dest = state.pipes;
20778
20779 // got a match.
20780 state.pipes = null;
20781 state.pipesCount = 0;
20782 state.flowing = false;
20783 if (dest)
20784 dest.emit('unpipe', this);
20785 return this;
20786 }
20787
20788 // slow case. multiple pipe destinations.
20789
20790 if (!dest) {
20791 // remove all.
20792 var dests = state.pipes;
20793 var len = state.pipesCount;
20794 state.pipes = null;
20795 state.pipesCount = 0;
20796 state.flowing = false;
20797
20798 for (var i = 0; i < len; i++)
20799 dests[i].emit('unpipe', this);
20800 return this;
20801 }
20802
20803 // try to find the right one.
20804 var i = indexOf(state.pipes, dest);
20805 if (i === -1)
20806 return this;
20807
20808 state.pipes.splice(i, 1);
20809 state.pipesCount -= 1;
20810 if (state.pipesCount === 1)
20811 state.pipes = state.pipes[0];
20812
20813 dest.emit('unpipe', this);
20814
20815 return this;
20816};
20817
20818// set up data events if they are asked for
20819// Ensure readable listeners eventually get something
20820Readable.prototype.on = function(ev, fn) {
20821 var res = Stream.prototype.on.call(this, ev, fn);
20822
20823 // If listening to data, and it has not explicitly been paused,
20824 // then call resume to start the flow of data on the next tick.
20825 if (ev === 'data' && false !== this._readableState.flowing) {
20826 this.resume();
20827 }
20828
20829 if (ev === 'readable' && this.readable) {
20830 var state = this._readableState;
20831 if (!state.readableListening) {
20832 state.readableListening = true;
20833 state.emittedReadable = false;
20834 state.needReadable = true;
20835 if (!state.reading) {
20836 var self = this;
20837 process.nextTick(function() {
20838 debug('readable nexttick read 0');
20839 self.read(0);
20840 });
20841 } else if (state.length) {
20842 emitReadable(this, state);
20843 }
20844 }
20845 }
20846
20847 return res;
20848};
20849Readable.prototype.addListener = Readable.prototype.on;
20850
20851// pause() and resume() are remnants of the legacy readable stream API
20852// If the user uses them, then switch into old mode.
20853Readable.prototype.resume = function() {
20854 var state = this._readableState;
20855 if (!state.flowing) {
20856 debug('resume');
20857 state.flowing = true;
20858 if (!state.reading) {
20859 debug('resume read 0');
20860 this.read(0);
20861 }
20862 resume(this, state);
20863 }
20864 return this;
20865};
20866
20867function resume(stream, state) {
20868 if (!state.resumeScheduled) {
20869 state.resumeScheduled = true;
20870 process.nextTick(function() {
20871 resume_(stream, state);
20872 });
20873 }
20874}
20875
20876function resume_(stream, state) {
20877 state.resumeScheduled = false;
20878 stream.emit('resume');
20879 flow(stream);
20880 if (state.flowing && !state.reading)
20881 stream.read(0);
20882}
20883
20884Readable.prototype.pause = function() {
20885 debug('call pause flowing=%j', this._readableState.flowing);
20886 if (false !== this._readableState.flowing) {
20887 debug('pause');
20888 this._readableState.flowing = false;
20889 this.emit('pause');
20890 }
20891 return this;
20892};
20893
20894function flow(stream) {
20895 var state = stream._readableState;
20896 debug('flow', state.flowing);
20897 if (state.flowing) {
20898 do {
20899 var chunk = stream.read();
20900 } while (null !== chunk && state.flowing);
20901 }
20902}
20903
20904// wrap an old-style stream as the async data source.
20905// This is *not* part of the readable stream interface.
20906// It is an ugly unfortunate mess of history.
20907Readable.prototype.wrap = function(stream) {
20908 var state = this._readableState;
20909 var paused = false;
20910
20911 var self = this;
20912 stream.on('end', function() {
20913 debug('wrapped end');
20914 if (state.decoder && !state.ended) {
20915 var chunk = state.decoder.end();
20916 if (chunk && chunk.length)
20917 self.push(chunk);
20918 }
20919
20920 self.push(null);
20921 });
20922
20923 stream.on('data', function(chunk) {
20924 debug('wrapped data');
20925 if (state.decoder)
20926 chunk = state.decoder.write(chunk);
20927 if (!chunk || !state.objectMode && !chunk.length)
20928 return;
20929
20930 var ret = self.push(chunk);
20931 if (!ret) {
20932 paused = true;
20933 stream.pause();
20934 }
20935 });
20936
20937 // proxy all the other methods.
20938 // important when wrapping filters and duplexes.
20939 for (var i in stream) {
20940 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
20941 this[i] = function(method) { return function() {
20942 return stream[method].apply(stream, arguments);
20943 }}(i);
20944 }
20945 }
20946
20947 // proxy certain important events.
20948 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
20949 forEach(events, function(ev) {
20950 stream.on(ev, self.emit.bind(self, ev));
20951 });
20952
20953 // when we try to consume some more bytes, simply unpause the
20954 // underlying stream.
20955 self._read = function(n) {
20956 debug('wrapped _read', n);
20957 if (paused) {
20958 paused = false;
20959 stream.resume();
20960 }
20961 };
20962
20963 return self;
20964};
20965
20966
20967
20968// exposed for testing purposes only.
20969Readable._fromList = fromList;
20970
20971// Pluck off n bytes from an array of buffers.
20972// Length is the combined lengths of all the buffers in the list.
20973function fromList(n, state) {
20974 var list = state.buffer;
20975 var length = state.length;
20976 var stringMode = !!state.decoder;
20977 var objectMode = !!state.objectMode;
20978 var ret;
20979
20980 // nothing in the list, definitely empty.
20981 if (list.length === 0)
20982 return null;
20983
20984 if (length === 0)
20985 ret = null;
20986 else if (objectMode)
20987 ret = list.shift();
20988 else if (!n || n >= length) {
20989 // read it all, truncate the array.
20990 if (stringMode)
20991 ret = list.join('');
20992 else
20993 ret = Buffer.concat(list, length);
20994 list.length = 0;
20995 } else {
20996 // read just some of it.
20997 if (n < list[0].length) {
20998 // just take a part of the first list item.
20999 // slice is the same for buffers and strings.
21000 var buf = list[0];
21001 ret = buf.slice(0, n);
21002 list[0] = buf.slice(n);
21003 } else if (n === list[0].length) {
21004 // first list is a perfect match
21005 ret = list.shift();
21006 } else {
21007 // complex case.
21008 // we have enough to cover it, but it spans past the first buffer.
21009 if (stringMode)
21010 ret = '';
21011 else
21012 ret = new Buffer(n);
21013
21014 var c = 0;
21015 for (var i = 0, l = list.length; i < l && c < n; i++) {
21016 var buf = list[0];
21017 var cpy = Math.min(n - c, buf.length);
21018
21019 if (stringMode)
21020 ret += buf.slice(0, cpy);
21021 else
21022 buf.copy(ret, c, 0, cpy);
21023
21024 if (cpy < buf.length)
21025 list[0] = buf.slice(cpy);
21026 else
21027 list.shift();
21028
21029 c += cpy;
21030 }
21031 }
21032 }
21033
21034 return ret;
21035}
21036
21037function endReadable(stream) {
21038 var state = stream._readableState;
21039
21040 // If we get here before consuming all the bytes, then that is a
21041 // bug in node. Should never happen.
21042 if (state.length > 0)
21043 throw new Error('endReadable called on non-empty stream');
21044
21045 if (!state.endEmitted) {
21046 state.ended = true;
21047 process.nextTick(function() {
21048 // Check that we didn't get one last unshift.
21049 if (!state.endEmitted && state.length === 0) {
21050 state.endEmitted = true;
21051 stream.readable = false;
21052 stream.emit('end');
21053 }
21054 });
21055 }
21056}
21057
21058function forEach (xs, f) {
21059 for (var i = 0, l = xs.length; i < l; i++) {
21060 f(xs[i], i);
21061 }
21062}
21063
21064function indexOf (xs, x) {
21065 for (var i = 0, l = xs.length; i < l; i++) {
21066 if (xs[i] === x) return i;
21067 }
21068 return -1;
21069}
21070}, {"isarray":116,"buffer":29,"events":3,"stream":52,"core-util-is":112,"inherits":113,"util":23,"./_stream_duplex":114,"string_decoder/":62}],116: [function (exports, require, module, global) {module.exports = Array.isArray || function (arr) {
21071 return Object.prototype.toString.call(arr) == '[object Array]';
21072};
21073}, {}],117: [function (exports, require, module, global) {exports = module.exports = require('./lib/_stream_readable.js');
21074exports.Stream = require('stream');
21075exports.Readable = exports;
21076exports.Writable = require('./lib/_stream_writable.js');
21077exports.Duplex = require('./lib/_stream_duplex.js');
21078exports.Transform = require('./lib/_stream_transform.js');
21079exports.PassThrough = require('./lib/_stream_passthrough.js');
21080}, {"./lib/_stream_readable.js":115,"stream":52,"./lib/_stream_writable.js":111,"./lib/_stream_duplex.js":114,"./lib/_stream_transform.js":118,"./lib/_stream_passthrough.js":119}],118: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
21081//
21082// Permission is hereby granted, free of charge, to any person obtaining a
21083// copy of this software and associated documentation files (the
21084// "Software"), to deal in the Software without restriction, including
21085// without limitation the rights to use, copy, modify, merge, publish,
21086// distribute, sublicense, and/or sell copies of the Software, and to permit
21087// persons to whom the Software is furnished to do so, subject to the
21088// following conditions:
21089//
21090// The above copyright notice and this permission notice shall be included
21091// in all copies or substantial portions of the Software.
21092//
21093// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21094// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21095// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21096// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21097// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21098// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21099// USE OR OTHER DEALINGS IN THE SOFTWARE.
21100
21101
21102// a transform stream is a readable/writable stream where you do
21103// something with the data. Sometimes it's called a "filter",
21104// but that's not a great name for it, since that implies a thing where
21105// some bits pass through, and others are simply ignored. (That would
21106// be a valid example of a transform, of course.)
21107//
21108// While the output is causally related to the input, it's not a
21109// necessarily symmetric or synchronous transformation. For example,
21110// a zlib stream might take multiple plain-text writes(), and then
21111// emit a single compressed chunk some time in the future.
21112//
21113// Here's how this works:
21114//
21115// The Transform stream has all the aspects of the readable and writable
21116// stream classes. When you write(chunk), that calls _write(chunk,cb)
21117// internally, and returns false if there's a lot of pending writes
21118// buffered up. When you call read(), that calls _read(n) until
21119// there's enough pending readable data buffered up.
21120//
21121// In a transform stream, the written data is placed in a buffer. When
21122// _read(n) is called, it transforms the queued up data, calling the
21123// buffered _write cb's as it consumes chunks. If consuming a single
21124// written chunk would result in multiple output chunks, then the first
21125// outputted bit calls the readcb, and subsequent chunks just go into
21126// the read buffer, and will cause it to emit 'readable' if necessary.
21127//
21128// This way, back-pressure is actually determined by the reading side,
21129// since _read has to be called to start processing a new chunk. However,
21130// a pathological inflate type of transform can cause excessive buffering
21131// here. For example, imagine a stream where every byte of input is
21132// interpreted as an integer from 0-255, and then results in that many
21133// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
21134// 1kb of data being output. In this case, you could write a very small
21135// amount of input, and end up with a very large amount of output. In
21136// such a pathological inflating mechanism, there'd be no way to tell
21137// the system to stop doing the transform. A single 4MB write could
21138// cause the system to run out of memory.
21139//
21140// However, even in such a pathological case, only a single written chunk
21141// would be consumed, and then the rest would wait (un-transformed) until
21142// the results of the previous transformed chunk were consumed.
21143
21144module.exports = Transform;
21145
21146var Duplex = require('./_stream_duplex');
21147
21148/*<replacement>*/
21149var util = require('core-util-is');
21150util.inherits = require('inherits');
21151/*</replacement>*/
21152
21153util.inherits(Transform, Duplex);
21154
21155
21156function TransformState(options, stream) {
21157 this.afterTransform = function(er, data) {
21158 return afterTransform(stream, er, data);
21159 };
21160
21161 this.needTransform = false;
21162 this.transforming = false;
21163 this.writecb = null;
21164 this.writechunk = null;
21165}
21166
21167function afterTransform(stream, er, data) {
21168 var ts = stream._transformState;
21169 ts.transforming = false;
21170
21171 var cb = ts.writecb;
21172
21173 if (!cb)
21174 return stream.emit('error', new Error('no writecb in Transform class'));
21175
21176 ts.writechunk = null;
21177 ts.writecb = null;
21178
21179 if (!util.isNullOrUndefined(data))
21180 stream.push(data);
21181
21182 if (cb)
21183 cb(er);
21184
21185 var rs = stream._readableState;
21186 rs.reading = false;
21187 if (rs.needReadable || rs.length < rs.highWaterMark) {
21188 stream._read(rs.highWaterMark);
21189 }
21190}
21191
21192
21193function Transform(options) {
21194 if (!(this instanceof Transform))
21195 return new Transform(options);
21196
21197 Duplex.call(this, options);
21198
21199 this._transformState = new TransformState(options, this);
21200
21201 // when the writable side finishes, then flush out anything remaining.
21202 var stream = this;
21203
21204 // start out asking for a readable event once data is transformed.
21205 this._readableState.needReadable = true;
21206
21207 // we have implemented the _read method, and done the other things
21208 // that Readable wants before the first _read call, so unset the
21209 // sync guard flag.
21210 this._readableState.sync = false;
21211
21212 this.once('prefinish', function() {
21213 if (util.isFunction(this._flush))
21214 this._flush(function(er) {
21215 done(stream, er);
21216 });
21217 else
21218 done(stream);
21219 });
21220}
21221
21222Transform.prototype.push = function(chunk, encoding) {
21223 this._transformState.needTransform = false;
21224 return Duplex.prototype.push.call(this, chunk, encoding);
21225};
21226
21227// This is the part where you do stuff!
21228// override this function in implementation classes.
21229// 'chunk' is an input chunk.
21230//
21231// Call `push(newChunk)` to pass along transformed output
21232// to the readable side. You may call 'push' zero or more times.
21233//
21234// Call `cb(err)` when you are done with this chunk. If you pass
21235// an error, then that'll put the hurt on the whole operation. If you
21236// never call cb(), then you'll never get another chunk.
21237Transform.prototype._transform = function(chunk, encoding, cb) {
21238 throw new Error('not implemented');
21239};
21240
21241Transform.prototype._write = function(chunk, encoding, cb) {
21242 var ts = this._transformState;
21243 ts.writecb = cb;
21244 ts.writechunk = chunk;
21245 ts.writeencoding = encoding;
21246 if (!ts.transforming) {
21247 var rs = this._readableState;
21248 if (ts.needTransform ||
21249 rs.needReadable ||
21250 rs.length < rs.highWaterMark)
21251 this._read(rs.highWaterMark);
21252 }
21253};
21254
21255// Doesn't matter what the args are here.
21256// _transform does all the work.
21257// That we got here means that the readable side wants more data.
21258Transform.prototype._read = function(n) {
21259 var ts = this._transformState;
21260
21261 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
21262 ts.transforming = true;
21263 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
21264 } else {
21265 // mark that we need a transform, so that any data that comes in
21266 // will get processed, now that we've asked for it.
21267 ts.needTransform = true;
21268 }
21269};
21270
21271
21272function done(stream, er) {
21273 if (er)
21274 return stream.emit('error', er);
21275
21276 // if there's nothing in the write buffer, then that means
21277 // that nothing more will ever be provided
21278 var ws = stream._writableState;
21279 var ts = stream._transformState;
21280
21281 if (ws.length)
21282 throw new Error('calling transform done when ws.length != 0');
21283
21284 if (ts.transforming)
21285 throw new Error('calling transform done when still transforming');
21286
21287 return stream.push(null);
21288}
21289}, {"./_stream_duplex":114,"core-util-is":112,"inherits":113}],119: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
21290//
21291// Permission is hereby granted, free of charge, to any person obtaining a
21292// copy of this software and associated documentation files (the
21293// "Software"), to deal in the Software without restriction, including
21294// without limitation the rights to use, copy, modify, merge, publish,
21295// distribute, sublicense, and/or sell copies of the Software, and to permit
21296// persons to whom the Software is furnished to do so, subject to the
21297// following conditions:
21298//
21299// The above copyright notice and this permission notice shall be included
21300// in all copies or substantial portions of the Software.
21301//
21302// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21303// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21304// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
21305// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21306// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21307// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21308// USE OR OTHER DEALINGS IN THE SOFTWARE.
21309
21310// a passthrough stream.
21311// basically just the most minimal sort of Transform stream.
21312// Every written chunk gets output as-is.
21313
21314module.exports = PassThrough;
21315
21316var Transform = require('./_stream_transform');
21317
21318/*<replacement>*/
21319var util = require('core-util-is');
21320util.inherits = require('inherits');
21321/*</replacement>*/
21322
21323util.inherits(PassThrough, Transform);
21324
21325function PassThrough(options) {
21326 if (!(this instanceof PassThrough))
21327 return new PassThrough(options);
21328
21329 Transform.call(this, options);
21330}
21331
21332PassThrough.prototype._transform = function(chunk, encoding, cb) {
21333 cb(null, chunk);
21334};
21335}, {"./_stream_transform":118,"core-util-is":112,"inherits":113}],120: [function (exports, require, module, global) {var fixRange = require('level-fix-range')
21336//get the first/last record in a range
21337
21338exports = module.exports = peek
21339exports.first = first
21340exports.last = last
21341
21342function once(emitter, events, listener) {
21343 var remove = []
21344 events.forEach(function (e) {
21345 function onEvent (arg) {
21346 if(listener(e, arg) === false) return
21347 remove.forEach(function (r) {
21348 r()
21349 })
21350 }
21351 emitter.on(e, onEvent)
21352 remove.push(function () {
21353 emitter.removeListener(e, onEvent)
21354 })
21355 })
21356 return emitter
21357}
21358
21359
21360function peek (db, opts, cb) {
21361 opts.limit = opts.reverse ? 2 : 1
21362 var stream = once(db.createReadStream(opts),
21363 ['data', 'error', 'end'],
21364 function (event, data) {
21365 if(opts.reverse && data && opts.start
21366 && (data.key.toString() > opts.start))
21367 return false
21368 if(event == 'error') cb(data)
21369 else if(event == 'end') cb(new Error('range not found'), null, null)
21370 else cb(null, data.key, data.value)
21371 })
21372}
21373
21374function first (db, opts, cb) {
21375 if (!cb) {
21376 cb = opts;
21377 opts = {};
21378 }
21379 opts.reverse = false
21380 return peek(db, fixRange(opts), cb)
21381}
21382
21383//SO, this is pretty horrible,
21384//but it's works around an issue here
21385//https://github.com/rvagg/node-levelup/issues/110
21386
21387function last (db, opts, cb) {
21388 if (!cb) {
21389 cb = opts;
21390 opts = {};
21391 }
21392 var start = opts.start
21393 opts.reverse = true
21394 return peek(db, fixRange(opts), function (err, key, value) {
21395 if(err) {
21396 var _start = opts.start
21397 opts.start = null
21398 peek (db, opts, function (_, key, value) {
21399 if(!key) return cb(err, null, null)
21400 var _key = key.toString()
21401 if(_key <= _start && (!opts.end || _key >= opts.end))
21402 cb(_, key, value)
21403 else cb(err, null, null)
21404 })
21405 }
21406 else cb(err, key, value)
21407 })
21408}
21409
21410}, {"level-fix-range":121}],121: [function (exports, require, module, global) {
21411module.exports =
21412function fixRange(opts) {
21413 var reverse = opts.reverse
21414 var end = opts.end
21415 var start = opts.start
21416
21417 var range = [start, end]
21418 if(start != null && end != null)
21419 range.sort()
21420 if(reverse)
21421 range = range.reverse()
21422
21423 opts.start = range[0]
21424 opts.end = range[1]
21425 return opts
21426}
21427
21428}, {}],122: [function (exports, require, module, global) {var wrappy = require('wrappy')
21429module.exports = wrappy(once)
21430
21431once.proto = once(function () {
21432 Object.defineProperty(Function.prototype, 'once', {
21433 value: function () {
21434 return once(this)
21435 },
21436 configurable: true
21437 })
21438})
21439
21440function once (fn) {
21441 var f = function () {
21442 if (f.called) return f.value
21443 f.called = true
21444 return f.value = fn.apply(this, arguments)
21445 }
21446 f.called = false
21447 return f
21448}
21449}, {"wrappy":123}],123: [function (exports, require, module, global) {// Returns a wrapper function that returns a wrapped callback
21450// The wrapper function should do some stuff, and return a
21451// presumably different callback function.
21452// This makes sure that own properties are retained, so that
21453// decorations and such are not lost along the way.
21454module.exports = wrappy
21455function wrappy (fn, cb) {
21456 if (fn && cb) return wrappy(fn)(cb)
21457
21458 if (typeof fn !== 'function')
21459 throw new TypeError('need wrapper function')
21460
21461 Object.keys(fn).forEach(function (k) {
21462 wrapper[k] = fn[k]
21463 })
21464
21465 return wrapper
21466
21467 function wrapper() {
21468 var args = new Array(arguments.length)
21469 for (var i = 0; i < args.length; i++) {
21470 args[i] = arguments[i]
21471 }
21472 var ret = fn.apply(this, args)
21473 var cb = args[args.length-1]
21474 if (typeof ret === 'function' && ret !== cb) {
21475 Object.keys(cb).forEach(function (k) {
21476 ret[k] = cb[k]
21477 })
21478 }
21479 return ret
21480 }
21481}
21482}, {}],124: [function (exports, require, module, global) {var errno = require('errno');
21483
21484Object.keys(errno.code).forEach(function(code) {
21485 var e = errno.code[code];
21486
21487 exports[code] = function(path) {
21488 var err = new Error(code+', '+e.description+(path ? ' \''+path+'\'' : ''));
21489 err.errno = e.errno;
21490 err.code = code;
21491 err.path = path;
21492 return err;
21493 };
21494});}, {"errno":125}],125: [function (exports, require, module, global) {var all = module.exports.all = [
21495 {
21496 errno: -2,
21497 code: 'ENOENT',
21498 description: 'no such file or directory'
21499 },
21500 {
21501 errno: -1,
21502 code: 'UNKNOWN',
21503 description: 'unknown error'
21504 },
21505 {
21506 errno: 0,
21507 code: 'OK',
21508 description: 'success'
21509 },
21510 {
21511 errno: 1,
21512 code: 'EOF',
21513 description: 'end of file'
21514 },
21515 {
21516 errno: 2,
21517 code: 'EADDRINFO',
21518 description: 'getaddrinfo error'
21519 },
21520 {
21521 errno: 3,
21522 code: 'EACCES',
21523 description: 'permission denied'
21524 },
21525 {
21526 errno: 4,
21527 code: 'EAGAIN',
21528 description: 'resource temporarily unavailable'
21529 },
21530 {
21531 errno: 5,
21532 code: 'EADDRINUSE',
21533 description: 'address already in use'
21534 },
21535 {
21536 errno: 6,
21537 code: 'EADDRNOTAVAIL',
21538 description: 'address not available'
21539 },
21540 {
21541 errno: 7,
21542 code: 'EAFNOSUPPORT',
21543 description: 'address family not supported'
21544 },
21545 {
21546 errno: 8,
21547 code: 'EALREADY',
21548 description: 'connection already in progress'
21549 },
21550 {
21551 errno: 9,
21552 code: 'EBADF',
21553 description: 'bad file descriptor'
21554 },
21555 {
21556 errno: 10,
21557 code: 'EBUSY',
21558 description: 'resource busy or locked'
21559 },
21560 {
21561 errno: 11,
21562 code: 'ECONNABORTED',
21563 description: 'software caused connection abort'
21564 },
21565 {
21566 errno: 12,
21567 code: 'ECONNREFUSED',
21568 description: 'connection refused'
21569 },
21570 {
21571 errno: 13,
21572 code: 'ECONNRESET',
21573 description: 'connection reset by peer'
21574 },
21575 {
21576 errno: 14,
21577 code: 'EDESTADDRREQ',
21578 description: 'destination address required'
21579 },
21580 {
21581 errno: 15,
21582 code: 'EFAULT',
21583 description: 'bad address in system call argument'
21584 },
21585 {
21586 errno: 16,
21587 code: 'EHOSTUNREACH',
21588 description: 'host is unreachable'
21589 },
21590 {
21591 errno: 17,
21592 code: 'EINTR',
21593 description: 'interrupted system call'
21594 },
21595 {
21596 errno: 18,
21597 code: 'EINVAL',
21598 description: 'invalid argument'
21599 },
21600 {
21601 errno: 19,
21602 code: 'EISCONN',
21603 description: 'socket is already connected'
21604 },
21605 {
21606 errno: 20,
21607 code: 'EMFILE',
21608 description: 'too many open files'
21609 },
21610 {
21611 errno: 21,
21612 code: 'EMSGSIZE',
21613 description: 'message too long'
21614 },
21615 {
21616 errno: 22,
21617 code: 'ENETDOWN',
21618 description: 'network is down'
21619 },
21620 {
21621 errno: 23,
21622 code: 'ENETUNREACH',
21623 description: 'network is unreachable'
21624 },
21625 {
21626 errno: 24,
21627 code: 'ENFILE',
21628 description: 'file table overflow'
21629 },
21630 {
21631 errno: 25,
21632 code: 'ENOBUFS',
21633 description: 'no buffer space available'
21634 },
21635 {
21636 errno: 26,
21637 code: 'ENOMEM',
21638 description: 'not enough memory'
21639 },
21640 {
21641 errno: 27,
21642 code: 'ENOTDIR',
21643 description: 'not a directory'
21644 },
21645 {
21646 errno: 28,
21647 code: 'EISDIR',
21648 description: 'illegal operation on a directory'
21649 },
21650 {
21651 errno: 29,
21652 code: 'ENONET',
21653 description: 'machine is not on the network'
21654 },
21655 {
21656 errno: 31,
21657 code: 'ENOTCONN',
21658 description: 'socket is not connected'
21659 },
21660 {
21661 errno: 32,
21662 code: 'ENOTSOCK',
21663 description: 'socket operation on non-socket'
21664 },
21665 {
21666 errno: 33,
21667 code: 'ENOTSUP',
21668 description: 'operation not supported on socket'
21669 },
21670 {
21671 errno: 34,
21672 code: 'ENOENT',
21673 description: 'no such file or directory'
21674 },
21675 {
21676 errno: 35,
21677 code: 'ENOSYS',
21678 description: 'function not implemented'
21679 },
21680 {
21681 errno: 36,
21682 code: 'EPIPE',
21683 description: 'broken pipe'
21684 },
21685 {
21686 errno: 37,
21687 code: 'EPROTO',
21688 description: 'protocol error'
21689 },
21690 {
21691 errno: 38,
21692 code: 'EPROTONOSUPPORT',
21693 description: 'protocol not supported'
21694 },
21695 {
21696 errno: 39,
21697 code: 'EPROTOTYPE',
21698 description: 'protocol wrong type for socket'
21699 },
21700 {
21701 errno: 40,
21702 code: 'ETIMEDOUT',
21703 description: 'connection timed out'
21704 },
21705 {
21706 errno: 41,
21707 code: 'ECHARSET',
21708 description: 'invalid Unicode character'
21709 },
21710 {
21711 errno: 42,
21712 code: 'EAIFAMNOSUPPORT',
21713 description: 'address family for hostname not supported'
21714 },
21715 {
21716 errno: 44,
21717 code: 'EAISERVICE',
21718 description: 'servname not supported for ai_socktype'
21719 },
21720 {
21721 errno: 45,
21722 code: 'EAISOCKTYPE',
21723 description: 'ai_socktype not supported'
21724 },
21725 {
21726 errno: 46,
21727 code: 'ESHUTDOWN',
21728 description: 'cannot send after transport endpoint shutdown'
21729 },
21730 {
21731 errno: 47,
21732 code: 'EEXIST',
21733 description: 'file already exists'
21734 },
21735 {
21736 errno: 48,
21737 code: 'ESRCH',
21738 description: 'no such process'
21739 },
21740 {
21741 errno: 49,
21742 code: 'ENAMETOOLONG',
21743 description: 'name too long'
21744 },
21745 {
21746 errno: 50,
21747 code: 'EPERM',
21748 description: 'operation not permitted'
21749 },
21750 {
21751 errno: 51,
21752 code: 'ELOOP',
21753 description: 'too many symbolic links encountered'
21754 },
21755 {
21756 errno: 52,
21757 code: 'EXDEV',
21758 description: 'cross-device link not permitted'
21759 },
21760 {
21761 errno: 53,
21762 code: 'ENOTEMPTY',
21763 description: 'directory not empty'
21764 },
21765 {
21766 errno: 54,
21767 code: 'ENOSPC',
21768 description: 'no space left on device'
21769 },
21770 {
21771 errno: 55,
21772 code: 'EIO',
21773 description: 'i/o error'
21774 },
21775 {
21776 errno: 56,
21777 code: 'EROFS',
21778 description: 'read-only file system'
21779 },
21780 {
21781 errno: 57,
21782 code: 'ENODEV',
21783 description: 'no such device'
21784 },
21785 {
21786 errno: 58,
21787 code: 'ESPIPE',
21788 description: 'invalid seek'
21789 },
21790 {
21791 errno: 59,
21792 code: 'ECANCELED',
21793 description: 'operation canceled'
21794 }
21795]
21796
21797module.exports.errno = {}
21798module.exports.code = {}
21799
21800all.forEach(function (error) {
21801 module.exports.errno[error.errno] = error
21802 module.exports.code[error.code] = error
21803})
21804
21805module.exports.custom = require('./custom')(module.exports)
21806module.exports.create = module.exports.custom.createError
21807}, {"./custom":126}],126: [function (exports, require, module, global) {var prr = require('prr')
21808
21809function init (type, message, cause) {
21810 prr(this, {
21811 type : type
21812 , name : type
21813 // can be passed just a 'cause'
21814 , cause : typeof message != 'string' ? message : cause
21815 , message : !!message && typeof message != 'string' ? message.message : message
21816
21817 }, 'ewr')
21818}
21819
21820// generic prototype, not intended to be actually used - helpful for `instanceof`
21821function CustomError (message, cause) {
21822 Error.call(this)
21823 if (Error.captureStackTrace)
21824 Error.captureStackTrace(this, arguments.callee)
21825 init.call(this, 'CustomError', message, cause)
21826}
21827
21828CustomError.prototype = new Error()
21829
21830function createError (errno, type, proto) {
21831 var err = function (message, cause) {
21832 init.call(this, type, message, cause)
21833 //TODO: the specificity here is stupid, errno should be available everywhere
21834 if (type == 'FilesystemError') {
21835 this.code = this.cause.code
21836 this.path = this.cause.path
21837 this.errno = this.cause.errno
21838 this.message =
21839 (errno.errno[this.cause.errno]
21840 ? errno.errno[this.cause.errno].description
21841 : this.cause.message)
21842 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
21843 }
21844 Error.call(this)
21845 if (Error.captureStackTrace)
21846 Error.captureStackTrace(this, arguments.callee)
21847 }
21848 err.prototype = !!proto ? new proto() : new CustomError()
21849 return err
21850}
21851
21852module.exports = function (errno) {
21853 var ce = function (type, proto) {
21854 return createError(errno, type, proto)
21855 }
21856 return {
21857 CustomError : CustomError
21858 , FilesystemError : ce('FilesystemError')
21859 , createError : ce
21860 }
21861}
21862}, {"prr":127}],127: [function (exports, require, module, global) {/*!
21863 * prr
21864 * (c) 2013 Rod Vagg <rod@vagg.org>
21865 * https://github.com/rvagg/prr
21866 * License: MIT
21867 */
21868
21869(function (name, context, definition) {
21870 if (typeof module != 'undefined' && module.exports)
21871 module.exports = definition()
21872 else
21873 context[name] = definition()
21874})('prr', this, function() {
21875
21876 var setProperty = typeof Object.defineProperty == 'function'
21877 ? function (obj, key, options) {
21878 Object.defineProperty(obj, key, options)
21879 return obj
21880 }
21881 : function (obj, key, options) { // < es5
21882 obj[key] = options.value
21883 return obj
21884 }
21885
21886 , makeOptions = function (value, options) {
21887 var oo = typeof options == 'object'
21888 , os = !oo && typeof options == 'string'
21889 , op = function (p) {
21890 return oo
21891 ? !!options[p]
21892 : os
21893 ? options.indexOf(p[0]) > -1
21894 : false
21895 }
21896
21897 return {
21898 enumerable : op('enumerable')
21899 , configurable : op('configurable')
21900 , writable : op('writable')
21901 , value : value
21902 }
21903 }
21904
21905 , prr = function (obj, key, value, options) {
21906 var k
21907
21908 options = makeOptions(value, options)
21909
21910 if (typeof key == 'object') {
21911 for (k in key) {
21912 if (Object.hasOwnProperty.call(key, k)) {
21913 options.value = key[k]
21914 setProperty(obj, k, options)
21915 }
21916 }
21917 return obj
21918 }
21919
21920 return setProperty(obj, key, options)
21921 }
21922
21923 return prr
21924})}, {}],128: [function (exports, require, module, global) {var path = require('path');
21925var once = require('once');
21926var concat = require('concat-stream');
21927var stat = require('./stat');
21928var xtend = require('xtend');
21929var errno = require('./errno');
21930
21931var ROOT = stat({
21932 type: 'directory',
21933 mode: 0777,
21934 size: 4096
21935});
21936
21937var normalize = function(key) {
21938 key = key[0] === '/' ? key : '/' + key;
21939 key = path.normalize(key);
21940 if (key === '/') return key;
21941 return key[key.length-1] === '/' ? key.slice(0, -1) : key;
21942};
21943
21944var prefix = function(key) {
21945 var depth = key.split('/').length.toString(36);
21946 return '0000000000'.slice(depth.length)+depth+key;
21947};
21948
21949module.exports = function(db) {
21950 var that = {};
21951
21952 that.normalize = normalize;
21953
21954 that.get = function(key, cb) {
21955 key = normalize(key);
21956 if (key === '/') return process.nextTick(cb.bind(null, null, ROOT, '/'));
21957 db.get(prefix(key), {valueEncoding:'json'}, function(err, doc) {
21958 if (err && err.notFound) return cb(errno.ENOENT(key), null, key);
21959 if (err) return cb(err, null, key);
21960 cb(null, stat(doc), key);
21961 });
21962 };
21963
21964 that.writable = function(key, cb) {
21965 key = normalize(key);
21966 if (key === '/') return process.nextTick(cb.bind(null, errno.EPERM(key)));
21967 that.follow(path.dirname(key), function(err, parent) {
21968 if (err) return cb(err);
21969 if (!parent.isDirectory()) return cb(errno.ENOTDIR(key));
21970 cb(null, key);
21971 });
21972 };
21973
21974 that.list = function(key, cb) {
21975 key = normalize(key);
21976
21977 var start = prefix(key === '/' ? key : key + '/');
21978 var keys = db.createKeyStream({start: start, end: start+'\xff'});
21979
21980 cb = once(cb);
21981
21982 keys.on('error', cb);
21983 keys.pipe(concat({encoding:'object'}, function(files) {
21984 files = files.map(function(file) {
21985 return file.split('/').pop();
21986 });
21987
21988 cb(null, files);
21989 }));
21990 };
21991
21992 var resolve = function(dir, cb) {
21993 var root = '/';
21994 var parts = dir.split('/').slice(1);
21995
21996 var loop = function() {
21997 that.get(path.join(root, parts.shift()), function(err, doc, key) {
21998 if (err) return cb(err, doc, dir);
21999 root = doc.target || key;
22000 if (!parts.length) return cb(null, doc, key);
22001 loop();
22002 });
22003 };
22004
22005 loop();
22006 };
22007
22008 that.follow = function(key, cb) {
22009 resolve(normalize(key), function loop(err, doc, key) {
22010 if (err) return cb(err, null, key);
22011 if (doc.target) return that.get(doc.target, loop);
22012 cb(null, stat(doc), key);
22013 });
22014 };
22015
22016 that.update = function(key, opts, cb) {
22017 that.get(key, function(err, doc, key) {
22018 if (err) return cb(err);
22019 if (key === '/') return cb(errno.EPERM(key));
22020 that.put(key, xtend(doc, opts), cb);
22021 });
22022 };
22023
22024 that.put = function(key, opts, cb) {
22025 that.writable(key, function(err, key) {
22026 if (err) return cb(err);
22027 db.put(prefix(key), stat(opts), {valueEncoding:'json'}, cb);
22028 });
22029 };
22030
22031 that.del = function(key, cb) {
22032 key = normalize(key);
22033 if (key === '/') return process.nextTick(cb.bind(null, errno.EPERM(key)));
22034 db.del(prefix(key), cb);
22035 };
22036
22037 return that;
22038};}, {"path":8,"once":122,"concat-stream":129,"./stat":142,"xtend":143,"./errno":124}],129: [function (exports, require, module, global) {var Writable = require('readable-stream').Writable
22039var inherits = require('inherits')
22040
22041if (typeof Uint8Array === 'undefined') {
22042 var U8 = require('typedarray').Uint8Array
22043} else {
22044 var U8 = Uint8Array
22045}
22046
22047function ConcatStream(opts, cb) {
22048 if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
22049
22050 if (typeof opts === 'function') {
22051 cb = opts
22052 opts = {}
22053 }
22054 if (!opts) opts = {}
22055
22056 var encoding = opts.encoding
22057 var shouldInferEncoding = false
22058
22059 if (!encoding) {
22060 shouldInferEncoding = true
22061 } else {
22062 encoding = String(encoding).toLowerCase()
22063 if (encoding === 'u8' || encoding === 'uint8') {
22064 encoding = 'uint8array'
22065 }
22066 }
22067
22068 Writable.call(this, { objectMode: true })
22069
22070 this.encoding = encoding
22071 this.shouldInferEncoding = shouldInferEncoding
22072
22073 if (cb) this.on('finish', function () { cb(this.getBody()) })
22074 this.body = []
22075}
22076
22077module.exports = ConcatStream
22078inherits(ConcatStream, Writable)
22079
22080ConcatStream.prototype._write = function(chunk, enc, next) {
22081 this.body.push(chunk)
22082 next()
22083}
22084
22085ConcatStream.prototype.inferEncoding = function (buff) {
22086 var firstBuffer = buff === undefined ? this.body[0] : buff;
22087 if (Buffer.isBuffer(firstBuffer)) return 'buffer'
22088 if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
22089 if (Array.isArray(firstBuffer)) return 'array'
22090 if (typeof firstBuffer === 'string') return 'string'
22091 if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
22092 return 'buffer'
22093}
22094
22095ConcatStream.prototype.getBody = function () {
22096 if (!this.encoding && this.body.length === 0) return []
22097 if (this.shouldInferEncoding) this.encoding = this.inferEncoding()
22098 if (this.encoding === 'array') return arrayConcat(this.body)
22099 if (this.encoding === 'string') return stringConcat(this.body)
22100 if (this.encoding === 'buffer') return bufferConcat(this.body)
22101 if (this.encoding === 'uint8array') return u8Concat(this.body)
22102 return this.body
22103}
22104
22105var isArray = Array.isArray || function (arr) {
22106 return Object.prototype.toString.call(arr) == '[object Array]'
22107}
22108
22109function isArrayish (arr) {
22110 return /Array\]$/.test(Object.prototype.toString.call(arr))
22111}
22112
22113function stringConcat (parts) {
22114 var strings = []
22115 var needsToString = false
22116 for (var i = 0; i < parts.length; i++) {
22117 var p = parts[i]
22118 if (typeof p === 'string') {
22119 strings.push(p)
22120 } else if (Buffer.isBuffer(p)) {
22121 strings.push(p)
22122 } else {
22123 strings.push(Buffer(p))
22124 }
22125 }
22126 if (Buffer.isBuffer(parts[0])) {
22127 strings = Buffer.concat(strings)
22128 strings = strings.toString('utf8')
22129 } else {
22130 strings = strings.join('')
22131 }
22132 return strings
22133}
22134
22135function bufferConcat (parts) {
22136 var bufs = []
22137 for (var i = 0; i < parts.length; i++) {
22138 var p = parts[i]
22139 if (Buffer.isBuffer(p)) {
22140 bufs.push(p)
22141 } else if (typeof p === 'string' || isArrayish(p)
22142 || (p && typeof p.subarray === 'function')) {
22143 bufs.push(Buffer(p))
22144 } else bufs.push(Buffer(String(p)))
22145 }
22146 return Buffer.concat(bufs)
22147}
22148
22149function arrayConcat (parts) {
22150 var res = []
22151 for (var i = 0; i < parts.length; i++) {
22152 res.push.apply(res, parts[i])
22153 }
22154 return res
22155}
22156
22157function u8Concat (parts) {
22158 var len = 0
22159 for (var i = 0; i < parts.length; i++) {
22160 if (typeof parts[i] === 'string') {
22161 parts[i] = Buffer(parts[i])
22162 }
22163 len += parts[i].length
22164 }
22165 var u8 = new U8(len)
22166 for (var i = 0, offset = 0; i < parts.length; i++) {
22167 var part = parts[i]
22168 for (var j = 0; j < part.length; j++) {
22169 u8[offset++] = part[j]
22170 }
22171 }
22172 return u8
22173}
22174}, {"readable-stream":130,"inherits":135,"typedarray":141}],130: [function (exports, require, module, global) {var Stream = (function (){
22175 try {
22176 return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
22177 } catch(_){}
22178}());
22179exports = module.exports = require('./lib/_stream_readable.js');
22180exports.Stream = Stream || exports;
22181exports.Readable = exports;
22182exports.Writable = require('./lib/_stream_writable.js');
22183exports.Duplex = require('./lib/_stream_duplex.js');
22184exports.Transform = require('./lib/_stream_transform.js');
22185exports.PassThrough = require('./lib/_stream_passthrough.js');
22186}, {"./lib/_stream_readable.js":131,"./lib/_stream_writable.js":137,"./lib/_stream_duplex.js":136,"./lib/_stream_transform.js":139,"./lib/_stream_passthrough.js":140}],131: [function (exports, require, module, global) {'use strict';
22187
22188module.exports = Readable;
22189
22190/*<replacement>*/
22191var processNextTick = require('process-nextick-args');
22192/*</replacement>*/
22193
22194
22195/*<replacement>*/
22196var isArray = require('isarray');
22197/*</replacement>*/
22198
22199
22200/*<replacement>*/
22201var Buffer = require('buffer').Buffer;
22202/*</replacement>*/
22203
22204Readable.ReadableState = ReadableState;
22205
22206var EE = require('events');
22207
22208/*<replacement>*/
22209var EElistenerCount = function(emitter, type) {
22210 return emitter.listeners(type).length;
22211};
22212/*</replacement>*/
22213
22214
22215
22216/*<replacement>*/
22217var Stream;
22218(function (){try{
22219 Stream = require('st' + 'ream');
22220}catch(_){}finally{
22221 if (!Stream)
22222 Stream = require('events').EventEmitter;
22223}}())
22224/*</replacement>*/
22225
22226var Buffer = require('buffer').Buffer;
22227
22228/*<replacement>*/
22229var util = require('core-util-is');
22230util.inherits = require('inherits');
22231/*</replacement>*/
22232
22233
22234
22235/*<replacement>*/
22236var debugUtil = require('util');
22237var debug;
22238if (debugUtil && debugUtil.debuglog) {
22239 debug = debugUtil.debuglog('stream');
22240} else {
22241 debug = function () {};
22242}
22243/*</replacement>*/
22244
22245var StringDecoder;
22246
22247util.inherits(Readable, Stream);
22248
22249function ReadableState(options, stream) {
22250 var Duplex = require('./_stream_duplex');
22251
22252 options = options || {};
22253
22254 // object stream flag. Used to make read(n) ignore n and to
22255 // make all the buffer merging and length checks go away
22256 this.objectMode = !!options.objectMode;
22257
22258 if (stream instanceof Duplex)
22259 this.objectMode = this.objectMode || !!options.readableObjectMode;
22260
22261 // the point at which it stops calling _read() to fill the buffer
22262 // Note: 0 is a valid value, means "don't call _read preemptively ever"
22263 var hwm = options.highWaterMark;
22264 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
22265 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
22266
22267 // cast to ints.
22268 this.highWaterMark = ~~this.highWaterMark;
22269
22270 this.buffer = [];
22271 this.length = 0;
22272 this.pipes = null;
22273 this.pipesCount = 0;
22274 this.flowing = null;
22275 this.ended = false;
22276 this.endEmitted = false;
22277 this.reading = false;
22278
22279 // a flag to be able to tell if the onwrite cb is called immediately,
22280 // or on a later tick. We set this to true at first, because any
22281 // actions that shouldn't happen until "later" should generally also
22282 // not happen before the first write call.
22283 this.sync = true;
22284
22285 // whenever we return null, then we set a flag to say
22286 // that we're awaiting a 'readable' event emission.
22287 this.needReadable = false;
22288 this.emittedReadable = false;
22289 this.readableListening = false;
22290
22291 // Crypto is kind of old and crusty. Historically, its default string
22292 // encoding is 'binary' so we have to make this configurable.
22293 // Everything else in the universe uses 'utf8', though.
22294 this.defaultEncoding = options.defaultEncoding || 'utf8';
22295
22296 // when piping, we only care about 'readable' events that happen
22297 // after read()ing all the bytes and not getting any pushback.
22298 this.ranOut = false;
22299
22300 // the number of writers that are awaiting a drain event in .pipe()s
22301 this.awaitDrain = 0;
22302
22303 // if true, a maybeReadMore has been scheduled
22304 this.readingMore = false;
22305
22306 this.decoder = null;
22307 this.encoding = null;
22308 if (options.encoding) {
22309 if (!StringDecoder)
22310 StringDecoder = require('string_decoder/').StringDecoder;
22311 this.decoder = new StringDecoder(options.encoding);
22312 this.encoding = options.encoding;
22313 }
22314}
22315
22316function Readable(options) {
22317 var Duplex = require('./_stream_duplex');
22318
22319 if (!(this instanceof Readable))
22320 return new Readable(options);
22321
22322 this._readableState = new ReadableState(options, this);
22323
22324 // legacy
22325 this.readable = true;
22326
22327 if (options && typeof options.read === 'function')
22328 this._read = options.read;
22329
22330 Stream.call(this);
22331}
22332
22333// Manually shove something into the read() buffer.
22334// This returns true if the highWaterMark has not been hit yet,
22335// similar to how Writable.write() returns true if you should
22336// write() some more.
22337Readable.prototype.push = function(chunk, encoding) {
22338 var state = this._readableState;
22339
22340 if (!state.objectMode && typeof chunk === 'string') {
22341 encoding = encoding || state.defaultEncoding;
22342 if (encoding !== state.encoding) {
22343 chunk = new Buffer(chunk, encoding);
22344 encoding = '';
22345 }
22346 }
22347
22348 return readableAddChunk(this, state, chunk, encoding, false);
22349};
22350
22351// Unshift should *always* be something directly out of read()
22352Readable.prototype.unshift = function(chunk) {
22353 var state = this._readableState;
22354 return readableAddChunk(this, state, chunk, '', true);
22355};
22356
22357Readable.prototype.isPaused = function() {
22358 return this._readableState.flowing === false;
22359};
22360
22361function readableAddChunk(stream, state, chunk, encoding, addToFront) {
22362 var er = chunkInvalid(state, chunk);
22363 if (er) {
22364 stream.emit('error', er);
22365 } else if (chunk === null) {
22366 state.reading = false;
22367 onEofChunk(stream, state);
22368 } else if (state.objectMode || chunk && chunk.length > 0) {
22369 if (state.ended && !addToFront) {
22370 var e = new Error('stream.push() after EOF');
22371 stream.emit('error', e);
22372 } else if (state.endEmitted && addToFront) {
22373 var e = new Error('stream.unshift() after end event');
22374 stream.emit('error', e);
22375 } else {
22376 if (state.decoder && !addToFront && !encoding)
22377 chunk = state.decoder.write(chunk);
22378
22379 if (!addToFront)
22380 state.reading = false;
22381
22382 // if we want the data now, just emit it.
22383 if (state.flowing && state.length === 0 && !state.sync) {
22384 stream.emit('data', chunk);
22385 stream.read(0);
22386 } else {
22387 // update the buffer info.
22388 state.length += state.objectMode ? 1 : chunk.length;
22389 if (addToFront)
22390 state.buffer.unshift(chunk);
22391 else
22392 state.buffer.push(chunk);
22393
22394 if (state.needReadable)
22395 emitReadable(stream);
22396 }
22397
22398 maybeReadMore(stream, state);
22399 }
22400 } else if (!addToFront) {
22401 state.reading = false;
22402 }
22403
22404 return needMoreData(state);
22405}
22406
22407
22408// if it's past the high water mark, we can push in some more.
22409// Also, if we have no data yet, we can stand some
22410// more bytes. This is to work around cases where hwm=0,
22411// such as the repl. Also, if the push() triggered a
22412// readable event, and the user called read(largeNumber) such that
22413// needReadable was set, then we ought to push more, so that another
22414// 'readable' event will be triggered.
22415function needMoreData(state) {
22416 return !state.ended &&
22417 (state.needReadable ||
22418 state.length < state.highWaterMark ||
22419 state.length === 0);
22420}
22421
22422// backwards compatibility.
22423Readable.prototype.setEncoding = function(enc) {
22424 if (!StringDecoder)
22425 StringDecoder = require('string_decoder/').StringDecoder;
22426 this._readableState.decoder = new StringDecoder(enc);
22427 this._readableState.encoding = enc;
22428 return this;
22429};
22430
22431// Don't raise the hwm > 8MB
22432var MAX_HWM = 0x800000;
22433function computeNewHighWaterMark(n) {
22434 if (n >= MAX_HWM) {
22435 n = MAX_HWM;
22436 } else {
22437 // Get the next highest power of 2
22438 n--;
22439 n |= n >>> 1;
22440 n |= n >>> 2;
22441 n |= n >>> 4;
22442 n |= n >>> 8;
22443 n |= n >>> 16;
22444 n++;
22445 }
22446 return n;
22447}
22448
22449function howMuchToRead(n, state) {
22450 if (state.length === 0 && state.ended)
22451 return 0;
22452
22453 if (state.objectMode)
22454 return n === 0 ? 0 : 1;
22455
22456 if (n === null || isNaN(n)) {
22457 // only flow one buffer at a time
22458 if (state.flowing && state.buffer.length)
22459 return state.buffer[0].length;
22460 else
22461 return state.length;
22462 }
22463
22464 if (n <= 0)
22465 return 0;
22466
22467 // If we're asking for more than the target buffer level,
22468 // then raise the water mark. Bump up to the next highest
22469 // power of 2, to prevent increasing it excessively in tiny
22470 // amounts.
22471 if (n > state.highWaterMark)
22472 state.highWaterMark = computeNewHighWaterMark(n);
22473
22474 // don't have that much. return null, unless we've ended.
22475 if (n > state.length) {
22476 if (!state.ended) {
22477 state.needReadable = true;
22478 return 0;
22479 } else {
22480 return state.length;
22481 }
22482 }
22483
22484 return n;
22485}
22486
22487// you can override either this method, or the async _read(n) below.
22488Readable.prototype.read = function(n) {
22489 debug('read', n);
22490 var state = this._readableState;
22491 var nOrig = n;
22492
22493 if (typeof n !== 'number' || n > 0)
22494 state.emittedReadable = false;
22495
22496 // if we're doing read(0) to trigger a readable event, but we
22497 // already have a bunch of data in the buffer, then just trigger
22498 // the 'readable' event and move on.
22499 if (n === 0 &&
22500 state.needReadable &&
22501 (state.length >= state.highWaterMark || state.ended)) {
22502 debug('read: emitReadable', state.length, state.ended);
22503 if (state.length === 0 && state.ended)
22504 endReadable(this);
22505 else
22506 emitReadable(this);
22507 return null;
22508 }
22509
22510 n = howMuchToRead(n, state);
22511
22512 // if we've ended, and we're now clear, then finish it up.
22513 if (n === 0 && state.ended) {
22514 if (state.length === 0)
22515 endReadable(this);
22516 return null;
22517 }
22518
22519 // All the actual chunk generation logic needs to be
22520 // *below* the call to _read. The reason is that in certain
22521 // synthetic stream cases, such as passthrough streams, _read
22522 // may be a completely synchronous operation which may change
22523 // the state of the read buffer, providing enough data when
22524 // before there was *not* enough.
22525 //
22526 // So, the steps are:
22527 // 1. Figure out what the state of things will be after we do
22528 // a read from the buffer.
22529 //
22530 // 2. If that resulting state will trigger a _read, then call _read.
22531 // Note that this may be asynchronous, or synchronous. Yes, it is
22532 // deeply ugly to write APIs this way, but that still doesn't mean
22533 // that the Readable class should behave improperly, as streams are
22534 // designed to be sync/async agnostic.
22535 // Take note if the _read call is sync or async (ie, if the read call
22536 // has returned yet), so that we know whether or not it's safe to emit
22537 // 'readable' etc.
22538 //
22539 // 3. Actually pull the requested chunks out of the buffer and return.
22540
22541 // if we need a readable event, then we need to do some reading.
22542 var doRead = state.needReadable;
22543 debug('need readable', doRead);
22544
22545 // if we currently have less than the highWaterMark, then also read some
22546 if (state.length === 0 || state.length - n < state.highWaterMark) {
22547 doRead = true;
22548 debug('length less than watermark', doRead);
22549 }
22550
22551 // however, if we've ended, then there's no point, and if we're already
22552 // reading, then it's unnecessary.
22553 if (state.ended || state.reading) {
22554 doRead = false;
22555 debug('reading or ended', doRead);
22556 }
22557
22558 if (doRead) {
22559 debug('do read');
22560 state.reading = true;
22561 state.sync = true;
22562 // if the length is currently zero, then we *need* a readable event.
22563 if (state.length === 0)
22564 state.needReadable = true;
22565 // call internal read method
22566 this._read(state.highWaterMark);
22567 state.sync = false;
22568 }
22569
22570 // If _read pushed data synchronously, then `reading` will be false,
22571 // and we need to re-evaluate how much data we can return to the user.
22572 if (doRead && !state.reading)
22573 n = howMuchToRead(nOrig, state);
22574
22575 var ret;
22576 if (n > 0)
22577 ret = fromList(n, state);
22578 else
22579 ret = null;
22580
22581 if (ret === null) {
22582 state.needReadable = true;
22583 n = 0;
22584 }
22585
22586 state.length -= n;
22587
22588 // If we have nothing in the buffer, then we want to know
22589 // as soon as we *do* get something into the buffer.
22590 if (state.length === 0 && !state.ended)
22591 state.needReadable = true;
22592
22593 // If we tried to read() past the EOF, then emit end on the next tick.
22594 if (nOrig !== n && state.ended && state.length === 0)
22595 endReadable(this);
22596
22597 if (ret !== null)
22598 this.emit('data', ret);
22599
22600 return ret;
22601};
22602
22603function chunkInvalid(state, chunk) {
22604 var er = null;
22605 if (!(Buffer.isBuffer(chunk)) &&
22606 typeof chunk !== 'string' &&
22607 chunk !== null &&
22608 chunk !== undefined &&
22609 !state.objectMode) {
22610 er = new TypeError('Invalid non-string/buffer chunk');
22611 }
22612 return er;
22613}
22614
22615
22616function onEofChunk(stream, state) {
22617 if (state.ended) return;
22618 if (state.decoder) {
22619 var chunk = state.decoder.end();
22620 if (chunk && chunk.length) {
22621 state.buffer.push(chunk);
22622 state.length += state.objectMode ? 1 : chunk.length;
22623 }
22624 }
22625 state.ended = true;
22626
22627 // emit 'readable' now to make sure it gets picked up.
22628 emitReadable(stream);
22629}
22630
22631// Don't emit readable right away in sync mode, because this can trigger
22632// another read() call => stack overflow. This way, it might trigger
22633// a nextTick recursion warning, but that's not so bad.
22634function emitReadable(stream) {
22635 var state = stream._readableState;
22636 state.needReadable = false;
22637 if (!state.emittedReadable) {
22638 debug('emitReadable', state.flowing);
22639 state.emittedReadable = true;
22640 if (state.sync)
22641 processNextTick(emitReadable_, stream);
22642 else
22643 emitReadable_(stream);
22644 }
22645}
22646
22647function emitReadable_(stream) {
22648 debug('emit readable');
22649 stream.emit('readable');
22650 flow(stream);
22651}
22652
22653
22654// at this point, the user has presumably seen the 'readable' event,
22655// and called read() to consume some data. that may have triggered
22656// in turn another _read(n) call, in which case reading = true if
22657// it's in progress.
22658// However, if we're not ended, or reading, and the length < hwm,
22659// then go ahead and try to read some more preemptively.
22660function maybeReadMore(stream, state) {
22661 if (!state.readingMore) {
22662 state.readingMore = true;
22663 processNextTick(maybeReadMore_, stream, state);
22664 }
22665}
22666
22667function maybeReadMore_(stream, state) {
22668 var len = state.length;
22669 while (!state.reading && !state.flowing && !state.ended &&
22670 state.length < state.highWaterMark) {
22671 debug('maybeReadMore read 0');
22672 stream.read(0);
22673 if (len === state.length)
22674 // didn't get any data, stop spinning.
22675 break;
22676 else
22677 len = state.length;
22678 }
22679 state.readingMore = false;
22680}
22681
22682// abstract method. to be overridden in specific implementation classes.
22683// call cb(er, data) where data is <= n in length.
22684// for virtual (non-string, non-buffer) streams, "length" is somewhat
22685// arbitrary, and perhaps not very meaningful.
22686Readable.prototype._read = function(n) {
22687 this.emit('error', new Error('not implemented'));
22688};
22689
22690Readable.prototype.pipe = function(dest, pipeOpts) {
22691 var src = this;
22692 var state = this._readableState;
22693
22694 switch (state.pipesCount) {
22695 case 0:
22696 state.pipes = dest;
22697 break;
22698 case 1:
22699 state.pipes = [state.pipes, dest];
22700 break;
22701 default:
22702 state.pipes.push(dest);
22703 break;
22704 }
22705 state.pipesCount += 1;
22706 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
22707
22708 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
22709 dest !== process.stdout &&
22710 dest !== process.stderr;
22711
22712 var endFn = doEnd ? onend : cleanup;
22713 if (state.endEmitted)
22714 processNextTick(endFn);
22715 else
22716 src.once('end', endFn);
22717
22718 dest.on('unpipe', onunpipe);
22719 function onunpipe(readable) {
22720 debug('onunpipe');
22721 if (readable === src) {
22722 cleanup();
22723 }
22724 }
22725
22726 function onend() {
22727 debug('onend');
22728 dest.end();
22729 }
22730
22731 // when the dest drains, it reduces the awaitDrain counter
22732 // on the source. This would be more elegant with a .once()
22733 // handler in flow(), but adding and removing repeatedly is
22734 // too slow.
22735 var ondrain = pipeOnDrain(src);
22736 dest.on('drain', ondrain);
22737
22738 function cleanup() {
22739 debug('cleanup');
22740 // cleanup event handlers once the pipe is broken
22741 dest.removeListener('close', onclose);
22742 dest.removeListener('finish', onfinish);
22743 dest.removeListener('drain', ondrain);
22744 dest.removeListener('error', onerror);
22745 dest.removeListener('unpipe', onunpipe);
22746 src.removeListener('end', onend);
22747 src.removeListener('end', cleanup);
22748 src.removeListener('data', ondata);
22749
22750 // if the reader is waiting for a drain event from this
22751 // specific writer, then it would cause it to never start
22752 // flowing again.
22753 // So, if this is awaiting a drain, then we just call it now.
22754 // If we don't know, then assume that we are waiting for one.
22755 if (state.awaitDrain &&
22756 (!dest._writableState || dest._writableState.needDrain))
22757 ondrain();
22758 }
22759
22760 src.on('data', ondata);
22761 function ondata(chunk) {
22762 debug('ondata');
22763 var ret = dest.write(chunk);
22764 if (false === ret) {
22765 debug('false write response, pause',
22766 src._readableState.awaitDrain);
22767 src._readableState.awaitDrain++;
22768 src.pause();
22769 }
22770 }
22771
22772 // if the dest has an error, then stop piping into it.
22773 // however, don't suppress the throwing behavior for this.
22774 function onerror(er) {
22775 debug('onerror', er);
22776 unpipe();
22777 dest.removeListener('error', onerror);
22778 if (EElistenerCount(dest, 'error') === 0)
22779 dest.emit('error', er);
22780 }
22781 // This is a brutally ugly hack to make sure that our error handler
22782 // is attached before any userland ones. NEVER DO THIS.
22783 if (!dest._events || !dest._events.error)
22784 dest.on('error', onerror);
22785 else if (isArray(dest._events.error))
22786 dest._events.error.unshift(onerror);
22787 else
22788 dest._events.error = [onerror, dest._events.error];
22789
22790
22791 // Both close and finish should trigger unpipe, but only once.
22792 function onclose() {
22793 dest.removeListener('finish', onfinish);
22794 unpipe();
22795 }
22796 dest.once('close', onclose);
22797 function onfinish() {
22798 debug('onfinish');
22799 dest.removeListener('close', onclose);
22800 unpipe();
22801 }
22802 dest.once('finish', onfinish);
22803
22804 function unpipe() {
22805 debug('unpipe');
22806 src.unpipe(dest);
22807 }
22808
22809 // tell the dest that it's being piped to
22810 dest.emit('pipe', src);
22811
22812 // start the flow if it hasn't been started already.
22813 if (!state.flowing) {
22814 debug('pipe resume');
22815 src.resume();
22816 }
22817
22818 return dest;
22819};
22820
22821function pipeOnDrain(src) {
22822 return function() {
22823 var state = src._readableState;
22824 debug('pipeOnDrain', state.awaitDrain);
22825 if (state.awaitDrain)
22826 state.awaitDrain--;
22827 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
22828 state.flowing = true;
22829 flow(src);
22830 }
22831 };
22832}
22833
22834
22835Readable.prototype.unpipe = function(dest) {
22836 var state = this._readableState;
22837
22838 // if we're not piping anywhere, then do nothing.
22839 if (state.pipesCount === 0)
22840 return this;
22841
22842 // just one destination. most common case.
22843 if (state.pipesCount === 1) {
22844 // passed in one, but it's not the right one.
22845 if (dest && dest !== state.pipes)
22846 return this;
22847
22848 if (!dest)
22849 dest = state.pipes;
22850
22851 // got a match.
22852 state.pipes = null;
22853 state.pipesCount = 0;
22854 state.flowing = false;
22855 if (dest)
22856 dest.emit('unpipe', this);
22857 return this;
22858 }
22859
22860 // slow case. multiple pipe destinations.
22861
22862 if (!dest) {
22863 // remove all.
22864 var dests = state.pipes;
22865 var len = state.pipesCount;
22866 state.pipes = null;
22867 state.pipesCount = 0;
22868 state.flowing = false;
22869
22870 for (var i = 0; i < len; i++)
22871 dests[i].emit('unpipe', this);
22872 return this;
22873 }
22874
22875 // try to find the right one.
22876 var i = indexOf(state.pipes, dest);
22877 if (i === -1)
22878 return this;
22879
22880 state.pipes.splice(i, 1);
22881 state.pipesCount -= 1;
22882 if (state.pipesCount === 1)
22883 state.pipes = state.pipes[0];
22884
22885 dest.emit('unpipe', this);
22886
22887 return this;
22888};
22889
22890// set up data events if they are asked for
22891// Ensure readable listeners eventually get something
22892Readable.prototype.on = function(ev, fn) {
22893 var res = Stream.prototype.on.call(this, ev, fn);
22894
22895 // If listening to data, and it has not explicitly been paused,
22896 // then call resume to start the flow of data on the next tick.
22897 if (ev === 'data' && false !== this._readableState.flowing) {
22898 this.resume();
22899 }
22900
22901 if (ev === 'readable' && this.readable) {
22902 var state = this._readableState;
22903 if (!state.readableListening) {
22904 state.readableListening = true;
22905 state.emittedReadable = false;
22906 state.needReadable = true;
22907 if (!state.reading) {
22908 processNextTick(nReadingNextTick, this);
22909 } else if (state.length) {
22910 emitReadable(this, state);
22911 }
22912 }
22913 }
22914
22915 return res;
22916};
22917Readable.prototype.addListener = Readable.prototype.on;
22918
22919function nReadingNextTick(self) {
22920 debug('readable nexttick read 0');
22921 self.read(0);
22922}
22923
22924// pause() and resume() are remnants of the legacy readable stream API
22925// If the user uses them, then switch into old mode.
22926Readable.prototype.resume = function() {
22927 var state = this._readableState;
22928 if (!state.flowing) {
22929 debug('resume');
22930 state.flowing = true;
22931 resume(this, state);
22932 }
22933 return this;
22934};
22935
22936function resume(stream, state) {
22937 if (!state.resumeScheduled) {
22938 state.resumeScheduled = true;
22939 processNextTick(resume_, stream, state);
22940 }
22941}
22942
22943function resume_(stream, state) {
22944 if (!state.reading) {
22945 debug('resume read 0');
22946 stream.read(0);
22947 }
22948
22949 state.resumeScheduled = false;
22950 stream.emit('resume');
22951 flow(stream);
22952 if (state.flowing && !state.reading)
22953 stream.read(0);
22954}
22955
22956Readable.prototype.pause = function() {
22957 debug('call pause flowing=%j', this._readableState.flowing);
22958 if (false !== this._readableState.flowing) {
22959 debug('pause');
22960 this._readableState.flowing = false;
22961 this.emit('pause');
22962 }
22963 return this;
22964};
22965
22966function flow(stream) {
22967 var state = stream._readableState;
22968 debug('flow', state.flowing);
22969 if (state.flowing) {
22970 do {
22971 var chunk = stream.read();
22972 } while (null !== chunk && state.flowing);
22973 }
22974}
22975
22976// wrap an old-style stream as the async data source.
22977// This is *not* part of the readable stream interface.
22978// It is an ugly unfortunate mess of history.
22979Readable.prototype.wrap = function(stream) {
22980 var state = this._readableState;
22981 var paused = false;
22982
22983 var self = this;
22984 stream.on('end', function() {
22985 debug('wrapped end');
22986 if (state.decoder && !state.ended) {
22987 var chunk = state.decoder.end();
22988 if (chunk && chunk.length)
22989 self.push(chunk);
22990 }
22991
22992 self.push(null);
22993 });
22994
22995 stream.on('data', function(chunk) {
22996 debug('wrapped data');
22997 if (state.decoder)
22998 chunk = state.decoder.write(chunk);
22999
23000 // don't skip over falsy values in objectMode
23001 if (state.objectMode && (chunk === null || chunk === undefined))
23002 return;
23003 else if (!state.objectMode && (!chunk || !chunk.length))
23004 return;
23005
23006 var ret = self.push(chunk);
23007 if (!ret) {
23008 paused = true;
23009 stream.pause();
23010 }
23011 });
23012
23013 // proxy all the other methods.
23014 // important when wrapping filters and duplexes.
23015 for (var i in stream) {
23016 if (this[i] === undefined && typeof stream[i] === 'function') {
23017 this[i] = function(method) { return function() {
23018 return stream[method].apply(stream, arguments);
23019 }; }(i);
23020 }
23021 }
23022
23023 // proxy certain important events.
23024 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
23025 forEach(events, function(ev) {
23026 stream.on(ev, self.emit.bind(self, ev));
23027 });
23028
23029 // when we try to consume some more bytes, simply unpause the
23030 // underlying stream.
23031 self._read = function(n) {
23032 debug('wrapped _read', n);
23033 if (paused) {
23034 paused = false;
23035 stream.resume();
23036 }
23037 };
23038
23039 return self;
23040};
23041
23042
23043// exposed for testing purposes only.
23044Readable._fromList = fromList;
23045
23046// Pluck off n bytes from an array of buffers.
23047// Length is the combined lengths of all the buffers in the list.
23048function fromList(n, state) {
23049 var list = state.buffer;
23050 var length = state.length;
23051 var stringMode = !!state.decoder;
23052 var objectMode = !!state.objectMode;
23053 var ret;
23054
23055 // nothing in the list, definitely empty.
23056 if (list.length === 0)
23057 return null;
23058
23059 if (length === 0)
23060 ret = null;
23061 else if (objectMode)
23062 ret = list.shift();
23063 else if (!n || n >= length) {
23064 // read it all, truncate the array.
23065 if (stringMode)
23066 ret = list.join('');
23067 else
23068 ret = Buffer.concat(list, length);
23069 list.length = 0;
23070 } else {
23071 // read just some of it.
23072 if (n < list[0].length) {
23073 // just take a part of the first list item.
23074 // slice is the same for buffers and strings.
23075 var buf = list[0];
23076 ret = buf.slice(0, n);
23077 list[0] = buf.slice(n);
23078 } else if (n === list[0].length) {
23079 // first list is a perfect match
23080 ret = list.shift();
23081 } else {
23082 // complex case.
23083 // we have enough to cover it, but it spans past the first buffer.
23084 if (stringMode)
23085 ret = '';
23086 else
23087 ret = new Buffer(n);
23088
23089 var c = 0;
23090 for (var i = 0, l = list.length; i < l && c < n; i++) {
23091 var buf = list[0];
23092 var cpy = Math.min(n - c, buf.length);
23093
23094 if (stringMode)
23095 ret += buf.slice(0, cpy);
23096 else
23097 buf.copy(ret, c, 0, cpy);
23098
23099 if (cpy < buf.length)
23100 list[0] = buf.slice(cpy);
23101 else
23102 list.shift();
23103
23104 c += cpy;
23105 }
23106 }
23107 }
23108
23109 return ret;
23110}
23111
23112function endReadable(stream) {
23113 var state = stream._readableState;
23114
23115 // If we get here before consuming all the bytes, then that is a
23116 // bug in node. Should never happen.
23117 if (state.length > 0)
23118 throw new Error('endReadable called on non-empty stream');
23119
23120 if (!state.endEmitted) {
23121 state.ended = true;
23122 processNextTick(endReadableNT, state, stream);
23123 }
23124}
23125
23126function endReadableNT(state, stream) {
23127 // Check that we didn't get one last unshift.
23128 if (!state.endEmitted && state.length === 0) {
23129 state.endEmitted = true;
23130 stream.readable = false;
23131 stream.emit('end');
23132 }
23133}
23134
23135function forEach (xs, f) {
23136 for (var i = 0, l = xs.length; i < l; i++) {
23137 f(xs[i], i);
23138 }
23139}
23140
23141function indexOf (xs, x) {
23142 for (var i = 0, l = xs.length; i < l; i++) {
23143 if (xs[i] === x) return i;
23144 }
23145 return -1;
23146}
23147}, {"process-nextick-args":132,"isarray":133,"buffer":29,"events":3,"core-util-is":134,"inherits":135,"util":23,"./_stream_duplex":136,"string_decoder/":62}],132: [function (exports, require, module, global) {'use strict';
23148module.exports = nextTick;
23149
23150function nextTick(fn) {
23151 var args = new Array(arguments.length - 1);
23152 var i = 0;
23153 while (i < args.length) {
23154 args[i++] = arguments[i];
23155 }
23156 process.nextTick(function afterTick() {
23157 fn.apply(null, args);
23158 });
23159}
23160}, {}],133: [function (exports, require, module, global) {module.exports = Array.isArray || function (arr) {
23161 return Object.prototype.toString.call(arr) == '[object Array]';
23162};
23163}, {}],134: [function (exports, require, module, global) {// Copyright Joyent, Inc. and other Node contributors.
23164//
23165// Permission is hereby granted, free of charge, to any person obtaining a
23166// copy of this software and associated documentation files (the
23167// "Software"), to deal in the Software without restriction, including
23168// without limitation the rights to use, copy, modify, merge, publish,
23169// distribute, sublicense, and/or sell copies of the Software, and to permit
23170// persons to whom the Software is furnished to do so, subject to the
23171// following conditions:
23172//
23173// The above copyright notice and this permission notice shall be included
23174// in all copies or substantial portions of the Software.
23175//
23176// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23177// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23178// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
23179// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23180// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23181// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23182// USE OR OTHER DEALINGS IN THE SOFTWARE.
23183
23184// NOTE: These type checking functions intentionally don't use `instanceof`
23185// because it is fragile and can be easily faked with `Object.create()`.
23186function isArray(ar) {
23187 return Array.isArray(ar);
23188}
23189exports.isArray = isArray;
23190
23191function isBoolean(arg) {
23192 return typeof arg === 'boolean';
23193}
23194exports.isBoolean = isBoolean;
23195
23196function isNull(arg) {
23197 return arg === null;
23198}
23199exports.isNull = isNull;
23200
23201function isNullOrUndefined(arg) {
23202 return arg == null;
23203}
23204exports.isNullOrUndefined = isNullOrUndefined;
23205
23206function isNumber(arg) {
23207 return typeof arg === 'number';
23208}
23209exports.isNumber = isNumber;
23210
23211function isString(arg) {
23212 return typeof arg === 'string';
23213}
23214exports.isString = isString;
23215
23216function isSymbol(arg) {
23217 return typeof arg === 'symbol';
23218}
23219exports.isSymbol = isSymbol;
23220
23221function isUndefined(arg) {
23222 return arg === void 0;
23223}
23224exports.isUndefined = isUndefined;
23225
23226function isRegExp(re) {
23227 return isObject(re) && objectToString(re) === '[object RegExp]';
23228}
23229exports.isRegExp = isRegExp;
23230
23231function isObject(arg) {
23232 return typeof arg === 'object' && arg !== null;
23233}
23234exports.isObject = isObject;
23235
23236function isDate(d) {
23237 return isObject(d) && objectToString(d) === '[object Date]';
23238}
23239exports.isDate = isDate;
23240
23241function isError(e) {
23242 return isObject(e) &&
23243 (objectToString(e) === '[object Error]' || e instanceof Error);
23244}
23245exports.isError = isError;
23246
23247function isFunction(arg) {
23248 return typeof arg === 'function';
23249}
23250exports.isFunction = isFunction;
23251
23252function isPrimitive(arg) {
23253 return arg === null ||
23254 typeof arg === 'boolean' ||
23255 typeof arg === 'number' ||
23256 typeof arg === 'string' ||
23257 typeof arg === 'symbol' || // ES6 symbol
23258 typeof arg === 'undefined';
23259}
23260exports.isPrimitive = isPrimitive;
23261
23262function isBuffer(arg) {
23263 return Buffer.isBuffer(arg);
23264}
23265exports.isBuffer = isBuffer;
23266
23267function objectToString(o) {
23268 return Object.prototype.toString.call(o);
23269}}, {}],135: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
23270 // implementation from standard node.js 'util' module
23271 module.exports = function inherits(ctor, superCtor) {
23272 ctor.super_ = superCtor
23273 ctor.prototype = Object.create(superCtor.prototype, {
23274 constructor: {
23275 value: ctor,
23276 enumerable: false,
23277 writable: true,
23278 configurable: true
23279 }
23280 });
23281 };
23282} else {
23283 // old school shim for old browsers
23284 module.exports = function inherits(ctor, superCtor) {
23285 ctor.super_ = superCtor
23286 var TempCtor = function () {}
23287 TempCtor.prototype = superCtor.prototype
23288 ctor.prototype = new TempCtor()
23289 ctor.prototype.constructor = ctor
23290 }
23291}
23292}, {}],136: [function (exports, require, module, global) {// a duplex stream is just a stream that is both readable and writable.
23293// Since JS doesn't have multiple prototypal inheritance, this class
23294// prototypally inherits from Readable, and then parasitically from
23295// Writable.
23296
23297'use strict';
23298
23299/*<replacement>*/
23300var objectKeys = Object.keys || function (obj) {
23301 var keys = [];
23302 for (var key in obj) keys.push(key);
23303 return keys;
23304}
23305/*</replacement>*/
23306
23307
23308module.exports = Duplex;
23309
23310/*<replacement>*/
23311var processNextTick = require('process-nextick-args');
23312/*</replacement>*/
23313
23314
23315
23316/*<replacement>*/
23317var util = require('core-util-is');
23318util.inherits = require('inherits');
23319/*</replacement>*/
23320
23321var Readable = require('./_stream_readable');
23322var Writable = require('./_stream_writable');
23323
23324util.inherits(Duplex, Readable);
23325
23326var keys = objectKeys(Writable.prototype);
23327for (var v = 0; v < keys.length; v++) {
23328 var method = keys[v];
23329 if (!Duplex.prototype[method])
23330 Duplex.prototype[method] = Writable.prototype[method];
23331}
23332
23333function Duplex(options) {
23334 if (!(this instanceof Duplex))
23335 return new Duplex(options);
23336
23337 Readable.call(this, options);
23338 Writable.call(this, options);
23339
23340 if (options && options.readable === false)
23341 this.readable = false;
23342
23343 if (options && options.writable === false)
23344 this.writable = false;
23345
23346 this.allowHalfOpen = true;
23347 if (options && options.allowHalfOpen === false)
23348 this.allowHalfOpen = false;
23349
23350 this.once('end', onend);
23351}
23352
23353// the no-half-open enforcer
23354function onend() {
23355 // if we allow half-open state, or if the writable side ended,
23356 // then we're ok.
23357 if (this.allowHalfOpen || this._writableState.ended)
23358 return;
23359
23360 // no more data can be written.
23361 // But allow more writes to happen in this tick.
23362 processNextTick(onEndNT, this);
23363}
23364
23365function onEndNT(self) {
23366 self.end();
23367}
23368
23369function forEach (xs, f) {
23370 for (var i = 0, l = xs.length; i < l; i++) {
23371 f(xs[i], i);
23372 }
23373}
23374}, {"process-nextick-args":132,"core-util-is":134,"inherits":135,"./_stream_readable":131,"./_stream_writable":137}],137: [function (exports, require, module, global) {// A bit simpler than readable streams.
23375// Implement an async ._write(chunk, cb), and it'll handle all
23376// the drain event emission and buffering.
23377
23378'use strict';
23379
23380module.exports = Writable;
23381
23382/*<replacement>*/
23383var processNextTick = require('process-nextick-args');
23384/*</replacement>*/
23385
23386
23387/*<replacement>*/
23388var Buffer = require('buffer').Buffer;
23389/*</replacement>*/
23390
23391Writable.WritableState = WritableState;
23392
23393
23394/*<replacement>*/
23395var util = require('core-util-is');
23396util.inherits = require('inherits');
23397/*</replacement>*/
23398
23399
23400/*<replacement>*/
23401var internalUtil = {
23402 deprecate: require('util-deprecate')
23403};
23404/*</replacement>*/
23405
23406
23407
23408/*<replacement>*/
23409var Stream;
23410(function (){try{
23411 Stream = require('st' + 'ream');
23412}catch(_){}finally{
23413 if (!Stream)
23414 Stream = require('events').EventEmitter;
23415}}())
23416/*</replacement>*/
23417
23418var Buffer = require('buffer').Buffer;
23419
23420util.inherits(Writable, Stream);
23421
23422function nop() {}
23423
23424function WriteReq(chunk, encoding, cb) {
23425 this.chunk = chunk;
23426 this.encoding = encoding;
23427 this.callback = cb;
23428 this.next = null;
23429}
23430
23431function WritableState(options, stream) {
23432 var Duplex = require('./_stream_duplex');
23433
23434 options = options || {};
23435
23436 // object stream flag to indicate whether or not this stream
23437 // contains buffers or objects.
23438 this.objectMode = !!options.objectMode;
23439
23440 if (stream instanceof Duplex)
23441 this.objectMode = this.objectMode || !!options.writableObjectMode;
23442
23443 // the point at which write() starts returning false
23444 // Note: 0 is a valid value, means that we always return false if
23445 // the entire buffer is not flushed immediately on write()
23446 var hwm = options.highWaterMark;
23447 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
23448 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
23449
23450 // cast to ints.
23451 this.highWaterMark = ~~this.highWaterMark;
23452
23453 this.needDrain = false;
23454 // at the start of calling end()
23455 this.ending = false;
23456 // when end() has been called, and returned
23457 this.ended = false;
23458 // when 'finish' is emitted
23459 this.finished = false;
23460
23461 // should we decode strings into buffers before passing to _write?
23462 // this is here so that some node-core streams can optimize string
23463 // handling at a lower level.
23464 var noDecode = options.decodeStrings === false;
23465 this.decodeStrings = !noDecode;
23466
23467 // Crypto is kind of old and crusty. Historically, its default string
23468 // encoding is 'binary' so we have to make this configurable.
23469 // Everything else in the universe uses 'utf8', though.
23470 this.defaultEncoding = options.defaultEncoding || 'utf8';
23471
23472 // not an actual buffer we keep track of, but a measurement
23473 // of how much we're waiting to get pushed to some underlying
23474 // socket or file.
23475 this.length = 0;
23476
23477 // a flag to see when we're in the middle of a write.
23478 this.writing = false;
23479
23480 // when true all writes will be buffered until .uncork() call
23481 this.corked = 0;
23482
23483 // a flag to be able to tell if the onwrite cb is called immediately,
23484 // or on a later tick. We set this to true at first, because any
23485 // actions that shouldn't happen until "later" should generally also
23486 // not happen before the first write call.
23487 this.sync = true;
23488
23489 // a flag to know if we're processing previously buffered items, which
23490 // may call the _write() callback in the same tick, so that we don't
23491 // end up in an overlapped onwrite situation.
23492 this.bufferProcessing = false;
23493
23494 // the callback that's passed to _write(chunk,cb)
23495 this.onwrite = function(er) {
23496 onwrite(stream, er);
23497 };
23498
23499 // the callback that the user supplies to write(chunk,encoding,cb)
23500 this.writecb = null;
23501
23502 // the amount that is being written when _write is called.
23503 this.writelen = 0;
23504
23505 this.bufferedRequest = null;
23506 this.lastBufferedRequest = null;
23507
23508 // number of pending user-supplied write callbacks
23509 // this must be 0 before 'finish' can be emitted
23510 this.pendingcb = 0;
23511
23512 // emit prefinish if the only thing we're waiting for is _write cbs
23513 // This is relevant for synchronous Transform streams
23514 this.prefinished = false;
23515
23516 // True if the error was already emitted and should not be thrown again
23517 this.errorEmitted = false;
23518}
23519
23520WritableState.prototype.getBuffer = function writableStateGetBuffer() {
23521 var current = this.bufferedRequest;
23522 var out = [];
23523 while (current) {
23524 out.push(current);
23525 current = current.next;
23526 }
23527 return out;
23528};
23529
23530(function (){try {
23531Object.defineProperty(WritableState.prototype, 'buffer', {
23532 get: internalUtil.deprecate(function() {
23533 return this.getBuffer();
23534 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
23535 'instead.')
23536});
23537}catch(_){}}());
23538
23539
23540function Writable(options) {
23541 var Duplex = require('./_stream_duplex');
23542
23543 // Writable ctor is applied to Duplexes, though they're not
23544 // instanceof Writable, they're instanceof Readable.
23545 if (!(this instanceof Writable) && !(this instanceof Duplex))
23546 return new Writable(options);
23547
23548 this._writableState = new WritableState(options, this);
23549
23550 // legacy.
23551 this.writable = true;
23552
23553 if (options) {
23554 if (typeof options.write === 'function')
23555 this._write = options.write;
23556
23557 if (typeof options.writev === 'function')
23558 this._writev = options.writev;
23559 }
23560
23561 Stream.call(this);
23562}
23563
23564// Otherwise people can pipe Writable streams, which is just wrong.
23565Writable.prototype.pipe = function() {
23566 this.emit('error', new Error('Cannot pipe. Not readable.'));
23567};
23568
23569
23570function writeAfterEnd(stream, cb) {
23571 var er = new Error('write after end');
23572 // TODO: defer error events consistently everywhere, not just the cb
23573 stream.emit('error', er);
23574 processNextTick(cb, er);
23575}
23576
23577// If we get something that is not a buffer, string, null, or undefined,
23578// and we're not in objectMode, then that's an error.
23579// Otherwise stream chunks are all considered to be of length=1, and the
23580// watermarks determine how many objects to keep in the buffer, rather than
23581// how many bytes or characters.
23582function validChunk(stream, state, chunk, cb) {
23583 var valid = true;
23584
23585 if (!(Buffer.isBuffer(chunk)) &&
23586 typeof chunk !== 'string' &&
23587 chunk !== null &&
23588 chunk !== undefined &&
23589 !state.objectMode) {
23590 var er = new TypeError('Invalid non-string/buffer chunk');
23591 stream.emit('error', er);
23592 processNextTick(cb, er);
23593 valid = false;
23594 }
23595 return valid;
23596}
23597
23598Writable.prototype.write = function(chunk, encoding, cb) {
23599 var state = this._writableState;
23600 var ret = false;
23601
23602 if (typeof encoding === 'function') {
23603 cb = encoding;
23604 encoding = null;
23605 }
23606
23607 if (Buffer.isBuffer(chunk))
23608 encoding = 'buffer';
23609 else if (!encoding)
23610 encoding = state.defaultEncoding;
23611
23612 if (typeof cb !== 'function')
23613 cb = nop;
23614
23615 if (state.ended)
23616 writeAfterEnd(this, cb);
23617 else if (validChunk(this, state, chunk, cb)) {
23618 state.pendingcb++;
23619 ret = writeOrBuffer(this, state, chunk, encoding, cb);
23620 }
23621
23622 return ret;
23623};
23624
23625Writable.prototype.cork = function() {
23626 var state = this._writableState;
23627
23628 state.corked++;
23629};
23630
23631Writable.prototype.uncork = function() {
23632 var state = this._writableState;
23633
23634 if (state.corked) {
23635 state.corked--;
23636
23637 if (!state.writing &&
23638 !state.corked &&
23639 !state.finished &&
23640 !state.bufferProcessing &&
23641 state.bufferedRequest)
23642 clearBuffer(this, state);
23643 }
23644};
23645
23646Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
23647 // node::ParseEncoding() requires lower case.
23648 if (typeof encoding === 'string')
23649 encoding = encoding.toLowerCase();
23650 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64',
23651'ucs2', 'ucs-2','utf16le', 'utf-16le', 'raw']
23652.indexOf((encoding + '').toLowerCase()) > -1))
23653 throw new TypeError('Unknown encoding: ' + encoding);
23654 this._writableState.defaultEncoding = encoding;
23655};
23656
23657function decodeChunk(state, chunk, encoding) {
23658 if (!state.objectMode &&
23659 state.decodeStrings !== false &&
23660 typeof chunk === 'string') {
23661 chunk = new Buffer(chunk, encoding);
23662 }
23663 return chunk;
23664}
23665
23666// if we're already writing something, then just put this
23667// in the queue, and wait our turn. Otherwise, call _write
23668// If we return false, then we need a drain event, so set that flag.
23669function writeOrBuffer(stream, state, chunk, encoding, cb) {
23670 chunk = decodeChunk(state, chunk, encoding);
23671
23672 if (Buffer.isBuffer(chunk))
23673 encoding = 'buffer';
23674 var len = state.objectMode ? 1 : chunk.length;
23675
23676 state.length += len;
23677
23678 var ret = state.length < state.highWaterMark;
23679 // we must ensure that previous needDrain will not be reset to false.
23680 if (!ret)
23681 state.needDrain = true;
23682
23683 if (state.writing || state.corked) {
23684 var last = state.lastBufferedRequest;
23685 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
23686 if (last) {
23687 last.next = state.lastBufferedRequest;
23688 } else {
23689 state.bufferedRequest = state.lastBufferedRequest;
23690 }
23691 } else {
23692 doWrite(stream, state, false, len, chunk, encoding, cb);
23693 }
23694
23695 return ret;
23696}
23697
23698function doWrite(stream, state, writev, len, chunk, encoding, cb) {
23699 state.writelen = len;
23700 state.writecb = cb;
23701 state.writing = true;
23702 state.sync = true;
23703 if (writev)
23704 stream._writev(chunk, state.onwrite);
23705 else
23706 stream._write(chunk, encoding, state.onwrite);
23707 state.sync = false;
23708}
23709
23710function onwriteError(stream, state, sync, er, cb) {
23711 --state.pendingcb;
23712 if (sync)
23713 processNextTick(cb, er);
23714 else
23715 cb(er);
23716
23717 stream._writableState.errorEmitted = true;
23718 stream.emit('error', er);
23719}
23720
23721function onwriteStateUpdate(state) {
23722 state.writing = false;
23723 state.writecb = null;
23724 state.length -= state.writelen;
23725 state.writelen = 0;
23726}
23727
23728function onwrite(stream, er) {
23729 var state = stream._writableState;
23730 var sync = state.sync;
23731 var cb = state.writecb;
23732
23733 onwriteStateUpdate(state);
23734
23735 if (er)
23736 onwriteError(stream, state, sync, er, cb);
23737 else {
23738 // Check if we're actually ready to finish, but don't emit yet
23739 var finished = needFinish(state);
23740
23741 if (!finished &&
23742 !state.corked &&
23743 !state.bufferProcessing &&
23744 state.bufferedRequest) {
23745 clearBuffer(stream, state);
23746 }
23747
23748 if (sync) {
23749 processNextTick(afterWrite, stream, state, finished, cb);
23750 } else {
23751 afterWrite(stream, state, finished, cb);
23752 }
23753 }
23754}
23755
23756function afterWrite(stream, state, finished, cb) {
23757 if (!finished)
23758 onwriteDrain(stream, state);
23759 state.pendingcb--;
23760 cb();
23761 finishMaybe(stream, state);
23762}
23763
23764// Must force callback to be called on nextTick, so that we don't
23765// emit 'drain' before the write() consumer gets the 'false' return
23766// value, and has a chance to attach a 'drain' listener.
23767function onwriteDrain(stream, state) {
23768 if (state.length === 0 && state.needDrain) {
23769 state.needDrain = false;
23770 stream.emit('drain');
23771 }
23772}
23773
23774
23775// if there's something in the buffer waiting, then process it
23776function clearBuffer(stream, state) {
23777 state.bufferProcessing = true;
23778 var entry = state.bufferedRequest;
23779
23780 if (stream._writev && entry && entry.next) {
23781 // Fast case, write everything using _writev()
23782 var buffer = [];
23783 var cbs = [];
23784 while (entry) {
23785 cbs.push(entry.callback);
23786 buffer.push(entry);
23787 entry = entry.next;
23788 }
23789
23790 // count the one we are adding, as well.
23791 // TODO(isaacs) clean this up
23792 state.pendingcb++;
23793 state.lastBufferedRequest = null;
23794 doWrite(stream, state, true, state.length, buffer, '', function(err) {
23795 for (var i = 0; i < cbs.length; i++) {
23796 state.pendingcb--;
23797 cbs[i](err);
23798 }
23799 });
23800
23801 // Clear buffer
23802 } else {
23803 // Slow case, write chunks one-by-one
23804 while (entry) {
23805 var chunk = entry.chunk;
23806 var encoding = entry.encoding;
23807 var cb = entry.callback;
23808 var len = state.objectMode ? 1 : chunk.length;
23809
23810 doWrite(stream, state, false, len, chunk, encoding, cb);
23811 entry = entry.next;
23812 // if we didn't call the onwrite immediately, then
23813 // it means that we need to wait until it does.
23814 // also, that means that the chunk and cb are currently
23815 // being processed, so move the buffer counter past them.
23816 if (state.writing) {
23817 break;
23818 }
23819 }
23820
23821 if (entry === null)
23822 state.lastBufferedRequest = null;
23823 }
23824 state.bufferedRequest = entry;
23825 state.bufferProcessing = false;
23826}
23827
23828Writable.prototype._write = function(chunk, encoding, cb) {
23829 cb(new Error('not implemented'));
23830};
23831
23832Writable.prototype._writev = null;
23833
23834Writable.prototype.end = function(chunk, encoding, cb) {
23835 var state = this._writableState;
23836
23837 if (typeof chunk === 'function') {
23838 cb = chunk;
23839 chunk = null;
23840 encoding = null;
23841 } else if (typeof encoding === 'function') {
23842 cb = encoding;
23843 encoding = null;
23844 }
23845
23846 if (chunk !== null && chunk !== undefined)
23847 this.write(chunk, encoding);
23848
23849 // .end() fully uncorks
23850 if (state.corked) {
23851 state.corked = 1;
23852 this.uncork();
23853 }
23854
23855 // ignore unnecessary end() calls.
23856 if (!state.ending && !state.finished)
23857 endWritable(this, state, cb);
23858};
23859
23860
23861function needFinish(state) {
23862 return (state.ending &&
23863 state.length === 0 &&
23864 state.bufferedRequest === null &&
23865 !state.finished &&
23866 !state.writing);
23867}
23868
23869function prefinish(stream, state) {
23870 if (!state.prefinished) {
23871 state.prefinished = true;
23872 stream.emit('prefinish');
23873 }
23874}
23875
23876function finishMaybe(stream, state) {
23877 var need = needFinish(state);
23878 if (need) {
23879 if (state.pendingcb === 0) {
23880 prefinish(stream, state);
23881 state.finished = true;
23882 stream.emit('finish');
23883 } else {
23884 prefinish(stream, state);
23885 }
23886 }
23887 return need;
23888}
23889
23890function endWritable(stream, state, cb) {
23891 state.ending = true;
23892 finishMaybe(stream, state);
23893 if (cb) {
23894 if (state.finished)
23895 processNextTick(cb);
23896 else
23897 stream.once('finish', cb);
23898 }
23899 state.ended = true;
23900}
23901}, {"process-nextick-args":132,"buffer":29,"core-util-is":134,"inherits":135,"util-deprecate":138,"events":3,"./_stream_duplex":136}],138: [function (exports, require, module, global) {
23902/**
23903 * Module exports.
23904 */
23905
23906module.exports = deprecate;
23907
23908/**
23909 * Mark that a method should not be used.
23910 * Returns a modified function which warns once by default.
23911 *
23912 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
23913 *
23914 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
23915 * will throw an Error when invoked.
23916 *
23917 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
23918 * will invoke `console.trace()` instead of `console.error()`.
23919 *
23920 * @param {Function} fn - the function to deprecate
23921 * @param {String} msg - the string to print to the console when `fn` is invoked
23922 * @returns {Function} a new "deprecated" version of `fn`
23923 * @api public
23924 */
23925
23926function deprecate (fn, msg) {
23927 if (config('noDeprecation')) {
23928 return fn;
23929 }
23930
23931 var warned = false;
23932 function deprecated() {
23933 if (!warned) {
23934 if (config('throwDeprecation')) {
23935 throw new Error(msg);
23936 } else if (config('traceDeprecation')) {
23937 console.trace(msg);
23938 } else {
23939 console.warn(msg);
23940 }
23941 warned = true;
23942 }
23943 return fn.apply(this, arguments);
23944 }
23945
23946 return deprecated;
23947}
23948
23949/**
23950 * Checks `localStorage` for boolean values for the given `name`.
23951 *
23952 * @param {String} name
23953 * @returns {Boolean}
23954 * @api private
23955 */
23956
23957function config (name) {
23958 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
23959 try {
23960 if (!global.localStorage) return false;
23961 } catch (_) {
23962 return false;
23963 }
23964 var val = global.localStorage[name];
23965 if (null == val) return false;
23966 return String(val).toLowerCase() === 'true';
23967}
23968}, {}],139: [function (exports, require, module, global) {// a transform stream is a readable/writable stream where you do
23969// something with the data. Sometimes it's called a "filter",
23970// but that's not a great name for it, since that implies a thing where
23971// some bits pass through, and others are simply ignored. (That would
23972// be a valid example of a transform, of course.)
23973//
23974// While the output is causally related to the input, it's not a
23975// necessarily symmetric or synchronous transformation. For example,
23976// a zlib stream might take multiple plain-text writes(), and then
23977// emit a single compressed chunk some time in the future.
23978//
23979// Here's how this works:
23980//
23981// The Transform stream has all the aspects of the readable and writable
23982// stream classes. When you write(chunk), that calls _write(chunk,cb)
23983// internally, and returns false if there's a lot of pending writes
23984// buffered up. When you call read(), that calls _read(n) until
23985// there's enough pending readable data buffered up.
23986//
23987// In a transform stream, the written data is placed in a buffer. When
23988// _read(n) is called, it transforms the queued up data, calling the
23989// buffered _write cb's as it consumes chunks. If consuming a single
23990// written chunk would result in multiple output chunks, then the first
23991// outputted bit calls the readcb, and subsequent chunks just go into
23992// the read buffer, and will cause it to emit 'readable' if necessary.
23993//
23994// This way, back-pressure is actually determined by the reading side,
23995// since _read has to be called to start processing a new chunk. However,
23996// a pathological inflate type of transform can cause excessive buffering
23997// here. For example, imagine a stream where every byte of input is
23998// interpreted as an integer from 0-255, and then results in that many
23999// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
24000// 1kb of data being output. In this case, you could write a very small
24001// amount of input, and end up with a very large amount of output. In
24002// such a pathological inflating mechanism, there'd be no way to tell
24003// the system to stop doing the transform. A single 4MB write could
24004// cause the system to run out of memory.
24005//
24006// However, even in such a pathological case, only a single written chunk
24007// would be consumed, and then the rest would wait (un-transformed) until
24008// the results of the previous transformed chunk were consumed.
24009
24010'use strict';
24011
24012module.exports = Transform;
24013
24014var Duplex = require('./_stream_duplex');
24015
24016/*<replacement>*/
24017var util = require('core-util-is');
24018util.inherits = require('inherits');
24019/*</replacement>*/
24020
24021util.inherits(Transform, Duplex);
24022
24023
24024function TransformState(stream) {
24025 this.afterTransform = function(er, data) {
24026 return afterTransform(stream, er, data);
24027 };
24028
24029 this.needTransform = false;
24030 this.transforming = false;
24031 this.writecb = null;
24032 this.writechunk = null;
24033}
24034
24035function afterTransform(stream, er, data) {
24036 var ts = stream._transformState;
24037 ts.transforming = false;
24038
24039 var cb = ts.writecb;
24040
24041 if (!cb)
24042 return stream.emit('error', new Error('no writecb in Transform class'));
24043
24044 ts.writechunk = null;
24045 ts.writecb = null;
24046
24047 if (data !== null && data !== undefined)
24048 stream.push(data);
24049
24050 if (cb)
24051 cb(er);
24052
24053 var rs = stream._readableState;
24054 rs.reading = false;
24055 if (rs.needReadable || rs.length < rs.highWaterMark) {
24056 stream._read(rs.highWaterMark);
24057 }
24058}
24059
24060
24061function Transform(options) {
24062 if (!(this instanceof Transform))
24063 return new Transform(options);
24064
24065 Duplex.call(this, options);
24066
24067 this._transformState = new TransformState(this);
24068
24069 // when the writable side finishes, then flush out anything remaining.
24070 var stream = this;
24071
24072 // start out asking for a readable event once data is transformed.
24073 this._readableState.needReadable = true;
24074
24075 // we have implemented the _read method, and done the other things
24076 // that Readable wants before the first _read call, so unset the
24077 // sync guard flag.
24078 this._readableState.sync = false;
24079
24080 if (options) {
24081 if (typeof options.transform === 'function')
24082 this._transform = options.transform;
24083
24084 if (typeof options.flush === 'function')
24085 this._flush = options.flush;
24086 }
24087
24088 this.once('prefinish', function() {
24089 if (typeof this._flush === 'function')
24090 this._flush(function(er) {
24091 done(stream, er);
24092 });
24093 else
24094 done(stream);
24095 });
24096}
24097
24098Transform.prototype.push = function(chunk, encoding) {
24099 this._transformState.needTransform = false;
24100 return Duplex.prototype.push.call(this, chunk, encoding);
24101};
24102
24103// This is the part where you do stuff!
24104// override this function in implementation classes.
24105// 'chunk' is an input chunk.
24106//
24107// Call `push(newChunk)` to pass along transformed output
24108// to the readable side. You may call 'push' zero or more times.
24109//
24110// Call `cb(err)` when you are done with this chunk. If you pass
24111// an error, then that'll put the hurt on the whole operation. If you
24112// never call cb(), then you'll never get another chunk.
24113Transform.prototype._transform = function(chunk, encoding, cb) {
24114 throw new Error('not implemented');
24115};
24116
24117Transform.prototype._write = function(chunk, encoding, cb) {
24118 var ts = this._transformState;
24119 ts.writecb = cb;
24120 ts.writechunk = chunk;
24121 ts.writeencoding = encoding;
24122 if (!ts.transforming) {
24123 var rs = this._readableState;
24124 if (ts.needTransform ||
24125 rs.needReadable ||
24126 rs.length < rs.highWaterMark)
24127 this._read(rs.highWaterMark);
24128 }
24129};
24130
24131// Doesn't matter what the args are here.
24132// _transform does all the work.
24133// That we got here means that the readable side wants more data.
24134Transform.prototype._read = function(n) {
24135 var ts = this._transformState;
24136
24137 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
24138 ts.transforming = true;
24139 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
24140 } else {
24141 // mark that we need a transform, so that any data that comes in
24142 // will get processed, now that we've asked for it.
24143 ts.needTransform = true;
24144 }
24145};
24146
24147
24148function done(stream, er) {
24149 if (er)
24150 return stream.emit('error', er);
24151
24152 // if there's nothing in the write buffer, then that means
24153 // that nothing more will ever be provided
24154 var ws = stream._writableState;
24155 var ts = stream._transformState;
24156
24157 if (ws.length)
24158 throw new Error('calling transform done when ws.length != 0');
24159
24160 if (ts.transforming)
24161 throw new Error('calling transform done when still transforming');
24162
24163 return stream.push(null);
24164}
24165}, {"./_stream_duplex":136,"core-util-is":134,"inherits":135}],140: [function (exports, require, module, global) {// a passthrough stream.
24166// basically just the most minimal sort of Transform stream.
24167// Every written chunk gets output as-is.
24168
24169'use strict';
24170
24171module.exports = PassThrough;
24172
24173var Transform = require('./_stream_transform');
24174
24175/*<replacement>*/
24176var util = require('core-util-is');
24177util.inherits = require('inherits');
24178/*</replacement>*/
24179
24180util.inherits(PassThrough, Transform);
24181
24182function PassThrough(options) {
24183 if (!(this instanceof PassThrough))
24184 return new PassThrough(options);
24185
24186 Transform.call(this, options);
24187}
24188
24189PassThrough.prototype._transform = function(chunk, encoding, cb) {
24190 cb(null, chunk);
24191};
24192}, {"./_stream_transform":139,"core-util-is":134,"inherits":135}],141: [function (exports, require, module, global) {var undefined = (void 0); // Paranoia
24193
24194// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
24195// create, and consume so much memory, that the browser appears frozen.
24196var MAX_ARRAY_LENGTH = 1e5;
24197
24198// Approximations of internal ECMAScript conversion functions
24199var ECMAScript = (function() {
24200 // Stash a copy in case other scripts modify these
24201 var opts = Object.prototype.toString,
24202 ophop = Object.prototype.hasOwnProperty;
24203
24204 return {
24205 // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
24206 Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
24207 HasProperty: function(o, p) { return p in o; },
24208 HasOwnProperty: function(o, p) { return ophop.call(o, p); },
24209 IsCallable: function(o) { return typeof o === 'function'; },
24210 ToInt32: function(v) { return v >> 0; },
24211 ToUint32: function(v) { return v >>> 0; }
24212 };
24213}());
24214
24215// Snapshot intrinsics
24216var LN2 = Math.LN2,
24217 abs = Math.abs,
24218 floor = Math.floor,
24219 log = Math.log,
24220 min = Math.min,
24221 pow = Math.pow,
24222 round = Math.round;
24223
24224// ES5: lock down object properties
24225function configureProperties(obj) {
24226 if (getOwnPropNames && defineProp) {
24227 var props = getOwnPropNames(obj), i;
24228 for (i = 0; i < props.length; i += 1) {
24229 defineProp(obj, props[i], {
24230 value: obj[props[i]],
24231 writable: false,
24232 enumerable: false,
24233 configurable: false
24234 });
24235 }
24236 }
24237}
24238
24239// emulate ES5 getter/setter API using legacy APIs
24240// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
24241// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
24242// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
24243var defineProp
24244if (Object.defineProperty && (function() {
24245 try {
24246 Object.defineProperty({}, 'x', {});
24247 return true;
24248 } catch (e) {
24249 return false;
24250 }
24251 })()) {
24252 defineProp = Object.defineProperty;
24253} else {
24254 defineProp = function(o, p, desc) {
24255 if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
24256 if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
24257 if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
24258 if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
24259 return o;
24260 };
24261}
24262
24263var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
24264 if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
24265 var props = [], p;
24266 for (p in o) {
24267 if (ECMAScript.HasOwnProperty(o, p)) {
24268 props.push(p);
24269 }
24270 }
24271 return props;
24272};
24273
24274// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
24275// for index in 0 ... obj.length
24276function makeArrayAccessors(obj) {
24277 if (!defineProp) { return; }
24278
24279 if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
24280
24281 function makeArrayAccessor(index) {
24282 defineProp(obj, index, {
24283 'get': function() { return obj._getter(index); },
24284 'set': function(v) { obj._setter(index, v); },
24285 enumerable: true,
24286 configurable: false
24287 });
24288 }
24289
24290 var i;
24291 for (i = 0; i < obj.length; i += 1) {
24292 makeArrayAccessor(i);
24293 }
24294}
24295
24296// Internal conversion functions:
24297// pack<Type>() - take a number (interpreted as Type), output a byte array
24298// unpack<Type>() - take a byte array, output a Type-like number
24299
24300function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
24301function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
24302
24303function packI8(n) { return [n & 0xff]; }
24304function unpackI8(bytes) { return as_signed(bytes[0], 8); }
24305
24306function packU8(n) { return [n & 0xff]; }
24307function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
24308
24309function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
24310
24311function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
24312function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
24313
24314function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
24315function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
24316
24317function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
24318function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
24319
24320function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
24321function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
24322
24323function packIEEE754(v, ebits, fbits) {
24324
24325 var bias = (1 << (ebits - 1)) - 1,
24326 s, e, f, ln,
24327 i, bits, str, bytes;
24328
24329 function roundToEven(n) {
24330 var w = floor(n), f = n - w;
24331 if (f < 0.5)
24332 return w;
24333 if (f > 0.5)
24334 return w + 1;
24335 return w % 2 ? w + 1 : w;
24336 }
24337
24338 // Compute sign, exponent, fraction
24339 if (v !== v) {
24340 // NaN
24341 // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
24342 e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
24343 } else if (v === Infinity || v === -Infinity) {
24344 e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
24345 } else if (v === 0) {
24346 e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
24347 } else {
24348 s = v < 0;
24349 v = abs(v);
24350
24351 if (v >= pow(2, 1 - bias)) {
24352 e = min(floor(log(v) / LN2), 1023);
24353 f = roundToEven(v / pow(2, e) * pow(2, fbits));
24354 if (f / pow(2, fbits) >= 2) {
24355 e = e + 1;
24356 f = 1;
24357 }
24358 if (e > bias) {
24359 // Overflow
24360 e = (1 << ebits) - 1;
24361 f = 0;
24362 } else {
24363 // Normalized
24364 e = e + bias;
24365 f = f - pow(2, fbits);
24366 }
24367 } else {
24368 // Denormalized
24369 e = 0;
24370 f = roundToEven(v / pow(2, 1 - bias - fbits));
24371 }
24372 }
24373
24374 // Pack sign, exponent, fraction
24375 bits = [];
24376 for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
24377 for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
24378 bits.push(s ? 1 : 0);
24379 bits.reverse();
24380 str = bits.join('');
24381
24382 // Bits to bytes
24383 bytes = [];
24384 while (str.length) {
24385 bytes.push(parseInt(str.substring(0, 8), 2));
24386 str = str.substring(8);
24387 }
24388 return bytes;
24389}
24390
24391function unpackIEEE754(bytes, ebits, fbits) {
24392
24393 // Bytes to bits
24394 var bits = [], i, j, b, str,
24395 bias, s, e, f;
24396
24397 for (i = bytes.length; i; i -= 1) {
24398 b = bytes[i - 1];
24399 for (j = 8; j; j -= 1) {
24400 bits.push(b % 2 ? 1 : 0); b = b >> 1;
24401 }
24402 }
24403 bits.reverse();
24404 str = bits.join('');
24405
24406 // Unpack sign, exponent, fraction
24407 bias = (1 << (ebits - 1)) - 1;
24408 s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
24409 e = parseInt(str.substring(1, 1 + ebits), 2);
24410 f = parseInt(str.substring(1 + ebits), 2);
24411
24412 // Produce number
24413 if (e === (1 << ebits) - 1) {
24414 return f !== 0 ? NaN : s * Infinity;
24415 } else if (e > 0) {
24416 // Normalized
24417 return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
24418 } else if (f !== 0) {
24419 // Denormalized
24420 return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
24421 } else {
24422 return s < 0 ? -0 : 0;
24423 }
24424}
24425
24426function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
24427function packF64(v) { return packIEEE754(v, 11, 52); }
24428function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
24429function packF32(v) { return packIEEE754(v, 8, 23); }
24430
24431
24432//
24433// 3 The ArrayBuffer Type
24434//
24435
24436(function() {
24437
24438 /** @constructor */
24439 var ArrayBuffer = function ArrayBuffer(length) {
24440 length = ECMAScript.ToInt32(length);
24441 if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
24442
24443 this.byteLength = length;
24444 this._bytes = [];
24445 this._bytes.length = length;
24446
24447 var i;
24448 for (i = 0; i < this.byteLength; i += 1) {
24449 this._bytes[i] = 0;
24450 }
24451
24452 configureProperties(this);
24453 };
24454
24455 exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
24456
24457 //
24458 // 4 The ArrayBufferView Type
24459 //
24460
24461 // NOTE: this constructor is not exported
24462 /** @constructor */
24463 var ArrayBufferView = function ArrayBufferView() {
24464 //this.buffer = null;
24465 //this.byteOffset = 0;
24466 //this.byteLength = 0;
24467 };
24468
24469 //
24470 // 5 The Typed Array View Types
24471 //
24472
24473 function makeConstructor(bytesPerElement, pack, unpack) {
24474 // Each TypedArray type requires a distinct constructor instance with
24475 // identical logic, which this produces.
24476
24477 var ctor;
24478 ctor = function(buffer, byteOffset, length) {
24479 var array, sequence, i, s;
24480
24481 if (!arguments.length || typeof arguments[0] === 'number') {
24482 // Constructor(unsigned long length)
24483 this.length = ECMAScript.ToInt32(arguments[0]);
24484 if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
24485
24486 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
24487 this.buffer = new ArrayBuffer(this.byteLength);
24488 this.byteOffset = 0;
24489 } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
24490 // Constructor(TypedArray array)
24491 array = arguments[0];
24492
24493 this.length = array.length;
24494 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
24495 this.buffer = new ArrayBuffer(this.byteLength);
24496 this.byteOffset = 0;
24497
24498 for (i = 0; i < this.length; i += 1) {
24499 this._setter(i, array._getter(i));
24500 }
24501 } else if (typeof arguments[0] === 'object' &&
24502 !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
24503 // Constructor(sequence<type> array)
24504 sequence = arguments[0];
24505
24506 this.length = ECMAScript.ToUint32(sequence.length);
24507 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
24508 this.buffer = new ArrayBuffer(this.byteLength);
24509 this.byteOffset = 0;
24510
24511 for (i = 0; i < this.length; i += 1) {
24512 s = sequence[i];
24513 this._setter(i, Number(s));
24514 }
24515 } else if (typeof arguments[0] === 'object' &&
24516 (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
24517 // Constructor(ArrayBuffer buffer,
24518 // optional unsigned long byteOffset, optional unsigned long length)
24519 this.buffer = buffer;
24520
24521 this.byteOffset = ECMAScript.ToUint32(byteOffset);
24522 if (this.byteOffset > this.buffer.byteLength) {
24523 throw new RangeError("byteOffset out of range");
24524 }
24525
24526 if (this.byteOffset % this.BYTES_PER_ELEMENT) {
24527 // The given byteOffset must be a multiple of the element
24528 // size of the specific type, otherwise an exception is raised.
24529 throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
24530 }
24531
24532 if (arguments.length < 3) {
24533 this.byteLength = this.buffer.byteLength - this.byteOffset;
24534
24535 if (this.byteLength % this.BYTES_PER_ELEMENT) {
24536 throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
24537 }
24538 this.length = this.byteLength / this.BYTES_PER_ELEMENT;
24539 } else {
24540 this.length = ECMAScript.ToUint32(length);
24541 this.byteLength = this.length * this.BYTES_PER_ELEMENT;
24542 }
24543
24544 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
24545 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
24546 }
24547 } else {
24548 throw new TypeError("Unexpected argument type(s)");
24549 }
24550
24551 this.constructor = ctor;
24552
24553 configureProperties(this);
24554 makeArrayAccessors(this);
24555 };
24556
24557 ctor.prototype = new ArrayBufferView();
24558 ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
24559 ctor.prototype._pack = pack;
24560 ctor.prototype._unpack = unpack;
24561 ctor.BYTES_PER_ELEMENT = bytesPerElement;
24562
24563 // getter type (unsigned long index);
24564 ctor.prototype._getter = function(index) {
24565 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
24566
24567 index = ECMAScript.ToUint32(index);
24568 if (index >= this.length) {
24569 return undefined;
24570 }
24571
24572 var bytes = [], i, o;
24573 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
24574 i < this.BYTES_PER_ELEMENT;
24575 i += 1, o += 1) {
24576 bytes.push(this.buffer._bytes[o]);
24577 }
24578 return this._unpack(bytes);
24579 };
24580
24581 // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
24582 ctor.prototype.get = ctor.prototype._getter;
24583
24584 // setter void (unsigned long index, type value);
24585 ctor.prototype._setter = function(index, value) {
24586 if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
24587
24588 index = ECMAScript.ToUint32(index);
24589 if (index >= this.length) {
24590 return undefined;
24591 }
24592
24593 var bytes = this._pack(value), i, o;
24594 for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
24595 i < this.BYTES_PER_ELEMENT;
24596 i += 1, o += 1) {
24597 this.buffer._bytes[o] = bytes[i];
24598 }
24599 };
24600
24601 // void set(TypedArray array, optional unsigned long offset);
24602 // void set(sequence<type> array, optional unsigned long offset);
24603 ctor.prototype.set = function(index, value) {
24604 if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
24605 var array, sequence, offset, len,
24606 i, s, d,
24607 byteOffset, byteLength, tmp;
24608
24609 if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
24610 // void set(TypedArray array, optional unsigned long offset);
24611 array = arguments[0];
24612 offset = ECMAScript.ToUint32(arguments[1]);
24613
24614 if (offset + array.length > this.length) {
24615 throw new RangeError("Offset plus length of array is out of range");
24616 }
24617
24618 byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
24619 byteLength = array.length * this.BYTES_PER_ELEMENT;
24620
24621 if (array.buffer === this.buffer) {
24622 tmp = [];
24623 for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
24624 tmp[i] = array.buffer._bytes[s];
24625 }
24626 for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
24627 this.buffer._bytes[d] = tmp[i];
24628 }
24629 } else {
24630 for (i = 0, s = array.byteOffset, d = byteOffset;
24631 i < byteLength; i += 1, s += 1, d += 1) {
24632 this.buffer._bytes[d] = array.buffer._bytes[s];
24633 }
24634 }
24635 } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
24636 // void set(sequence<type> array, optional unsigned long offset);
24637 sequence = arguments[0];
24638 len = ECMAScript.ToUint32(sequence.length);
24639 offset = ECMAScript.ToUint32(arguments[1]);
24640
24641 if (offset + len > this.length) {
24642 throw new RangeError("Offset plus length of array is out of range");
24643 }
24644
24645 for (i = 0; i < len; i += 1) {
24646 s = sequence[i];
24647 this._setter(offset + i, Number(s));
24648 }
24649 } else {
24650 throw new TypeError("Unexpected argument type(s)");
24651 }
24652 };
24653
24654 // TypedArray subarray(long begin, optional long end);
24655 ctor.prototype.subarray = function(start, end) {
24656 function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
24657
24658 start = ECMAScript.ToInt32(start);
24659 end = ECMAScript.ToInt32(end);
24660
24661 if (arguments.length < 1) { start = 0; }
24662 if (arguments.length < 2) { end = this.length; }
24663
24664 if (start < 0) { start = this.length + start; }
24665 if (end < 0) { end = this.length + end; }
24666
24667 start = clamp(start, 0, this.length);
24668 end = clamp(end, 0, this.length);
24669
24670 var len = end - start;
24671 if (len < 0) {
24672 len = 0;
24673 }
24674
24675 return new this.constructor(
24676 this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
24677 };
24678
24679 return ctor;
24680 }
24681
24682 var Int8Array = makeConstructor(1, packI8, unpackI8);
24683 var Uint8Array = makeConstructor(1, packU8, unpackU8);
24684 var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
24685 var Int16Array = makeConstructor(2, packI16, unpackI16);
24686 var Uint16Array = makeConstructor(2, packU16, unpackU16);
24687 var Int32Array = makeConstructor(4, packI32, unpackI32);
24688 var Uint32Array = makeConstructor(4, packU32, unpackU32);
24689 var Float32Array = makeConstructor(4, packF32, unpackF32);
24690 var Float64Array = makeConstructor(8, packF64, unpackF64);
24691
24692 exports.Int8Array = exports.Int8Array || Int8Array;
24693 exports.Uint8Array = exports.Uint8Array || Uint8Array;
24694 exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
24695 exports.Int16Array = exports.Int16Array || Int16Array;
24696 exports.Uint16Array = exports.Uint16Array || Uint16Array;
24697 exports.Int32Array = exports.Int32Array || Int32Array;
24698 exports.Uint32Array = exports.Uint32Array || Uint32Array;
24699 exports.Float32Array = exports.Float32Array || Float32Array;
24700 exports.Float64Array = exports.Float64Array || Float64Array;
24701}());
24702
24703//
24704// 6 The DataView View Type
24705//
24706
24707(function() {
24708 function r(array, index) {
24709 return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
24710 }
24711
24712 var IS_BIG_ENDIAN = (function() {
24713 var u16array = new(exports.Uint16Array)([0x1234]),
24714 u8array = new(exports.Uint8Array)(u16array.buffer);
24715 return r(u8array, 0) === 0x12;
24716 }());
24717
24718 // Constructor(ArrayBuffer buffer,
24719 // optional unsigned long byteOffset,
24720 // optional unsigned long byteLength)
24721 /** @constructor */
24722 var DataView = function DataView(buffer, byteOffset, byteLength) {
24723 if (arguments.length === 0) {
24724 buffer = new exports.ArrayBuffer(0);
24725 } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
24726 throw new TypeError("TypeError");
24727 }
24728
24729 this.buffer = buffer || new exports.ArrayBuffer(0);
24730
24731 this.byteOffset = ECMAScript.ToUint32(byteOffset);
24732 if (this.byteOffset > this.buffer.byteLength) {
24733 throw new RangeError("byteOffset out of range");
24734 }
24735
24736 if (arguments.length < 3) {
24737 this.byteLength = this.buffer.byteLength - this.byteOffset;
24738 } else {
24739 this.byteLength = ECMAScript.ToUint32(byteLength);
24740 }
24741
24742 if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
24743 throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
24744 }
24745
24746 configureProperties(this);
24747 };
24748
24749 function makeGetter(arrayType) {
24750 return function(byteOffset, littleEndian) {
24751
24752 byteOffset = ECMAScript.ToUint32(byteOffset);
24753
24754 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
24755 throw new RangeError("Array index out of range");
24756 }
24757 byteOffset += this.byteOffset;
24758
24759 var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
24760 bytes = [], i;
24761 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
24762 bytes.push(r(uint8Array, i));
24763 }
24764
24765 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
24766 bytes.reverse();
24767 }
24768
24769 return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0);
24770 };
24771 }
24772
24773 DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
24774 DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
24775 DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
24776 DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
24777 DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
24778 DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
24779 DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
24780 DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
24781
24782 function makeSetter(arrayType) {
24783 return function(byteOffset, value, littleEndian) {
24784
24785 byteOffset = ECMAScript.ToUint32(byteOffset);
24786 if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
24787 throw new RangeError("Array index out of range");
24788 }
24789
24790 // Get bytes
24791 var typeArray = new arrayType([value]),
24792 byteArray = new exports.Uint8Array(typeArray.buffer),
24793 bytes = [], i, byteView;
24794
24795 for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
24796 bytes.push(r(byteArray, i));
24797 }
24798
24799 // Flip if necessary
24800 if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
24801 bytes.reverse();
24802 }
24803
24804 // Write them
24805 byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
24806 byteView.set(bytes);
24807 };
24808 }
24809
24810 DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
24811 DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
24812 DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
24813 DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
24814 DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
24815 DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
24816 DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
24817 DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
24818
24819 exports.DataView = exports.DataView || DataView;
24820
24821}());
24822}, {}],142: [function (exports, require, module, global) {var toDate = function(date) {
24823 if (!date) return new Date();
24824 if (typeof date === 'string') return new Date(date);
24825 return date;
24826};
24827
24828var Stat = function(opts) {
24829 this.uid = opts.uid || 0;
24830 this.gid = opts.gid || 0;
24831 this.mode = opts.mode || 0;
24832 this.size = opts.size || 0;
24833 this.mtime = toDate(opts.mtime);
24834 this.atime = toDate(opts.atime);
24835 this.ctime = toDate(opts.ctime);
24836 this.type = opts.type;
24837 this.target = opts.target;
24838 this.link = opts.link;
24839 this.blob = opts.blob;
24840};
24841
24842Stat.prototype.isDirectory = function() {
24843 return this.type === 'directory';
24844};
24845
24846Stat.prototype.isFile = function() {
24847 return this.type === 'file';
24848};
24849
24850Stat.prototype.isBlockDevice = function() {
24851 return false;
24852};
24853
24854Stat.prototype.isCharacterDevice = function() {
24855 return false;
24856};
24857
24858Stat.prototype.isSymbolicLink = function() {
24859 return this.type === 'symlink';
24860};
24861
24862Stat.prototype.isFIFO = function() {
24863 return false;
24864};
24865
24866Stat.prototype.isSocket = function() {
24867 return false;
24868};
24869
24870module.exports = function(opts) {
24871 return new Stat(opts);
24872};}, {}],143: [function (exports, require, module, global) {var hasKeys = require("./has-keys")
24873
24874module.exports = extend
24875
24876function extend() {
24877 var target = {}
24878
24879 for (var i = 0; i < arguments.length; i++) {
24880 var source = arguments[i]
24881
24882 if (!hasKeys(source)) {
24883 continue
24884 }
24885
24886 for (var key in source) {
24887 if (source.hasOwnProperty(key)) {
24888 target[key] = source[key]
24889 }
24890 }
24891 }
24892
24893 return target
24894}
24895}, {"./has-keys":144}],144: [function (exports, require, module, global) {module.exports = hasKeys
24896
24897function hasKeys(source) {
24898 return source !== null &&
24899 (typeof source === "object" ||
24900 typeof source === "function")
24901}
24902}, {}],145: [function (exports, require, module, global) {var events = require('events');
24903
24904module.exports = function() {
24905 var listeners = {};
24906 var that = new events.EventEmitter();
24907
24908 that.watch = function(key, cb) {
24909 if (!listeners[key]) {
24910 listeners[key] = new events.EventEmitter();
24911 listeners[key].setMaxListeners(0);
24912 }
24913
24914 if (cb) listeners[key].on('change', cb);
24915 return listeners[key];
24916 };
24917
24918 that.watcher = function(key, cb) {
24919 var watcher = new events.EventEmitter();
24920 var onchange = function() {
24921 watcher.emit('change', 'change', key);
24922 };
24923
24924 that.watch(key, onchange);
24925 if (cb) watcher.on('change', cb);
24926 watcher.close = function() {
24927 that.unwatch(key, onchange);
24928 };
24929
24930 return watcher;
24931 };
24932
24933 that.unwatch = function(key, cb) {
24934 if (!listeners[key]) return;
24935 if (cb) listeners[key].removeListener('change', cb);
24936 else listeners[key].removeAllListeners('change');
24937 if (!listeners[key].listeners('change').length) delete listeners[key];;
24938 };
24939
24940 that.change = function(key) {
24941 if (listeners[key]) listeners[key].emit('change');
24942 that.emit('change', key);
24943 };
24944
24945 that.cb = function(key, cb) {
24946 return function(err, val) {
24947 if (key) that.change(key);
24948 if (cb) cb(err, val);
24949 };
24950 };
24951
24952 return that;
24953};}, {"events":3}],146: [function (exports, require, module, global) {'use strict'
24954
24955exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
24956exports.createHash = exports.Hash = require('create-hash')
24957exports.createHmac = exports.Hmac = require('create-hmac')
24958
24959var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(Object.keys(require('browserify-sign/algos')))
24960exports.getHashes = function () {
24961 return hashes
24962}
24963
24964var p = require('pbkdf2')
24965exports.pbkdf2 = p.pbkdf2
24966exports.pbkdf2Sync = p.pbkdf2Sync
24967
24968var aes = require('browserify-cipher')
24969;[
24970 'Cipher',
24971 'createCipher',
24972 'Cipheriv',
24973 'createCipheriv',
24974 'Decipher',
24975 'createDecipher',
24976 'Decipheriv',
24977 'createDecipheriv',
24978 'getCiphers',
24979 'listCiphers'
24980].forEach(function (key) {
24981 exports[key] = aes[key]
24982})
24983
24984var dh = require('diffie-hellman')
24985;[
24986 'DiffieHellmanGroup',
24987 'createDiffieHellmanGroup',
24988 'getDiffieHellman',
24989 'createDiffieHellman',
24990 'DiffieHellman'
24991].forEach(function (key) {
24992 exports[key] = dh[key]
24993})
24994
24995var sign = require('browserify-sign')
24996;[
24997 'createSign',
24998 'Sign',
24999 'createVerify',
25000 'Verify'
25001].forEach(function (key) {
25002 exports[key] = sign[key]
25003})
25004
25005exports.createECDH = require('create-ecdh')
25006
25007var publicEncrypt = require('public-encrypt')
25008
25009;[
25010 'publicEncrypt',
25011 'privateEncrypt',
25012 'publicDecrypt',
25013 'privateDecrypt'
25014].forEach(function (key) {
25015 exports[key] = publicEncrypt[key]
25016})
25017
25018// the least I can do is make error messages for the rest of the node.js/crypto api.
25019;[
25020 'createCredentials'
25021].forEach(function (name) {
25022 exports[name] = function () {
25023 throw new Error([
25024 'sorry, ' + name + ' is not implemented yet',
25025 'we accept pull requests',
25026 'https://github.com/crypto-browserify/crypto-browserify'
25027 ].join('\n'))
25028 }
25029})
25030}, {"randombytes":147,"create-hash":148,"create-hmac":162,"browserify-sign/algos":163,"pbkdf2":164,"browserify-cipher":165,"diffie-hellman":194,"browserify-sign":201,"create-ecdh":267,"public-encrypt":290}],147: [function (exports, require, module, global) {'use strict';
25031
25032var crypto = global.crypto || global.msCrypto
25033if(crypto && crypto.getRandomValues) {
25034 module.exports = randomBytes;
25035} else {
25036 module.exports = oldBrowser;
25037}
25038function randomBytes(size, cb) {
25039 var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
25040 /* This will not work in older browsers.
25041 * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
25042 */
25043
25044 crypto.getRandomValues(bytes);
25045 if (typeof cb === 'function') {
25046 return process.nextTick(function () {
25047 cb(null, bytes);
25048 });
25049 }
25050 return bytes;
25051}
25052function oldBrowser() {
25053 throw new Error(
25054 'secure random number generation not supported by this browser\n'+
25055 'use chrome, FireFox or Internet Explorer 11'
25056 )
25057}
25058}, {}],148: [function (exports, require, module, global) {'use strict';
25059var inherits = require('inherits')
25060var md5 = require('./md5')
25061var rmd160 = require('ripemd160')
25062var sha = require('sha.js')
25063
25064var Base = require('cipher-base')
25065
25066function HashNoConstructor(hash) {
25067 Base.call(this, 'digest')
25068
25069 this._hash = hash
25070 this.buffers = []
25071}
25072
25073inherits(HashNoConstructor, Base)
25074
25075HashNoConstructor.prototype._update = function (data) {
25076 this.buffers.push(data)
25077}
25078
25079HashNoConstructor.prototype._final = function () {
25080 var buf = Buffer.concat(this.buffers)
25081 var r = this._hash(buf)
25082 this.buffers = null
25083
25084 return r
25085}
25086
25087function Hash(hash) {
25088 Base.call(this, 'digest')
25089
25090 this._hash = hash
25091}
25092
25093inherits(Hash, Base)
25094
25095Hash.prototype._update = function (data) {
25096 this._hash.update(data)
25097}
25098
25099Hash.prototype._final = function () {
25100 return this._hash.digest()
25101}
25102
25103module.exports = function createHash (alg) {
25104 alg = alg.toLowerCase()
25105 if ('md5' === alg) return new HashNoConstructor(md5)
25106 if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160)
25107
25108 return new Hash(sha(alg))
25109}
25110}, {"inherits":149,"./md5":150,"ripemd160":152,"sha.js":153,"cipher-base":161}],149: [function (exports, require, module, global) {if (typeof Object.create === 'function') {
25111 // implementation from standard node.js 'util' module
25112 module.exports = function inherits(ctor, superCtor) {
25113 ctor.super_ = superCtor
25114 ctor.prototype = Object.create(superCtor.prototype, {
25115 constructor: {
25116 value: ctor,
25117 enumerable: false,
25118 writable: true,
25119 configurable: true
25120 }
25121 });
25122 };
25123} else {
25124 // old school shim for old browsers
25125 module.exports = function inherits(ctor, superCtor) {
25126 ctor.super_ = superCtor
25127 var TempCtor = function () {}
25128 TempCtor.prototype = superCtor.prototype
25129 ctor.prototype = new TempCtor()
25130 ctor.prototype.constructor = ctor
25131 }
25132}
25133}, {}],150: [function (exports, require, module, global) {'use strict';
25134/*
25135 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
25136 * Digest Algorithm, as defined in RFC 1321.
25137 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
25138 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25139 * Distributed under the BSD License
25140 * See http://pajhome.org.uk/crypt/md5 for more info.
25141 */
25142
25143var helpers = require('./helpers');
25144
25145/*
25146 * Calculate the MD5 of an array of little-endian words, and a bit length
25147 */
25148function core_md5(x, len)
25149{
25150 /* append padding */
25151 x[len >> 5] |= 0x80 << ((len) % 32);
25152 x[(((len + 64) >>> 9) << 4) + 14] = len;
25153
25154 var a = 1732584193;
25155 var b = -271733879;
25156 var c = -1732584194;
25157 var d = 271733878;
25158
25159 for(var i = 0; i < x.length; i += 16)
25160 {
25161 var olda = a;
25162 var oldb = b;
25163 var oldc = c;
25164 var oldd = d;
25165
25166 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
25167 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
25168 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
25169 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
25170 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
25171 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
25172 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
25173 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
25174 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
25175 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
25176 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
25177 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
25178 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
25179 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
25180 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
25181 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
25182
25183 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
25184 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
25185 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
25186 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
25187 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
25188 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
25189 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
25190 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
25191 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
25192 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
25193 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
25194 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
25195 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
25196 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
25197 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
25198 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
25199
25200 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
25201 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
25202 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
25203 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
25204 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
25205 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
25206 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
25207 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
25208 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
25209 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
25210 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
25211 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
25212 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
25213 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
25214 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
25215 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
25216
25217 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
25218 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
25219 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
25220 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
25221 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
25222 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
25223 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
25224 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
25225 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
25226 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
25227 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
25228 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
25229 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
25230 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
25231 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
25232 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
25233
25234 a = safe_add(a, olda);
25235 b = safe_add(b, oldb);
25236 c = safe_add(c, oldc);
25237 d = safe_add(d, oldd);
25238 }
25239 return Array(a, b, c, d);
25240
25241}
25242
25243/*
25244 * These functions implement the four basic operations the algorithm uses.
25245 */
25246function md5_cmn(q, a, b, x, s, t)
25247{
25248 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
25249}
25250function md5_ff(a, b, c, d, x, s, t)
25251{
25252 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
25253}
25254function md5_gg(a, b, c, d, x, s, t)
25255{
25256 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
25257}
25258function md5_hh(a, b, c, d, x, s, t)
25259{
25260 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
25261}
25262function md5_ii(a, b, c, d, x, s, t)
25263{
25264 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
25265}
25266
25267/*
25268 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
25269 * to work around bugs in some JS interpreters.
25270 */
25271function safe_add(x, y)
25272{
25273 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
25274 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
25275 return (msw << 16) | (lsw & 0xFFFF);
25276}
25277
25278/*
25279 * Bitwise rotate a 32-bit number to the left.
25280 */
25281function bit_rol(num, cnt)
25282{
25283 return (num << cnt) | (num >>> (32 - cnt));
25284}
25285
25286module.exports = function md5(buf) {
25287 return helpers.hash(buf, core_md5, 16);
25288};}, {"./helpers":151}],151: [function (exports, require, module, global) {'use strict';
25289var intSize = 4;
25290var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
25291var chrsz = 8;
25292
25293function toArray(buf, bigEndian) {
25294 if ((buf.length % intSize) !== 0) {
25295 var len = buf.length + (intSize - (buf.length % intSize));
25296 buf = Buffer.concat([buf, zeroBuffer], len);
25297 }
25298
25299 var arr = [];
25300 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
25301 for (var i = 0; i < buf.length; i += intSize) {
25302 arr.push(fn.call(buf, i));
25303 }
25304 return arr;
25305}
25306
25307function toBuffer(arr, size, bigEndian) {
25308 var buf = new Buffer(size);
25309 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
25310 for (var i = 0; i < arr.length; i++) {
25311 fn.call(buf, arr[i], i * 4, true);
25312 }
25313 return buf;
25314}
25315
25316function hash(buf, fn, hashSize, bigEndian) {
25317 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
25318 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
25319 return toBuffer(arr, hashSize, bigEndian);
25320}
25321exports.hash = hash;}, {}],152: [function (exports, require, module, global) {/*
25322CryptoJS v3.1.2
25323code.google.com/p/crypto-js
25324(c) 2009-2013 by Jeff Mott. All rights reserved.
25325code.google.com/p/crypto-js/wiki/License
25326*/
25327/** @preserve
25328(c) 2012 by Cédric Mesnil. All rights reserved.
25329
25330Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
25331
25332 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
25333 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
25334
25335THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25336*/
25337
25338// constants table
25339var zl = [
25340 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
25341 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
25342 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
25343 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
25344 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
25345]
25346
25347var zr = [
25348 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
25349 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
25350 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
25351 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
25352 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
25353]
25354
25355var sl = [
25356 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
25357 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
25358 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
25359 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
25360 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
25361]
25362
25363var sr = [
25364 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
25365 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
25366 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
25367 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
25368 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
25369]
25370
25371var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
25372var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
25373
25374function bytesToWords (bytes) {
25375 var words = []
25376 for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
25377 words[b >>> 5] |= bytes[i] << (24 - b % 32)
25378 }
25379 return words
25380}
25381
25382function wordsToBytes (words) {
25383 var bytes = []
25384 for (var b = 0; b < words.length * 32; b += 8) {
25385 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF)
25386 }
25387 return bytes
25388}
25389
25390function processBlock (H, M, offset) {
25391 // swap endian
25392 for (var i = 0; i < 16; i++) {
25393 var offset_i = offset + i
25394 var M_offset_i = M[offset_i]
25395
25396 // Swap
25397 M[offset_i] = (
25398 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
25399 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
25400 )
25401 }
25402
25403 // Working variables
25404 var al, bl, cl, dl, el
25405 var ar, br, cr, dr, er
25406
25407 ar = al = H[0]
25408 br = bl = H[1]
25409 cr = cl = H[2]
25410 dr = dl = H[3]
25411 er = el = H[4]
25412
25413 // computation
25414 var t
25415 for (i = 0; i < 80; i += 1) {
25416 t = (al + M[offset + zl[i]]) | 0
25417 if (i < 16) {
25418 t += f1(bl, cl, dl) + hl[0]
25419 } else if (i < 32) {
25420 t += f2(bl, cl, dl) + hl[1]
25421 } else if (i < 48) {
25422 t += f3(bl, cl, dl) + hl[2]
25423 } else if (i < 64) {
25424 t += f4(bl, cl, dl) + hl[3]
25425 } else {// if (i<80) {
25426 t += f5(bl, cl, dl) + hl[4]
25427 }
25428 t = t | 0
25429 t = rotl(t, sl[i])
25430 t = (t + el) | 0
25431 al = el
25432 el = dl
25433 dl = rotl(cl, 10)
25434 cl = bl
25435 bl = t
25436
25437 t = (ar + M[offset + zr[i]]) | 0
25438 if (i < 16) {
25439 t += f5(br, cr, dr) + hr[0]
25440 } else if (i < 32) {
25441 t += f4(br, cr, dr) + hr[1]
25442 } else if (i < 48) {
25443 t += f3(br, cr, dr) + hr[2]
25444 } else if (i < 64) {
25445 t += f2(br, cr, dr) + hr[3]
25446 } else {// if (i<80) {
25447 t += f1(br, cr, dr) + hr[4]
25448 }
25449
25450 t = t | 0
25451 t = rotl(t, sr[i])
25452 t = (t + er) | 0
25453 ar = er
25454 er = dr
25455 dr = rotl(cr, 10)
25456 cr = br
25457 br = t
25458 }
25459
25460 // intermediate hash value
25461 t = (H[1] + cl + dr) | 0
25462 H[1] = (H[2] + dl + er) | 0
25463 H[2] = (H[3] + el + ar) | 0
25464 H[3] = (H[4] + al + br) | 0
25465 H[4] = (H[0] + bl + cr) | 0
25466 H[0] = t
25467}
25468
25469function f1 (x, y, z) {
25470 return ((x) ^ (y) ^ (z))
25471}
25472
25473function f2 (x, y, z) {
25474 return (((x) & (y)) | ((~x) & (z)))
25475}
25476
25477function f3 (x, y, z) {
25478 return (((x) | (~(y))) ^ (z))
25479}
25480
25481function f4 (x, y, z) {
25482 return (((x) & (z)) | ((y) & (~(z))))
25483}
25484
25485function f5 (x, y, z) {
25486 return ((x) ^ ((y) | (~(z))))
25487}
25488
25489function rotl (x, n) {
25490 return (x << n) | (x >>> (32 - n))
25491}
25492
25493function ripemd160 (message) {
25494 var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
25495
25496 if (typeof message === 'string') {
25497 message = new Buffer(message, 'utf8')
25498 }
25499
25500 var m = bytesToWords(message)
25501
25502 var nBitsLeft = message.length * 8
25503 var nBitsTotal = message.length * 8
25504
25505 // Add padding
25506 m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
25507 m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
25508 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
25509 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
25510 )
25511
25512 for (var i = 0; i < m.length; i += 16) {
25513 processBlock(H, m, i)
25514 }
25515
25516 // swap endian
25517 for (i = 0; i < 5; i++) {
25518 // shortcut
25519 var H_i = H[i]
25520
25521 // Swap
25522 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
25523 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
25524 }
25525
25526 var digestbytes = wordsToBytes(H)
25527 return new Buffer(digestbytes)
25528}
25529
25530module.exports = ripemd160
25531}, {}],153: [function (exports, require, module, global) {var exports = module.exports = function SHA (algorithm) {
25532 algorithm = algorithm.toLowerCase()
25533
25534 var Algorithm = exports[algorithm]
25535 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
25536
25537 return new Algorithm()
25538}
25539
25540exports.sha = require('./sha')
25541exports.sha1 = require('./sha1')
25542exports.sha224 = require('./sha224')
25543exports.sha256 = require('./sha256')
25544exports.sha384 = require('./sha384')
25545exports.sha512 = require('./sha512')
25546}, {"./sha":154,"./sha1":156,"./sha224":157,"./sha256":158,"./sha384":159,"./sha512":160}],154: [function (exports, require, module, global) {/*
25547 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
25548 * in FIPS PUB 180-1
25549 * This source code is derived from sha1.js of the same repository.
25550 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
25551 * operation was added.
25552 */
25553
25554var inherits = require('inherits')
25555var Hash = require('./hash')
25556
25557var W = new Array(80)
25558
25559function Sha () {
25560 this.init()
25561 this._w = W
25562
25563 Hash.call(this, 64, 56)
25564}
25565
25566inherits(Sha, Hash)
25567
25568Sha.prototype.init = function () {
25569 this._a = 0x67452301 | 0
25570 this._b = 0xefcdab89 | 0
25571 this._c = 0x98badcfe | 0
25572 this._d = 0x10325476 | 0
25573 this._e = 0xc3d2e1f0 | 0
25574
25575 return this
25576}
25577
25578/*
25579 * Bitwise rotate a 32-bit number to the left.
25580 */
25581function rol (num, cnt) {
25582 return (num << cnt) | (num >>> (32 - cnt))
25583}
25584
25585Sha.prototype._update = function (M) {
25586 var W = this._w
25587
25588 var a = this._a
25589 var b = this._b
25590 var c = this._c
25591 var d = this._d
25592 var e = this._e
25593
25594 var j = 0
25595 var k
25596
25597 /*
25598 * SHA-1 has a bitwise rotate left operation. But, SHA is not
25599 * function calcW() { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
25600 */
25601 function calcW () { return W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16] }
25602 function loop (w, f) {
25603 W[j] = w
25604
25605 var t = rol(a, 5) + f + e + w + k
25606
25607 e = d
25608 d = c
25609 c = rol(b, 30)
25610 b = a
25611 a = t
25612 j++
25613 }
25614
25615 k = 1518500249
25616 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d))
25617 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
25618 k = 1859775393
25619 while (j < 40) loop(calcW(), b ^ c ^ d)
25620 k = -1894007588
25621 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
25622 k = -899497514
25623 while (j < 80) loop(calcW(), b ^ c ^ d)
25624
25625 this._a = (a + this._a) | 0
25626 this._b = (b + this._b) | 0
25627 this._c = (c + this._c) | 0
25628 this._d = (d + this._d) | 0
25629 this._e = (e + this._e) | 0
25630}
25631
25632Sha.prototype._hash = function () {
25633 var H = new Buffer(20)
25634
25635 H.writeInt32BE(this._a | 0, 0)
25636 H.writeInt32BE(this._b | 0, 4)
25637 H.writeInt32BE(this._c | 0, 8)
25638 H.writeInt32BE(this._d | 0, 12)
25639 H.writeInt32BE(this._e | 0, 16)
25640
25641 return H
25642}
25643
25644module.exports = Sha
25645
25646}, {"inherits":149,"./hash":155}],155: [function (exports, require, module, global) {// prototype class for hash functions
25647function Hash (blockSize, finalSize) {
25648 this._block = new Buffer(blockSize)
25649 this._finalSize = finalSize
25650 this._blockSize = blockSize
25651 this._len = 0
25652 this._s = 0
25653}
25654
25655Hash.prototype.update = function (data, enc) {
25656 if (typeof data === 'string') {
25657 enc = enc || 'utf8'
25658 data = new Buffer(data, enc)
25659 }
25660
25661 var l = this._len += data.length
25662 var s = this._s || 0
25663 var f = 0
25664 var buffer = this._block
25665
25666 while (s < l) {
25667 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
25668 var ch = (t - f)
25669
25670 for (var i = 0; i < ch; i++) {
25671 buffer[(s % this._blockSize) + i] = data[i + f]
25672 }
25673
25674 s += ch
25675 f += ch
25676
25677 if ((s % this._blockSize) === 0) {
25678 this._update(buffer)
25679 }
25680 }
25681 this._s = s
25682
25683 return this
25684}
25685
25686Hash.prototype.digest = function (enc) {
25687 // Suppose the length of the message M, in bits, is l
25688 var l = this._len * 8
25689
25690 // Append the bit 1 to the end of the message
25691 this._block[this._len % this._blockSize] = 0x80
25692
25693 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
25694 this._block.fill(0, this._len % this._blockSize + 1)
25695
25696 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
25697 this._update(this._block)
25698 this._block.fill(0)
25699 }
25700
25701 // to this append the block which is equal to the number l written in binary
25702 // TODO: handle case where l is > Math.pow(2, 29)
25703 this._block.writeInt32BE(l, this._blockSize - 4)
25704
25705 var hash = this._update(this._block) || this._hash()
25706
25707 return enc ? hash.toString(enc) : hash
25708}
25709
25710Hash.prototype._update = function () {
25711 throw new Error('_update must be implemented by subclass')
25712}
25713
25714module.exports = Hash
25715}, {}],156: [function (exports, require, module, global) {/*
25716 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
25717 * in FIPS PUB 180-1
25718 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
25719 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25720 * Distributed under the BSD License
25721 * See http://pajhome.org.uk/crypt/md5 for details.
25722 */
25723
25724var inherits = require('inherits')
25725var Hash = require('./hash')
25726
25727var W = new Array(80)
25728
25729function Sha1 () {
25730 this.init()
25731 this._w = W
25732
25733 Hash.call(this, 64, 56)
25734}
25735
25736inherits(Sha1, Hash)
25737
25738Sha1.prototype.init = function () {
25739 this._a = 0x67452301 | 0
25740 this._b = 0xefcdab89 | 0
25741 this._c = 0x98badcfe | 0
25742 this._d = 0x10325476 | 0
25743 this._e = 0xc3d2e1f0 | 0
25744
25745 return this
25746}
25747
25748/*
25749 * Bitwise rotate a 32-bit number to the left.
25750 */
25751function rol (num, cnt) {
25752 return (num << cnt) | (num >>> (32 - cnt))
25753}
25754
25755Sha1.prototype._update = function (M) {
25756 var W = this._w
25757
25758 var a = this._a
25759 var b = this._b
25760 var c = this._c
25761 var d = this._d
25762 var e = this._e
25763
25764 var j = 0
25765 var k
25766
25767 function calcW () { return rol(W[j - 3] ^ W[j - 8] ^ W[j - 14] ^ W[j - 16], 1) }
25768 function loop (w, f) {
25769 W[j] = w
25770
25771 var t = rol(a, 5) + f + e + w + k
25772
25773 e = d
25774 d = c
25775 c = rol(b, 30)
25776 b = a
25777 a = t
25778 j++
25779 }
25780
25781 k = 1518500249
25782 while (j < 16) loop(M.readInt32BE(j * 4), (b & c) | ((~b) & d))
25783 while (j < 20) loop(calcW(), (b & c) | ((~b) & d))
25784 k = 1859775393
25785 while (j < 40) loop(calcW(), b ^ c ^ d)
25786 k = -1894007588
25787 while (j < 60) loop(calcW(), (b & c) | (b & d) | (c & d))
25788 k = -899497514
25789 while (j < 80) loop(calcW(), b ^ c ^ d)
25790
25791 this._a = (a + this._a) | 0
25792 this._b = (b + this._b) | 0
25793 this._c = (c + this._c) | 0
25794 this._d = (d + this._d) | 0
25795 this._e = (e + this._e) | 0
25796}
25797
25798Sha1.prototype._hash = function () {
25799 var H = new Buffer(20)
25800
25801 H.writeInt32BE(this._a | 0, 0)
25802 H.writeInt32BE(this._b | 0, 4)
25803 H.writeInt32BE(this._c | 0, 8)
25804 H.writeInt32BE(this._d | 0, 12)
25805 H.writeInt32BE(this._e | 0, 16)
25806
25807 return H
25808}
25809
25810module.exports = Sha1
25811}, {"inherits":149,"./hash":155}],157: [function (exports, require, module, global) {/**
25812 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
25813 * in FIPS 180-2
25814 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
25815 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25816 *
25817 */
25818
25819var inherits = require('inherits')
25820var Sha256 = require('./sha256')
25821var Hash = require('./hash')
25822
25823var W = new Array(64)
25824
25825function Sha224 () {
25826 this.init()
25827
25828 this._w = W // new Array(64)
25829
25830 Hash.call(this, 64, 56)
25831}
25832
25833inherits(Sha224, Sha256)
25834
25835Sha224.prototype.init = function () {
25836 this._a = 0xc1059ed8 | 0
25837 this._b = 0x367cd507 | 0
25838 this._c = 0x3070dd17 | 0
25839 this._d = 0xf70e5939 | 0
25840 this._e = 0xffc00b31 | 0
25841 this._f = 0x68581511 | 0
25842 this._g = 0x64f98fa7 | 0
25843 this._h = 0xbefa4fa4 | 0
25844
25845 return this
25846}
25847
25848Sha224.prototype._hash = function () {
25849 var H = new Buffer(28)
25850
25851 H.writeInt32BE(this._a, 0)
25852 H.writeInt32BE(this._b, 4)
25853 H.writeInt32BE(this._c, 8)
25854 H.writeInt32BE(this._d, 12)
25855 H.writeInt32BE(this._e, 16)
25856 H.writeInt32BE(this._f, 20)
25857 H.writeInt32BE(this._g, 24)
25858
25859 return H
25860}
25861
25862module.exports = Sha224
25863}, {"inherits":149,"./sha256":158,"./hash":155}],158: [function (exports, require, module, global) {/**
25864 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
25865 * in FIPS 180-2
25866 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
25867 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25868 *
25869 */
25870
25871var inherits = require('inherits')
25872var Hash = require('./hash')
25873
25874var K = [
25875 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
25876 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
25877 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
25878 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
25879 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
25880 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
25881 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
25882 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
25883 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
25884 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
25885 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
25886 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
25887 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
25888 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
25889 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
25890 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
25891]
25892
25893var W = new Array(64)
25894
25895function Sha256 () {
25896 this.init()
25897
25898 this._w = W // new Array(64)
25899
25900 Hash.call(this, 64, 56)
25901}
25902
25903inherits(Sha256, Hash)
25904
25905Sha256.prototype.init = function () {
25906 this._a = 0x6a09e667 | 0
25907 this._b = 0xbb67ae85 | 0
25908 this._c = 0x3c6ef372 | 0
25909 this._d = 0xa54ff53a | 0
25910 this._e = 0x510e527f | 0
25911 this._f = 0x9b05688c | 0
25912 this._g = 0x1f83d9ab | 0
25913 this._h = 0x5be0cd19 | 0
25914
25915 return this
25916}
25917
25918function Ch (x, y, z) {
25919 return z ^ (x & (y ^ z))
25920}
25921
25922function Maj (x, y, z) {
25923 return (x & y) | (z & (x | y))
25924}
25925
25926function Sigma0 (x) {
25927 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
25928}
25929
25930function Sigma1 (x) {
25931 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
25932}
25933
25934function Gamma0 (x) {
25935 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
25936}
25937
25938function Gamma1 (x) {
25939 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
25940}
25941
25942Sha256.prototype._update = function (M) {
25943 var W = this._w
25944
25945 var a = this._a | 0
25946 var b = this._b | 0
25947 var c = this._c | 0
25948 var d = this._d | 0
25949 var e = this._e | 0
25950 var f = this._f | 0
25951 var g = this._g | 0
25952 var h = this._h | 0
25953
25954 var j = 0
25955
25956 function calcW () { return Gamma1(W[j - 2]) + W[j - 7] + Gamma0(W[j - 15]) + W[j - 16] }
25957 function loop (w) {
25958 W[j] = w
25959
25960 var T1 = h + Sigma1(e) + Ch(e, f, g) + K[j] + w
25961 var T2 = Sigma0(a) + Maj(a, b, c)
25962
25963 h = g
25964 g = f
25965 f = e
25966 e = d + T1
25967 d = c
25968 c = b
25969 b = a
25970 a = T1 + T2
25971
25972 j++
25973 }
25974
25975 while (j < 16) loop(M.readInt32BE(j * 4))
25976 while (j < 64) loop(calcW())
25977
25978 this._a = (a + this._a) | 0
25979 this._b = (b + this._b) | 0
25980 this._c = (c + this._c) | 0
25981 this._d = (d + this._d) | 0
25982 this._e = (e + this._e) | 0
25983 this._f = (f + this._f) | 0
25984 this._g = (g + this._g) | 0
25985 this._h = (h + this._h) | 0
25986}
25987
25988Sha256.prototype._hash = function () {
25989 var H = new Buffer(32)
25990
25991 H.writeInt32BE(this._a, 0)
25992 H.writeInt32BE(this._b, 4)
25993 H.writeInt32BE(this._c, 8)
25994 H.writeInt32BE(this._d, 12)
25995 H.writeInt32BE(this._e, 16)
25996 H.writeInt32BE(this._f, 20)
25997 H.writeInt32BE(this._g, 24)
25998 H.writeInt32BE(this._h, 28)
25999
26000 return H
26001}
26002
26003module.exports = Sha256
26004}, {"inherits":149,"./hash":155}],159: [function (exports, require, module, global) {var inherits = require('inherits')
26005var SHA512 = require('./sha512')
26006var Hash = require('./hash')
26007
26008var W = new Array(160)
26009
26010function Sha384 () {
26011 this.init()
26012 this._w = W
26013
26014 Hash.call(this, 128, 112)
26015}
26016
26017inherits(Sha384, SHA512)
26018
26019Sha384.prototype.init = function () {
26020 this._a = 0xcbbb9d5d | 0
26021 this._b = 0x629a292a | 0
26022 this._c = 0x9159015a | 0
26023 this._d = 0x152fecd8 | 0
26024 this._e = 0x67332667 | 0
26025 this._f = 0x8eb44a87 | 0
26026 this._g = 0xdb0c2e0d | 0
26027 this._h = 0x47b5481d | 0
26028
26029 this._al = 0xc1059ed8 | 0
26030 this._bl = 0x367cd507 | 0
26031 this._cl = 0x3070dd17 | 0
26032 this._dl = 0xf70e5939 | 0
26033 this._el = 0xffc00b31 | 0
26034 this._fl = 0x68581511 | 0
26035 this._gl = 0x64f98fa7 | 0
26036 this._hl = 0xbefa4fa4 | 0
26037
26038 return this
26039}
26040
26041Sha384.prototype._hash = function () {
26042 var H = new Buffer(48)
26043
26044 function writeInt64BE (h, l, offset) {
26045 H.writeInt32BE(h, offset)
26046 H.writeInt32BE(l, offset + 4)
26047 }
26048
26049 writeInt64BE(this._a, this._al, 0)
26050 writeInt64BE(this._b, this._bl, 8)
26051 writeInt64BE(this._c, this._cl, 16)
26052 writeInt64BE(this._d, this._dl, 24)
26053 writeInt64BE(this._e, this._el, 32)
26054 writeInt64BE(this._f, this._fl, 40)
26055
26056 return H
26057}
26058
26059module.exports = Sha384
26060}, {"inherits":149,"./sha512":160,"./hash":155}],160: [function (exports, require, module, global) {var inherits = require('inherits')
26061var Hash = require('./hash')
26062
26063var K = [
26064 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
26065 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
26066 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
26067 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
26068 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
26069 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
26070 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
26071 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
26072 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
26073 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
26074 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
26075 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
26076 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
26077 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
26078 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
26079 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
26080 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
26081 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
26082 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
26083 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
26084 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
26085 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
26086 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
26087 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
26088 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
26089 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
26090 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
26091 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
26092 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
26093 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
26094 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
26095 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
26096 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
26097 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
26098 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
26099 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
26100 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
26101 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
26102 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
26103 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
26104]
26105
26106var W = new Array(160)
26107
26108function Sha512 () {
26109 this.init()
26110 this._w = W
26111
26112 Hash.call(this, 128, 112)
26113}
26114
26115inherits(Sha512, Hash)
26116
26117Sha512.prototype.init = function () {
26118 this._a = 0x6a09e667 | 0
26119 this._b = 0xbb67ae85 | 0
26120 this._c = 0x3c6ef372 | 0
26121 this._d = 0xa54ff53a | 0
26122 this._e = 0x510e527f | 0
26123 this._f = 0x9b05688c | 0
26124 this._g = 0x1f83d9ab | 0
26125 this._h = 0x5be0cd19 | 0
26126
26127 this._al = 0xf3bcc908 | 0
26128 this._bl = 0x84caa73b | 0
26129 this._cl = 0xfe94f82b | 0
26130 this._dl = 0x5f1d36f1 | 0
26131 this._el = 0xade682d1 | 0
26132 this._fl = 0x2b3e6c1f | 0
26133 this._gl = 0xfb41bd6b | 0
26134 this._hl = 0x137e2179 | 0
26135
26136 return this
26137}
26138
26139function Ch (x, y, z) {
26140 return z ^ (x & (y ^ z))
26141}
26142
26143function Maj (x, y, z) {
26144 return (x & y) | (z & (x | y))
26145}
26146
26147function Sigma0 (x, xl) {
26148 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
26149}
26150
26151function Sigma1 (x, xl) {
26152 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
26153}
26154
26155function Gamma0 (x, xl) {
26156 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
26157}
26158
26159function Gamma0l (x, xl) {
26160 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
26161}
26162
26163function Gamma1 (x, xl) {
26164 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
26165}
26166
26167function Gamma1l (x, xl) {
26168 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
26169}
26170
26171Sha512.prototype._update = function (M) {
26172 var W = this._w
26173
26174 var a = this._a | 0
26175 var b = this._b | 0
26176 var c = this._c | 0
26177 var d = this._d | 0
26178 var e = this._e | 0
26179 var f = this._f | 0
26180 var g = this._g | 0
26181 var h = this._h | 0
26182
26183 var al = this._al | 0
26184 var bl = this._bl | 0
26185 var cl = this._cl | 0
26186 var dl = this._dl | 0
26187 var el = this._el | 0
26188 var fl = this._fl | 0
26189 var gl = this._gl | 0
26190 var hl = this._hl | 0
26191
26192 var i = 0
26193 var j = 0
26194 var Wi, Wil
26195 function calcW () {
26196 var x = W[j - 15 * 2]
26197 var xl = W[j - 15 * 2 + 1]
26198 var gamma0 = Gamma0(x, xl)
26199 var gamma0l = Gamma0l(xl, x)
26200
26201 x = W[j - 2 * 2]
26202 xl = W[j - 2 * 2 + 1]
26203 var gamma1 = Gamma1(x, xl)
26204 var gamma1l = Gamma1l(xl, x)
26205
26206 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
26207 var Wi7 = W[j - 7 * 2]
26208 var Wi7l = W[j - 7 * 2 + 1]
26209
26210 var Wi16 = W[j - 16 * 2]
26211 var Wi16l = W[j - 16 * 2 + 1]
26212
26213 Wil = gamma0l + Wi7l
26214 Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0)
26215 Wil = Wil + gamma1l
26216 Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0)
26217 Wil = Wil + Wi16l
26218 Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0)
26219 }
26220
26221 function loop () {
26222 W[j] = Wi
26223 W[j + 1] = Wil
26224
26225 var maj = Maj(a, b, c)
26226 var majl = Maj(al, bl, cl)
26227
26228 var sigma0h = Sigma0(a, al)
26229 var sigma0l = Sigma0(al, a)
26230 var sigma1h = Sigma1(e, el)
26231 var sigma1l = Sigma1(el, e)
26232
26233 // t1 = h + sigma1 + ch + K[i] + W[i]
26234 var Ki = K[j]
26235 var Kil = K[j + 1]
26236
26237 var ch = Ch(e, f, g)
26238 var chl = Ch(el, fl, gl)
26239
26240 var t1l = hl + sigma1l
26241 var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0)
26242 t1l = t1l + chl
26243 t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0)
26244 t1l = t1l + Kil
26245 t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0)
26246 t1l = t1l + Wil
26247 t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0)
26248
26249 // t2 = sigma0 + maj
26250 var t2l = sigma0l + majl
26251 var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0)
26252
26253 h = g
26254 hl = gl
26255 g = f
26256 gl = fl
26257 f = e
26258 fl = el
26259 el = (dl + t1l) | 0
26260 e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
26261 d = c
26262 dl = cl
26263 c = b
26264 cl = bl
26265 b = a
26266 bl = al
26267 al = (t1l + t2l) | 0
26268 a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0
26269
26270 i++
26271 j += 2
26272 }
26273
26274 while (i < 16) {
26275 Wi = M.readInt32BE(j * 4)
26276 Wil = M.readInt32BE(j * 4 + 4)
26277
26278 loop()
26279 }
26280
26281 while (i < 80) {
26282 calcW()
26283 loop()
26284 }
26285
26286 this._al = (this._al + al) | 0
26287 this._bl = (this._bl + bl) | 0
26288 this._cl = (this._cl + cl) | 0
26289 this._dl = (this._dl + dl) | 0
26290 this._el = (this._el + el) | 0
26291 this._fl = (this._fl + fl) | 0
26292 this._gl = (this._gl + gl) | 0
26293 this._hl = (this._hl + hl) | 0
26294
26295 this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0
26296 this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0
26297 this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0
26298 this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
26299 this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0
26300 this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0
26301 this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0
26302 this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0
26303}
26304
26305Sha512.prototype._hash = function () {
26306 var H = new Buffer(64)
26307
26308 function writeInt64BE (h, l, offset) {
26309 H.writeInt32BE(h, offset)
26310 H.writeInt32BE(l, offset + 4)
26311 }
26312
26313 writeInt64BE(this._a, this._al, 0)
26314 writeInt64BE(this._b, this._bl, 8)
26315 writeInt64BE(this._c, this._cl, 16)
26316 writeInt64BE(this._d, this._dl, 24)
26317 writeInt64BE(this._e, this._el, 32)
26318 writeInt64BE(this._f, this._fl, 40)
26319 writeInt64BE(this._g, this._gl, 48)
26320 writeInt64BE(this._h, this._hl, 56)
26321
26322 return H
26323}
26324
26325module.exports = Sha512
26326}, {"inherits":149,"./hash":155}],161: [function (exports, require, module, global) {var Transform = require('stream').Transform
26327var inherits = require('inherits')
26328var StringDecoder = require('string_decoder').StringDecoder
26329module.exports = CipherBase
26330inherits(CipherBase, Transform)
26331function CipherBase (hashMode) {
26332 Transform.call(this)
26333 this.hashMode = typeof hashMode === 'string'
26334 if (this.hashMode) {
26335 this[hashMode] = this._finalOrDigest
26336 } else {
26337 this.final = this._finalOrDigest
26338 }
26339 this._decoder = null
26340 this._encoding = null
26341}
26342CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
26343 if (typeof data === 'string') {
26344 data = new Buffer(data, inputEnc)
26345 }
26346 var outData = this._update(data)
26347 if (this.hashMode) {
26348 return this
26349 }
26350 if (outputEnc) {
26351 outData = this._toString(outData, outputEnc)
26352 }
26353 return outData
26354}
26355
26356CipherBase.prototype.setAutoPadding = function () {}
26357
26358CipherBase.prototype.getAuthTag = function () {
26359 throw new Error('trying to get auth tag in unsupported state')
26360}
26361
26362CipherBase.prototype.setAuthTag = function () {
26363 throw new Error('trying to set auth tag in unsupported state')
26364}
26365
26366CipherBase.prototype.setAAD = function () {
26367 throw new Error('trying to set aad in unsupported state')
26368}
26369
26370CipherBase.prototype._transform = function (data, _, next) {
26371 var err
26372 try {
26373 if (this.hashMode) {
26374 this._update(data)
26375 } else {
26376 this.push(this._update(data))
26377 }
26378 } catch (e) {
26379 err = e
26380 } finally {
26381 next(err)
26382 }
26383}
26384CipherBase.prototype._flush = function (done) {
26385 var err
26386 try {
26387 this.push(this._final())
26388 } catch (e) {
26389 err = e
26390 } finally {
26391 done(err)
26392 }
26393}
26394CipherBase.prototype._finalOrDigest = function (outputEnc) {
26395 var outData = this._final() || new Buffer('')
26396 if (outputEnc) {
26397 outData = this._toString(outData, outputEnc, true)
26398 }
26399 return outData
26400}
26401
26402CipherBase.prototype._toString = function (value, enc, final) {
26403 if (!this._decoder) {
26404 this._decoder = new StringDecoder(enc)
26405 this._encoding = enc
26406 }
26407 if (this._encoding !== enc) {
26408 throw new Error('can\'t switch encodings')
26409 }
26410 var out = this._decoder.write(value)
26411 if (final) {
26412 out += this._decoder.end()
26413 }
26414 return out
26415}
26416}, {"stream":52,"inherits":149,"string_decoder":62}],162: [function (exports, require, module, global) {'use strict';
26417var createHash = require('create-hash/browser');
26418var inherits = require('inherits')
26419
26420var Transform = require('stream').Transform
26421
26422var ZEROS = new Buffer(128)
26423ZEROS.fill(0)
26424
26425function Hmac(alg, key) {
26426 Transform.call(this)
26427 alg = alg.toLowerCase()
26428 if (typeof key === 'string') {
26429 key = new Buffer(key)
26430 }
26431
26432 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
26433
26434 this._alg = alg
26435 this._key = key
26436
26437 if (key.length > blocksize) {
26438 key = createHash(alg).update(key).digest()
26439
26440 } else if (key.length < blocksize) {
26441 key = Buffer.concat([key, ZEROS], blocksize)
26442 }
26443
26444 var ipad = this._ipad = new Buffer(blocksize)
26445 var opad = this._opad = new Buffer(blocksize)
26446
26447 for (var i = 0; i < blocksize; i++) {
26448 ipad[i] = key[i] ^ 0x36
26449 opad[i] = key[i] ^ 0x5C
26450 }
26451
26452 this._hash = createHash(alg).update(ipad)
26453}
26454
26455inherits(Hmac, Transform)
26456
26457Hmac.prototype.update = function (data, enc) {
26458 this._hash.update(data, enc)
26459
26460 return this
26461}
26462
26463Hmac.prototype._transform = function (data, _, next) {
26464 this._hash.update(data)
26465
26466 next()
26467}
26468
26469Hmac.prototype._flush = function (next) {
26470 this.push(this.digest())
26471
26472 next()
26473}
26474
26475Hmac.prototype.digest = function (enc) {
26476 var h = this._hash.digest()
26477
26478 return createHash(this._alg).update(this._opad).update(h).digest(enc)
26479}
26480
26481module.exports = function createHmac(alg, key) {
26482 return new Hmac(alg, key)
26483}
26484}, {"create-hash/browser":148,"inherits":149,"stream":52}],163: [function (exports, require, module, global) {'use strict'
26485exports['RSA-SHA224'] = exports.sha224WithRSAEncryption = {
26486 sign: 'rsa',
26487 hash: 'sha224',
26488 id: new Buffer('302d300d06096086480165030402040500041c', 'hex')
26489}
26490exports['RSA-SHA256'] = exports.sha256WithRSAEncryption = {
26491 sign: 'rsa',
26492 hash: 'sha256',
26493 id: new Buffer('3031300d060960864801650304020105000420', 'hex')
26494}
26495exports['RSA-SHA384'] = exports.sha384WithRSAEncryption = {
26496 sign: 'rsa',
26497 hash: 'sha384',
26498 id: new Buffer('3041300d060960864801650304020205000430', 'hex')
26499}
26500exports['RSA-SHA512'] = exports.sha512WithRSAEncryption = {
26501 sign: 'rsa',
26502 hash: 'sha512',
26503 id: new Buffer('3051300d060960864801650304020305000440', 'hex')
26504}
26505exports['RSA-SHA1'] = {
26506 sign: 'rsa',
26507 hash: 'sha1',
26508 id: new Buffer('3021300906052b0e03021a05000414', 'hex')
26509}
26510exports['ecdsa-with-SHA1'] = {
26511 sign: 'ecdsa',
26512 hash: 'sha1',
26513 id: new Buffer('', 'hex')
26514}
26515exports.DSA = exports['DSA-SHA1'] = exports['DSA-SHA'] = {
26516 sign: 'dsa',
26517 hash: 'sha1',
26518 id: new Buffer('', 'hex')
26519}
26520exports['DSA-SHA224'] = exports['DSA-WITH-SHA224'] = {
26521 sign: 'dsa',
26522 hash: 'sha224',
26523 id: new Buffer('', 'hex')
26524}
26525exports['DSA-SHA256'] = exports['DSA-WITH-SHA256'] = {
26526 sign: 'dsa',
26527 hash: 'sha256',
26528 id: new Buffer('', 'hex')
26529}
26530exports['DSA-SHA384'] = exports['DSA-WITH-SHA384'] = {
26531 sign: 'dsa',
26532 hash: 'sha384',
26533 id: new Buffer('', 'hex')
26534}
26535exports['DSA-SHA512'] = exports['DSA-WITH-SHA512'] = {
26536 sign: 'dsa',
26537 hash: 'sha512',
26538 id: new Buffer('', 'hex')
26539}
26540exports['DSA-RIPEMD160'] = {
26541 sign: 'dsa',
26542 hash: 'rmd160',
26543 id: new Buffer('', 'hex')
26544}
26545exports['RSA-RIPEMD160'] = exports.ripemd160WithRSA = {
26546 sign: 'rsa',
26547 hash: 'rmd160',
26548 id: new Buffer('3021300906052b2403020105000414', 'hex')
26549}
26550exports['RSA-MD5'] = exports.md5WithRSAEncryption = {
26551 sign: 'rsa',
26552 hash: 'md5',
26553 id: new Buffer('3020300c06082a864886f70d020505000410', 'hex')
26554}
26555}, {}],164: [function (exports, require, module, global) {var createHmac = require('create-hmac')
26556var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
26557
26558exports.pbkdf2 = pbkdf2
26559function pbkdf2 (password, salt, iterations, keylen, digest, callback) {
26560 if (typeof digest === 'function') {
26561 callback = digest
26562 digest = undefined
26563 }
26564
26565 if (typeof callback !== 'function') {
26566 throw new Error('No callback provided to pbkdf2')
26567 }
26568
26569 var result = pbkdf2Sync(password, salt, iterations, keylen, digest)
26570 setTimeout(function () {
26571 callback(undefined, result)
26572 })
26573}
26574
26575exports.pbkdf2Sync = pbkdf2Sync
26576function pbkdf2Sync (password, salt, iterations, keylen, digest) {
26577 if (typeof iterations !== 'number') {
26578 throw new TypeError('Iterations not a number')
26579 }
26580
26581 if (iterations < 0) {
26582 throw new TypeError('Bad iterations')
26583 }
26584
26585 if (typeof keylen !== 'number') {
26586 throw new TypeError('Key length not a number')
26587 }
26588
26589 if (keylen < 0 || keylen > MAX_ALLOC) {
26590 throw new TypeError('Bad key length')
26591 }
26592
26593 digest = digest || 'sha1'
26594
26595 if (!Buffer.isBuffer(password)) password = new Buffer(password, 'binary')
26596 if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, 'binary')
26597
26598 var hLen
26599 var l = 1
26600 var DK = new Buffer(keylen)
26601 var block1 = new Buffer(salt.length + 4)
26602 salt.copy(block1, 0, 0, salt.length)
26603
26604 var r
26605 var T
26606
26607 for (var i = 1; i <= l; i++) {
26608 block1.writeUInt32BE(i, salt.length)
26609 var U = createHmac(digest, password).update(block1).digest()
26610
26611 if (!hLen) {
26612 hLen = U.length
26613 T = new Buffer(hLen)
26614 l = Math.ceil(keylen / hLen)
26615 r = keylen - (l - 1) * hLen
26616 }
26617
26618 U.copy(T, 0, 0, hLen)
26619
26620 for (var j = 1; j < iterations; j++) {
26621 U = createHmac(digest, password).update(U).digest()
26622
26623 for (var k = 0; k < hLen; k++) {
26624 T[k] ^= U[k]
26625 }
26626 }
26627
26628 var destPos = (i - 1) * hLen
26629 var len = (i === l ? r : hLen)
26630 T.copy(DK, destPos, 0, len)
26631 }
26632
26633 return DK
26634}
26635}, {"create-hmac":162}],165: [function (exports, require, module, global) {var ebtk = require('evp_bytestokey')
26636var aes = require('browserify-aes/browser')
26637var DES = require('browserify-des')
26638var desModes = require('browserify-des/modes')
26639var aesModes = require('browserify-aes/modes')
26640function createCipher (suite, password) {
26641 var keyLen, ivLen
26642 suite = suite.toLowerCase()
26643 if (aesModes[suite]) {
26644 keyLen = aesModes[suite].key
26645 ivLen = aesModes[suite].iv
26646 } else if (desModes[suite]) {
26647 keyLen = desModes[suite].key * 8
26648 ivLen = desModes[suite].iv
26649 } else {
26650 throw new TypeError('invalid suite type')
26651 }
26652 var keys = ebtk(password, false, keyLen, ivLen)
26653 return createCipheriv(suite, keys.key, keys.iv)
26654}
26655function createDecipher (suite, password) {
26656 var keyLen, ivLen
26657 suite = suite.toLowerCase()
26658 if (aesModes[suite]) {
26659 keyLen = aesModes[suite].key
26660 ivLen = aesModes[suite].iv
26661 } else if (desModes[suite]) {
26662 keyLen = desModes[suite].key * 8
26663 ivLen = desModes[suite].iv
26664 } else {
26665 throw new TypeError('invalid suite type')
26666 }
26667 var keys = ebtk(password, false, keyLen, ivLen)
26668 return createDecipheriv(suite, keys.key, keys.iv)
26669}
26670
26671function createCipheriv (suite, key, iv) {
26672 suite = suite.toLowerCase()
26673 if (aesModes[suite]) {
26674 return aes.createCipheriv(suite, key, iv)
26675 } else if (desModes[suite]) {
26676 return new DES({
26677 key: key,
26678 iv: iv,
26679 mode: suite
26680 })
26681 } else {
26682 throw new TypeError('invalid suite type')
26683 }
26684}
26685function createDecipheriv (suite, key, iv) {
26686 suite = suite.toLowerCase()
26687 if (aesModes[suite]) {
26688 return aes.createDecipheriv(suite, key, iv)
26689 } else if (desModes[suite]) {
26690 return new DES({
26691 key: key,
26692 iv: iv,
26693 mode: suite,
26694 decrypt: true
26695 })
26696 } else {
26697 throw new TypeError('invalid suite type')
26698 }
26699}
26700exports.createCipher = exports.Cipher = createCipher
26701exports.createCipheriv = exports.Cipheriv = createCipheriv
26702exports.createDecipher = exports.Decipher = createDecipher
26703exports.createDecipheriv = exports.Decipheriv = createDecipheriv
26704function getCiphers () {
26705 return Object.keys(desModes).concat(aes.getCiphers())
26706}
26707exports.listCiphers = exports.getCiphers = getCiphers
26708}, {"evp_bytestokey":166,"browserify-aes/browser":167,"browserify-des":184,"browserify-des/modes":193,"browserify-aes/modes":171}],166: [function (exports, require, module, global) {var md5 = require('create-hash/md5')
26709module.exports = EVP_BytesToKey
26710function EVP_BytesToKey (password, salt, keyLen, ivLen) {
26711 if (!Buffer.isBuffer(password)) {
26712 password = new Buffer(password, 'binary')
26713 }
26714 if (salt && !Buffer.isBuffer(salt)) {
26715 salt = new Buffer(salt, 'binary')
26716 }
26717 keyLen = keyLen / 8
26718 ivLen = ivLen || 0
26719 var ki = 0
26720 var ii = 0
26721 var key = new Buffer(keyLen)
26722 var iv = new Buffer(ivLen)
26723 var addmd = 0
26724 var md_buf
26725 var i
26726 var bufs = []
26727 while (true) {
26728 if (addmd++ > 0) {
26729 bufs.push(md_buf)
26730 }
26731 bufs.push(password)
26732 if (salt) {
26733 bufs.push(salt)
26734 }
26735 md_buf = md5(Buffer.concat(bufs))
26736 bufs = []
26737 i = 0
26738 if (keyLen > 0) {
26739 while (true) {
26740 if (keyLen === 0) {
26741 break
26742 }
26743 if (i === md_buf.length) {
26744 break
26745 }
26746 key[ki++] = md_buf[i]
26747 keyLen--
26748 i++
26749 }
26750 }
26751 if (ivLen > 0 && i !== md_buf.length) {
26752 while (true) {
26753 if (ivLen === 0) {
26754 break
26755 }
26756 if (i === md_buf.length) {
26757 break
26758 }
26759 iv[ii++] = md_buf[i]
26760 ivLen--
26761 i++
26762 }
26763 }
26764 if (keyLen === 0 && ivLen === 0) {
26765 break
26766 }
26767 }
26768 for (i = 0; i < md_buf.length; i++) {
26769 md_buf[i] = 0
26770 }
26771 return {
26772 key: key,
26773 iv: iv
26774 }
26775}
26776}, {"create-hash/md5":150}],167: [function (exports, require, module, global) {var ciphers = require('./encrypter')
26777exports.createCipher = exports.Cipher = ciphers.createCipher
26778exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
26779var deciphers = require('./decrypter')
26780exports.createDecipher = exports.Decipher = deciphers.createDecipher
26781exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
26782var modes = require('./modes')
26783function getCiphers () {
26784 return Object.keys(modes)
26785}
26786exports.listCiphers = exports.getCiphers = getCiphers
26787}, {"./encrypter":168,"./decrypter":183,"./modes":171}],168: [function (exports, require, module, global) {var aes = require('./aes')
26788var Transform = require('cipher-base')
26789var inherits = require('inherits')
26790var modes = require('./modes')
26791var ebtk = require('evp_bytestokey')
26792var StreamCipher = require('./streamCipher')
26793var AuthCipher = require('./authCipher')
26794inherits(Cipher, Transform)
26795function Cipher (mode, key, iv) {
26796 if (!(this instanceof Cipher)) {
26797 return new Cipher(mode, key, iv)
26798 }
26799 Transform.call(this)
26800 this._cache = new Splitter()
26801 this._cipher = new aes.AES(key)
26802 this._prev = new Buffer(iv.length)
26803 iv.copy(this._prev)
26804 this._mode = mode
26805 this._autopadding = true
26806}
26807Cipher.prototype._update = function (data) {
26808 this._cache.add(data)
26809 var chunk
26810 var thing
26811 var out = []
26812 while ((chunk = this._cache.get())) {
26813 thing = this._mode.encrypt(this, chunk)
26814 out.push(thing)
26815 }
26816 return Buffer.concat(out)
26817}
26818Cipher.prototype._final = function () {
26819 var chunk = this._cache.flush()
26820 if (this._autopadding) {
26821 chunk = this._mode.encrypt(this, chunk)
26822 this._cipher.scrub()
26823 return chunk
26824 } else if (chunk.toString('hex') !== '10101010101010101010101010101010') {
26825 this._cipher.scrub()
26826 throw new Error('data not multiple of block length')
26827 }
26828}
26829Cipher.prototype.setAutoPadding = function (setTo) {
26830 this._autopadding = !!setTo
26831}
26832
26833function Splitter () {
26834 if (!(this instanceof Splitter)) {
26835 return new Splitter()
26836 }
26837 this.cache = new Buffer('')
26838}
26839Splitter.prototype.add = function (data) {
26840 this.cache = Buffer.concat([this.cache, data])
26841}
26842
26843Splitter.prototype.get = function () {
26844 if (this.cache.length > 15) {
26845 var out = this.cache.slice(0, 16)
26846 this.cache = this.cache.slice(16)
26847 return out
26848 }
26849 return null
26850}
26851Splitter.prototype.flush = function () {
26852 var len = 16 - this.cache.length
26853 var padBuff = new Buffer(len)
26854
26855 var i = -1
26856 while (++i < len) {
26857 padBuff.writeUInt8(len, i)
26858 }
26859 var out = Buffer.concat([this.cache, padBuff])
26860 return out
26861}
26862var modelist = {
26863 ECB: require('./modes/ecb'),
26864 CBC: require('./modes/cbc'),
26865 CFB: require('./modes/cfb'),
26866 CFB8: require('./modes/cfb8'),
26867 CFB1: require('./modes/cfb1'),
26868 OFB: require('./modes/ofb'),
26869 CTR: require('./modes/ctr'),
26870 GCM: require('./modes/ctr')
26871}
26872
26873function createCipheriv (suite, password, iv) {
26874 var config = modes[suite.toLowerCase()]
26875 if (!config) {
26876 throw new TypeError('invalid suite type')
26877 }
26878 if (typeof iv === 'string') {
26879 iv = new Buffer(iv)
26880 }
26881 if (typeof password === 'string') {
26882 password = new Buffer(password)
26883 }
26884 if (password.length !== config.key / 8) {
26885 throw new TypeError('invalid key length ' + password.length)
26886 }
26887 if (iv.length !== config.iv) {
26888 throw new TypeError('invalid iv length ' + iv.length)
26889 }
26890 if (config.type === 'stream') {
26891 return new StreamCipher(modelist[config.mode], password, iv)
26892 } else if (config.type === 'auth') {
26893 return new AuthCipher(modelist[config.mode], password, iv)
26894 }
26895 return new Cipher(modelist[config.mode], password, iv)
26896}
26897function createCipher (suite, password) {
26898 var config = modes[suite.toLowerCase()]
26899 if (!config) {
26900 throw new TypeError('invalid suite type')
26901 }
26902 var keys = ebtk(password, false, config.key, config.iv)
26903 return createCipheriv(suite, keys.key, keys.iv)
26904}
26905
26906exports.createCipheriv = createCipheriv
26907exports.createCipher = createCipher
26908}, {"./aes":169,"cipher-base":170,"inherits":149,"./modes":171,"evp_bytestokey":166,"./streamCipher":172,"./authCipher":173,"./modes/ecb":176,"./modes/cbc":177,"./modes/cfb":178,"./modes/cfb8":179,"./modes/cfb1":180,"./modes/ofb":181,"./modes/ctr":182}],169: [function (exports, require, module, global) {// based on the aes implimentation in triple sec
26909// https://github.com/keybase/triplesec
26910
26911// which is in turn based on the one from crypto-js
26912// https://code.google.com/p/crypto-js/
26913
26914var uint_max = Math.pow(2, 32)
26915function fixup_uint32 (x) {
26916 var ret, x_pos
26917 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
26918 return ret
26919}
26920function scrub_vec (v) {
26921 for (var i = 0; i < v.length; v++) {
26922 v[i] = 0
26923 }
26924 return false
26925}
26926
26927function Global () {
26928 this.SBOX = []
26929 this.INV_SBOX = []
26930 this.SUB_MIX = [[], [], [], []]
26931 this.INV_SUB_MIX = [[], [], [], []]
26932 this.init()
26933 this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
26934}
26935
26936Global.prototype.init = function () {
26937 var d, i, sx, t, x, x2, x4, x8, xi, _i
26938 d = (function () {
26939 var _i, _results
26940 _results = []
26941 for (i = _i = 0; _i < 256; i = ++_i) {
26942 if (i < 128) {
26943 _results.push(i << 1)
26944 } else {
26945 _results.push((i << 1) ^ 0x11b)
26946 }
26947 }
26948 return _results
26949 })()
26950 x = 0
26951 xi = 0
26952 for (i = _i = 0; _i < 256; i = ++_i) {
26953 sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
26954 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
26955 this.SBOX[x] = sx
26956 this.INV_SBOX[sx] = x
26957 x2 = d[x]
26958 x4 = d[x2]
26959 x8 = d[x4]
26960 t = (d[sx] * 0x101) ^ (sx * 0x1010100)
26961 this.SUB_MIX[0][x] = (t << 24) | (t >>> 8)
26962 this.SUB_MIX[1][x] = (t << 16) | (t >>> 16)
26963 this.SUB_MIX[2][x] = (t << 8) | (t >>> 24)
26964 this.SUB_MIX[3][x] = t
26965 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
26966 this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
26967 this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
26968 this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
26969 this.INV_SUB_MIX[3][sx] = t
26970 if (x === 0) {
26971 x = xi = 1
26972 } else {
26973 x = x2 ^ d[d[d[x8 ^ x2]]]
26974 xi ^= d[d[xi]]
26975 }
26976 }
26977 return true
26978}
26979
26980var G = new Global()
26981
26982AES.blockSize = 4 * 4
26983
26984AES.prototype.blockSize = AES.blockSize
26985
26986AES.keySize = 256 / 8
26987
26988AES.prototype.keySize = AES.keySize
26989
26990function bufferToArray (buf) {
26991 var len = buf.length / 4
26992 var out = new Array(len)
26993 var i = -1
26994 while (++i < len) {
26995 out[i] = buf.readUInt32BE(i * 4)
26996 }
26997 return out
26998}
26999function AES (key) {
27000 this._key = bufferToArray(key)
27001 this._doReset()
27002}
27003
27004AES.prototype._doReset = function () {
27005 var invKsRow, keySize, keyWords, ksRow, ksRows, t
27006 keyWords = this._key
27007 keySize = keyWords.length
27008 this._nRounds = keySize + 6
27009 ksRows = (this._nRounds + 1) * 4
27010 this._keySchedule = []
27011 for (ksRow = 0; ksRow < ksRows; ksRow++) {
27012 this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t)
27013 }
27014 this._invKeySchedule = []
27015 for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
27016 ksRow = ksRows - invKsRow
27017 t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)]
27018 this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]]
27019 }
27020 return true
27021}
27022
27023AES.prototype.encryptBlock = function (M) {
27024 M = bufferToArray(new Buffer(M))
27025 var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX)
27026 var buf = new Buffer(16)
27027 buf.writeUInt32BE(out[0], 0)
27028 buf.writeUInt32BE(out[1], 4)
27029 buf.writeUInt32BE(out[2], 8)
27030 buf.writeUInt32BE(out[3], 12)
27031 return buf
27032}
27033
27034AES.prototype.decryptBlock = function (M) {
27035 M = bufferToArray(new Buffer(M))
27036 var temp = [M[3], M[1]]
27037 M[1] = temp[0]
27038 M[3] = temp[1]
27039 var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX)
27040 var buf = new Buffer(16)
27041 buf.writeUInt32BE(out[0], 0)
27042 buf.writeUInt32BE(out[3], 4)
27043 buf.writeUInt32BE(out[2], 8)
27044 buf.writeUInt32BE(out[1], 12)
27045 return buf
27046}
27047
27048AES.prototype.scrub = function () {
27049 scrub_vec(this._keySchedule)
27050 scrub_vec(this._invKeySchedule)
27051 scrub_vec(this._key)
27052}
27053
27054AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) {
27055 var ksRow, s0, s1, s2, s3, t0, t1, t2, t3
27056
27057 s0 = M[0] ^ keySchedule[0]
27058 s1 = M[1] ^ keySchedule[1]
27059 s2 = M[2] ^ keySchedule[2]
27060 s3 = M[3] ^ keySchedule[3]
27061 ksRow = 4
27062 for (var round = 1; round < this._nRounds; round++) {
27063 t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
27064 t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
27065 t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
27066 t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
27067 s0 = t0
27068 s1 = t1
27069 s2 = t2
27070 s3 = t3
27071 }
27072 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
27073 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
27074 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
27075 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
27076 return [
27077 fixup_uint32(t0),
27078 fixup_uint32(t1),
27079 fixup_uint32(t2),
27080 fixup_uint32(t3)
27081 ]
27082}
27083
27084exports.AES = AES
27085}, {}],170: [function (exports, require, module, global) {var Transform = require('stream').Transform
27086var inherits = require('inherits')
27087var StringDecoder = require('string_decoder').StringDecoder
27088module.exports = CipherBase
27089inherits(CipherBase, Transform)
27090function CipherBase (hashMode) {
27091 Transform.call(this)
27092 this.hashMode = typeof hashMode === 'string'
27093 if (this.hashMode) {
27094 this[hashMode] = this._finalOrDigest
27095 } else {
27096 this.final = this._finalOrDigest
27097 }
27098 this._decoder = null
27099 this._encoding = null
27100}
27101CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
27102 if (typeof data === 'string') {
27103 data = new Buffer(data, inputEnc)
27104 }
27105 var outData = this._update(data)
27106 if (this.hashMode) {
27107 return this
27108 }
27109 if (outputEnc) {
27110 outData = this._toString(outData, outputEnc)
27111 }
27112 return outData
27113}
27114
27115CipherBase.prototype.setAutoPadding = function () {}
27116
27117CipherBase.prototype.getAuthTag = function () {
27118 throw new Error('trying to get auth tag in unsupported state')
27119}
27120
27121CipherBase.prototype.setAuthTag = function () {
27122 throw new Error('trying to set auth tag in unsupported state')
27123}
27124
27125CipherBase.prototype.setAAD = function () {
27126 throw new Error('trying to set aad in unsupported state')
27127}
27128
27129CipherBase.prototype._transform = function (data, _, next) {
27130 var err
27131 try {
27132 if (this.hashMode) {
27133 this._update(data)
27134 } else {
27135 this.push(this._update(data))
27136 }
27137 } catch (e) {
27138 err = e
27139 } finally {
27140 next(err)
27141 }
27142}
27143CipherBase.prototype._flush = function (done) {
27144 var err
27145 try {
27146 this.push(this._final())
27147 } catch (e) {
27148 err = e
27149 } finally {
27150 done(err)
27151 }
27152}
27153CipherBase.prototype._finalOrDigest = function (outputEnc) {
27154 var outData = this._final() || new Buffer('')
27155 if (outputEnc) {
27156 outData = this._toString(outData, outputEnc, true)
27157 }
27158 return outData
27159}
27160
27161CipherBase.prototype._toString = function (value, enc, final) {
27162 if (!this._decoder) {
27163 this._decoder = new StringDecoder(enc)
27164 this._encoding = enc
27165 }
27166 if (this._encoding !== enc) {
27167 throw new Error('can\'t switch encodings')
27168 }
27169 var out = this._decoder.write(value)
27170 if (final) {
27171 out += this._decoder.end()
27172 }
27173 return out
27174}
27175}, {"stream":52,"inherits":149,"string_decoder":62}],171: [function (exports, require, module, global) {exports['aes-128-ecb'] = {
27176 cipher: 'AES',
27177 key: 128,
27178 iv: 0,
27179 mode: 'ECB',
27180 type: 'block'
27181}
27182exports['aes-192-ecb'] = {
27183 cipher: 'AES',
27184 key: 192,
27185 iv: 0,
27186 mode: 'ECB',
27187 type: 'block'
27188}
27189exports['aes-256-ecb'] = {
27190 cipher: 'AES',
27191 key: 256,
27192 iv: 0,
27193 mode: 'ECB',
27194 type: 'block'
27195}
27196exports['aes-128-cbc'] = {
27197 cipher: 'AES',
27198 key: 128,
27199 iv: 16,
27200 mode: 'CBC',
27201 type: 'block'
27202}
27203exports['aes-192-cbc'] = {
27204 cipher: 'AES',
27205 key: 192,
27206 iv: 16,
27207 mode: 'CBC',
27208 type: 'block'
27209}
27210exports['aes-256-cbc'] = {
27211 cipher: 'AES',
27212 key: 256,
27213 iv: 16,
27214 mode: 'CBC',
27215 type: 'block'
27216}
27217exports['aes128'] = exports['aes-128-cbc']
27218exports['aes192'] = exports['aes-192-cbc']
27219exports['aes256'] = exports['aes-256-cbc']
27220exports['aes-128-cfb'] = {
27221 cipher: 'AES',
27222 key: 128,
27223 iv: 16,
27224 mode: 'CFB',
27225 type: 'stream'
27226}
27227exports['aes-192-cfb'] = {
27228 cipher: 'AES',
27229 key: 192,
27230 iv: 16,
27231 mode: 'CFB',
27232 type: 'stream'
27233}
27234exports['aes-256-cfb'] = {
27235 cipher: 'AES',
27236 key: 256,
27237 iv: 16,
27238 mode: 'CFB',
27239 type: 'stream'
27240}
27241exports['aes-128-cfb8'] = {
27242 cipher: 'AES',
27243 key: 128,
27244 iv: 16,
27245 mode: 'CFB8',
27246 type: 'stream'
27247}
27248exports['aes-192-cfb8'] = {
27249 cipher: 'AES',
27250 key: 192,
27251 iv: 16,
27252 mode: 'CFB8',
27253 type: 'stream'
27254}
27255exports['aes-256-cfb8'] = {
27256 cipher: 'AES',
27257 key: 256,
27258 iv: 16,
27259 mode: 'CFB8',
27260 type: 'stream'
27261}
27262exports['aes-128-cfb1'] = {
27263 cipher: 'AES',
27264 key: 128,
27265 iv: 16,
27266 mode: 'CFB1',
27267 type: 'stream'
27268}
27269exports['aes-192-cfb1'] = {
27270 cipher: 'AES',
27271 key: 192,
27272 iv: 16,
27273 mode: 'CFB1',
27274 type: 'stream'
27275}
27276exports['aes-256-cfb1'] = {
27277 cipher: 'AES',
27278 key: 256,
27279 iv: 16,
27280 mode: 'CFB1',
27281 type: 'stream'
27282}
27283exports['aes-128-ofb'] = {
27284 cipher: 'AES',
27285 key: 128,
27286 iv: 16,
27287 mode: 'OFB',
27288 type: 'stream'
27289}
27290exports['aes-192-ofb'] = {
27291 cipher: 'AES',
27292 key: 192,
27293 iv: 16,
27294 mode: 'OFB',
27295 type: 'stream'
27296}
27297exports['aes-256-ofb'] = {
27298 cipher: 'AES',
27299 key: 256,
27300 iv: 16,
27301 mode: 'OFB',
27302 type: 'stream'
27303}
27304exports['aes-128-ctr'] = {
27305 cipher: 'AES',
27306 key: 128,
27307 iv: 16,
27308 mode: 'CTR',
27309 type: 'stream'
27310}
27311exports['aes-192-ctr'] = {
27312 cipher: 'AES',
27313 key: 192,
27314 iv: 16,
27315 mode: 'CTR',
27316 type: 'stream'
27317}
27318exports['aes-256-ctr'] = {
27319 cipher: 'AES',
27320 key: 256,
27321 iv: 16,
27322 mode: 'CTR',
27323 type: 'stream'
27324}
27325exports['aes-128-gcm'] = {
27326 cipher: 'AES',
27327 key: 128,
27328 iv: 12,
27329 mode: 'GCM',
27330 type: 'auth'
27331}
27332exports['aes-192-gcm'] = {
27333 cipher: 'AES',
27334 key: 192,
27335 iv: 12,
27336 mode: 'GCM',
27337 type: 'auth'
27338}
27339exports['aes-256-gcm'] = {
27340 cipher: 'AES',
27341 key: 256,
27342 iv: 12,
27343 mode: 'GCM',
27344 type: 'auth'
27345}
27346}, {}],172: [function (exports, require, module, global) {var aes = require('./aes')
27347var Transform = require('cipher-base')
27348var inherits = require('inherits')
27349
27350inherits(StreamCipher, Transform)
27351module.exports = StreamCipher
27352function StreamCipher (mode, key, iv, decrypt) {
27353 if (!(this instanceof StreamCipher)) {
27354 return new StreamCipher(mode, key, iv)
27355 }
27356 Transform.call(this)
27357 this._cipher = new aes.AES(key)
27358 this._prev = new Buffer(iv.length)
27359 this._cache = new Buffer('')
27360 this._secCache = new Buffer('')
27361 this._decrypt = decrypt
27362 iv.copy(this._prev)
27363 this._mode = mode
27364}
27365StreamCipher.prototype._update = function (chunk) {
27366 return this._mode.encrypt(this, chunk, this._decrypt)
27367}
27368StreamCipher.prototype._final = function () {
27369 this._cipher.scrub()
27370}
27371}, {"./aes":169,"cipher-base":170,"inherits":149}],173: [function (exports, require, module, global) {var aes = require('./aes')
27372var Transform = require('cipher-base')
27373var inherits = require('inherits')
27374var GHASH = require('./ghash')
27375var xor = require('buffer-xor')
27376inherits(StreamCipher, Transform)
27377module.exports = StreamCipher
27378
27379function StreamCipher (mode, key, iv, decrypt) {
27380 if (!(this instanceof StreamCipher)) {
27381 return new StreamCipher(mode, key, iv)
27382 }
27383 Transform.call(this)
27384 this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])])
27385 iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])])
27386 this._cipher = new aes.AES(key)
27387 this._prev = new Buffer(iv.length)
27388 this._cache = new Buffer('')
27389 this._secCache = new Buffer('')
27390 this._decrypt = decrypt
27391 this._alen = 0
27392 this._len = 0
27393 iv.copy(this._prev)
27394 this._mode = mode
27395 var h = new Buffer(4)
27396 h.fill(0)
27397 this._ghash = new GHASH(this._cipher.encryptBlock(h))
27398 this._authTag = null
27399 this._called = false
27400}
27401StreamCipher.prototype._update = function (chunk) {
27402 if (!this._called && this._alen) {
27403 var rump = 16 - (this._alen % 16)
27404 if (rump < 16) {
27405 rump = new Buffer(rump)
27406 rump.fill(0)
27407 this._ghash.update(rump)
27408 }
27409 }
27410 this._called = true
27411 var out = this._mode.encrypt(this, chunk)
27412 if (this._decrypt) {
27413 this._ghash.update(chunk)
27414 } else {
27415 this._ghash.update(out)
27416 }
27417 this._len += chunk.length
27418 return out
27419}
27420StreamCipher.prototype._final = function () {
27421 if (this._decrypt && !this._authTag) {
27422 throw new Error('Unsupported state or unable to authenticate data')
27423 }
27424 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
27425 if (this._decrypt) {
27426 if (xorTest(tag, this._authTag)) {
27427 throw new Error('Unsupported state or unable to authenticate data')
27428 }
27429 } else {
27430 this._authTag = tag
27431 }
27432 this._cipher.scrub()
27433}
27434StreamCipher.prototype.getAuthTag = function getAuthTag () {
27435 if (!this._decrypt && Buffer.isBuffer(this._authTag)) {
27436 return this._authTag
27437 } else {
27438 throw new Error('Attempting to get auth tag in unsupported state')
27439 }
27440}
27441StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
27442 if (this._decrypt) {
27443 this._authTag = tag
27444 } else {
27445 throw new Error('Attempting to set auth tag in unsupported state')
27446 }
27447}
27448StreamCipher.prototype.setAAD = function setAAD (buf) {
27449 if (!this._called) {
27450 this._ghash.update(buf)
27451 this._alen += buf.length
27452 } else {
27453 throw new Error('Attempting to set AAD in unsupported state')
27454 }
27455}
27456function xorTest (a, b) {
27457 var out = 0
27458 if (a.length !== b.length) {
27459 out++
27460 }
27461 var len = Math.min(a.length, b.length)
27462 var i = -1
27463 while (++i < len) {
27464 out += (a[i] ^ b[i])
27465 }
27466 return out
27467}
27468}, {"./aes":169,"cipher-base":170,"inherits":149,"./ghash":174,"buffer-xor":175}],174: [function (exports, require, module, global) {var zeros = new Buffer(16)
27469zeros.fill(0)
27470module.exports = GHASH
27471function GHASH (key) {
27472 this.h = key
27473 this.state = new Buffer(16)
27474 this.state.fill(0)
27475 this.cache = new Buffer('')
27476}
27477// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
27478// by Juho Vähä-Herttua
27479GHASH.prototype.ghash = function (block) {
27480 var i = -1
27481 while (++i < block.length) {
27482 this.state[i] ^= block[i]
27483 }
27484 this._multiply()
27485}
27486
27487GHASH.prototype._multiply = function () {
27488 var Vi = toArray(this.h)
27489 var Zi = [0, 0, 0, 0]
27490 var j, xi, lsb_Vi
27491 var i = -1
27492 while (++i < 128) {
27493 xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0
27494 if (xi) {
27495 // Z_i+1 = Z_i ^ V_i
27496 Zi = xor(Zi, Vi)
27497 }
27498
27499 // Store the value of LSB(V_i)
27500 lsb_Vi = (Vi[3] & 1) !== 0
27501
27502 // V_i+1 = V_i >> 1
27503 for (j = 3; j > 0; j--) {
27504 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
27505 }
27506 Vi[0] = Vi[0] >>> 1
27507
27508 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
27509 if (lsb_Vi) {
27510 Vi[0] = Vi[0] ^ (0xe1 << 24)
27511 }
27512 }
27513 this.state = fromArray(Zi)
27514}
27515GHASH.prototype.update = function (buf) {
27516 this.cache = Buffer.concat([this.cache, buf])
27517 var chunk
27518 while (this.cache.length >= 16) {
27519 chunk = this.cache.slice(0, 16)
27520 this.cache = this.cache.slice(16)
27521 this.ghash(chunk)
27522 }
27523}
27524GHASH.prototype.final = function (abl, bl) {
27525 if (this.cache.length) {
27526 this.ghash(Buffer.concat([this.cache, zeros], 16))
27527 }
27528 this.ghash(fromArray([
27529 0, abl,
27530 0, bl
27531 ]))
27532 return this.state
27533}
27534
27535function toArray (buf) {
27536 return [
27537 buf.readUInt32BE(0),
27538 buf.readUInt32BE(4),
27539 buf.readUInt32BE(8),
27540 buf.readUInt32BE(12)
27541 ]
27542}
27543function fromArray (out) {
27544 out = out.map(fixup_uint32)
27545 var buf = new Buffer(16)
27546 buf.writeUInt32BE(out[0], 0)
27547 buf.writeUInt32BE(out[1], 4)
27548 buf.writeUInt32BE(out[2], 8)
27549 buf.writeUInt32BE(out[3], 12)
27550 return buf
27551}
27552var uint_max = Math.pow(2, 32)
27553function fixup_uint32 (x) {
27554 var ret, x_pos
27555 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
27556 return ret
27557}
27558function xor (a, b) {
27559 return [
27560 a[0] ^ b[0],
27561 a[1] ^ b[1],
27562 a[2] ^ b[2],
27563 a[3] ^ b[3]
27564 ]
27565}
27566}, {}],175: [function (exports, require, module, global) {module.exports = function xor (a, b) {
27567 var length = Math.min(a.length, b.length)
27568 var buffer = new Buffer(length)
27569
27570 for (var i = 0; i < length; ++i) {
27571 buffer[i] = a[i] ^ b[i]
27572 }
27573
27574 return buffer
27575}
27576}, {}],176: [function (exports, require, module, global) {exports.encrypt = function (self, block) {
27577 return self._cipher.encryptBlock(block)
27578}
27579exports.decrypt = function (self, block) {
27580 return self._cipher.decryptBlock(block)
27581}
27582}, {}],177: [function (exports, require, module, global) {var xor = require('buffer-xor')
27583
27584exports.encrypt = function (self, block) {
27585 var data = xor(block, self._prev)
27586
27587 self._prev = self._cipher.encryptBlock(data)
27588 return self._prev
27589}
27590
27591exports.decrypt = function (self, block) {
27592 var pad = self._prev
27593
27594 self._prev = block
27595 var out = self._cipher.decryptBlock(block)
27596
27597 return xor(out, pad)
27598}
27599}, {"buffer-xor":175}],178: [function (exports, require, module, global) {var xor = require('buffer-xor')
27600
27601exports.encrypt = function (self, data, decrypt) {
27602 var out = new Buffer('')
27603 var len
27604
27605 while (data.length) {
27606 if (self._cache.length === 0) {
27607 self._cache = self._cipher.encryptBlock(self._prev)
27608 self._prev = new Buffer('')
27609 }
27610
27611 if (self._cache.length <= data.length) {
27612 len = self._cache.length
27613 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
27614 data = data.slice(len)
27615 } else {
27616 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
27617 break
27618 }
27619 }
27620
27621 return out
27622}
27623function encryptStart (self, data, decrypt) {
27624 var len = data.length
27625 var out = xor(data, self._cache)
27626 self._cache = self._cache.slice(len)
27627 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
27628 return out
27629}
27630}, {"buffer-xor":175}],179: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
27631 var pad = self._cipher.encryptBlock(self._prev)
27632 var out = pad[0] ^ byteParam
27633 self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])])
27634 return out
27635}
27636exports.encrypt = function (self, chunk, decrypt) {
27637 var len = chunk.length
27638 var out = new Buffer(len)
27639 var i = -1
27640 while (++i < len) {
27641 out[i] = encryptByte(self, chunk[i], decrypt)
27642 }
27643 return out
27644}
27645}, {}],180: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
27646 var pad
27647 var i = -1
27648 var len = 8
27649 var out = 0
27650 var bit, value
27651 while (++i < len) {
27652 pad = self._cipher.encryptBlock(self._prev)
27653 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
27654 value = pad[0] ^ bit
27655 out += ((value & 0x80) >> (i % 8))
27656 self._prev = shiftIn(self._prev, decrypt ? bit : value)
27657 }
27658 return out
27659}
27660exports.encrypt = function (self, chunk, decrypt) {
27661 var len = chunk.length
27662 var out = new Buffer(len)
27663 var i = -1
27664 while (++i < len) {
27665 out[i] = encryptByte(self, chunk[i], decrypt)
27666 }
27667 return out
27668}
27669function shiftIn (buffer, value) {
27670 var len = buffer.length
27671 var i = -1
27672 var out = new Buffer(buffer.length)
27673 buffer = Buffer.concat([buffer, new Buffer([value])])
27674 while (++i < len) {
27675 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
27676 }
27677 return out
27678}
27679}, {}],181: [function (exports, require, module, global) {var xor = require('buffer-xor')
27680
27681function getBlock (self) {
27682 self._prev = self._cipher.encryptBlock(self._prev)
27683 return self._prev
27684}
27685
27686exports.encrypt = function (self, chunk) {
27687 while (self._cache.length < chunk.length) {
27688 self._cache = Buffer.concat([self._cache, getBlock(self)])
27689 }
27690
27691 var pad = self._cache.slice(0, chunk.length)
27692 self._cache = self._cache.slice(chunk.length)
27693 return xor(chunk, pad)
27694}
27695}, {"buffer-xor":175}],182: [function (exports, require, module, global) {var xor = require('buffer-xor')
27696
27697function incr32 (iv) {
27698 var len = iv.length
27699 var item
27700 while (len--) {
27701 item = iv.readUInt8(len)
27702 if (item === 255) {
27703 iv.writeUInt8(0, len)
27704 } else {
27705 item++
27706 iv.writeUInt8(item, len)
27707 break
27708 }
27709 }
27710}
27711
27712function getBlock (self) {
27713 var out = self._cipher.encryptBlock(self._prev)
27714 incr32(self._prev)
27715 return out
27716}
27717
27718exports.encrypt = function (self, chunk) {
27719 while (self._cache.length < chunk.length) {
27720 self._cache = Buffer.concat([self._cache, getBlock(self)])
27721 }
27722 var pad = self._cache.slice(0, chunk.length)
27723 self._cache = self._cache.slice(chunk.length)
27724 return xor(chunk, pad)
27725}
27726}, {"buffer-xor":175}],183: [function (exports, require, module, global) {var aes = require('./aes')
27727var Transform = require('cipher-base')
27728var inherits = require('inherits')
27729var modes = require('./modes')
27730var StreamCipher = require('./streamCipher')
27731var AuthCipher = require('./authCipher')
27732var ebtk = require('evp_bytestokey')
27733
27734inherits(Decipher, Transform)
27735function Decipher (mode, key, iv) {
27736 if (!(this instanceof Decipher)) {
27737 return new Decipher(mode, key, iv)
27738 }
27739 Transform.call(this)
27740 this._cache = new Splitter()
27741 this._last = void 0
27742 this._cipher = new aes.AES(key)
27743 this._prev = new Buffer(iv.length)
27744 iv.copy(this._prev)
27745 this._mode = mode
27746 this._autopadding = true
27747}
27748Decipher.prototype._update = function (data) {
27749 this._cache.add(data)
27750 var chunk
27751 var thing
27752 var out = []
27753 while ((chunk = this._cache.get(this._autopadding))) {
27754 thing = this._mode.decrypt(this, chunk)
27755 out.push(thing)
27756 }
27757 return Buffer.concat(out)
27758}
27759Decipher.prototype._final = function () {
27760 var chunk = this._cache.flush()
27761 if (this._autopadding) {
27762 return unpad(this._mode.decrypt(this, chunk))
27763 } else if (chunk) {
27764 throw new Error('data not multiple of block length')
27765 }
27766}
27767Decipher.prototype.setAutoPadding = function (setTo) {
27768 this._autopadding = !!setTo
27769}
27770function Splitter () {
27771 if (!(this instanceof Splitter)) {
27772 return new Splitter()
27773 }
27774 this.cache = new Buffer('')
27775}
27776Splitter.prototype.add = function (data) {
27777 this.cache = Buffer.concat([this.cache, data])
27778}
27779
27780Splitter.prototype.get = function (autoPadding) {
27781 var out
27782 if (autoPadding) {
27783 if (this.cache.length > 16) {
27784 out = this.cache.slice(0, 16)
27785 this.cache = this.cache.slice(16)
27786 return out
27787 }
27788 } else {
27789 if (this.cache.length >= 16) {
27790 out = this.cache.slice(0, 16)
27791 this.cache = this.cache.slice(16)
27792 return out
27793 }
27794 }
27795 return null
27796}
27797Splitter.prototype.flush = function () {
27798 if (this.cache.length) {
27799 return this.cache
27800 }
27801}
27802function unpad (last) {
27803 var padded = last[15]
27804 var i = -1
27805 while (++i < padded) {
27806 if (last[(i + (16 - padded))] !== padded) {
27807 throw new Error('unable to decrypt data')
27808 }
27809 }
27810 if (padded === 16) {
27811 return
27812 }
27813 return last.slice(0, 16 - padded)
27814}
27815
27816var modelist = {
27817 ECB: require('./modes/ecb'),
27818 CBC: require('./modes/cbc'),
27819 CFB: require('./modes/cfb'),
27820 CFB8: require('./modes/cfb8'),
27821 CFB1: require('./modes/cfb1'),
27822 OFB: require('./modes/ofb'),
27823 CTR: require('./modes/ctr'),
27824 GCM: require('./modes/ctr')
27825}
27826
27827function createDecipheriv (suite, password, iv) {
27828 var config = modes[suite.toLowerCase()]
27829 if (!config) {
27830 throw new TypeError('invalid suite type')
27831 }
27832 if (typeof iv === 'string') {
27833 iv = new Buffer(iv)
27834 }
27835 if (typeof password === 'string') {
27836 password = new Buffer(password)
27837 }
27838 if (password.length !== config.key / 8) {
27839 throw new TypeError('invalid key length ' + password.length)
27840 }
27841 if (iv.length !== config.iv) {
27842 throw new TypeError('invalid iv length ' + iv.length)
27843 }
27844 if (config.type === 'stream') {
27845 return new StreamCipher(modelist[config.mode], password, iv, true)
27846 } else if (config.type === 'auth') {
27847 return new AuthCipher(modelist[config.mode], password, iv, true)
27848 }
27849 return new Decipher(modelist[config.mode], password, iv)
27850}
27851
27852function createDecipher (suite, password) {
27853 var config = modes[suite.toLowerCase()]
27854 if (!config) {
27855 throw new TypeError('invalid suite type')
27856 }
27857 var keys = ebtk(password, false, config.key, config.iv)
27858 return createDecipheriv(suite, keys.key, keys.iv)
27859}
27860exports.createDecipher = createDecipher
27861exports.createDecipheriv = createDecipheriv
27862}, {"./aes":169,"cipher-base":170,"inherits":149,"./modes":171,"./streamCipher":172,"./authCipher":173,"evp_bytestokey":166,"./modes/ecb":176,"./modes/cbc":177,"./modes/cfb":178,"./modes/cfb8":179,"./modes/cfb1":180,"./modes/ofb":181,"./modes/ctr":182}],184: [function (exports, require, module, global) {var CipherBase = require('cipher-base')
27863var des = require('des.js')
27864var inherits = require('inherits')
27865
27866var modes = {
27867 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
27868 'des-ede3': des.EDE,
27869 'des-ede-cbc': des.CBC.instantiate(des.EDE),
27870 'des-ede': des.EDE,
27871 'des-cbc': des.CBC.instantiate(des.DES),
27872 'des-ecb': des.DES
27873}
27874modes.des = modes['des-cbc']
27875modes.des3 = modes['des-ede3-cbc']
27876module.exports = DES
27877inherits(DES, CipherBase)
27878function DES (opts) {
27879 CipherBase.call(this)
27880 var modeName = opts.mode.toLowerCase()
27881 var mode = modes[modeName]
27882 var type
27883 if (opts.decrypt) {
27884 type = 'decrypt'
27885 } else {
27886 type = 'encrypt'
27887 }
27888 var key = opts.key
27889 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
27890 key = Buffer.concat([key, key.slice(0, 8)])
27891 }
27892 var iv = opts.iv
27893 this._des = mode.create({
27894 key: key,
27895 iv: iv,
27896 type: type
27897 })
27898}
27899DES.prototype._update = function (data) {
27900 return new Buffer(this._des.update(data))
27901}
27902DES.prototype._final = function () {
27903 return new Buffer(this._des.final())
27904}
27905}, {"cipher-base":185,"des.js":186,"inherits":149}],185: [function (exports, require, module, global) {var Transform = require('stream').Transform
27906var inherits = require('inherits')
27907var StringDecoder = require('string_decoder').StringDecoder
27908module.exports = CipherBase
27909inherits(CipherBase, Transform)
27910function CipherBase (hashMode) {
27911 Transform.call(this)
27912 this.hashMode = typeof hashMode === 'string'
27913 if (this.hashMode) {
27914 this[hashMode] = this._finalOrDigest
27915 } else {
27916 this.final = this._finalOrDigest
27917 }
27918 this._decoder = null
27919 this._encoding = null
27920}
27921CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
27922 if (typeof data === 'string') {
27923 data = new Buffer(data, inputEnc)
27924 }
27925 var outData = this._update(data)
27926 if (this.hashMode) {
27927 return this
27928 }
27929 if (outputEnc) {
27930 outData = this._toString(outData, outputEnc)
27931 }
27932 return outData
27933}
27934
27935CipherBase.prototype.setAutoPadding = function () {}
27936
27937CipherBase.prototype.getAuthTag = function () {
27938 throw new Error('trying to get auth tag in unsupported state')
27939}
27940
27941CipherBase.prototype.setAuthTag = function () {
27942 throw new Error('trying to set auth tag in unsupported state')
27943}
27944
27945CipherBase.prototype.setAAD = function () {
27946 throw new Error('trying to set aad in unsupported state')
27947}
27948
27949CipherBase.prototype._transform = function (data, _, next) {
27950 var err
27951 try {
27952 if (this.hashMode) {
27953 this._update(data)
27954 } else {
27955 this.push(this._update(data))
27956 }
27957 } catch (e) {
27958 err = e
27959 } finally {
27960 next(err)
27961 }
27962}
27963CipherBase.prototype._flush = function (done) {
27964 var err
27965 try {
27966 this.push(this._final())
27967 } catch (e) {
27968 err = e
27969 } finally {
27970 done(err)
27971 }
27972}
27973CipherBase.prototype._finalOrDigest = function (outputEnc) {
27974 var outData = this._final() || new Buffer('')
27975 if (outputEnc) {
27976 outData = this._toString(outData, outputEnc, true)
27977 }
27978 return outData
27979}
27980
27981CipherBase.prototype._toString = function (value, enc, final) {
27982 if (!this._decoder) {
27983 this._decoder = new StringDecoder(enc)
27984 this._encoding = enc
27985 }
27986 if (this._encoding !== enc) {
27987 throw new Error('can\'t switch encodings')
27988 }
27989 var out = this._decoder.write(value)
27990 if (final) {
27991 out += this._decoder.end()
27992 }
27993 return out
27994}
27995}, {"stream":52,"inherits":149,"string_decoder":62}],186: [function (exports, require, module, global) {'use strict';
27996
27997exports.utils = require('./des/utils');
27998exports.Cipher = require('./des/cipher');
27999exports.DES = require('./des/des');
28000exports.CBC = require('./des/cbc');
28001exports.EDE = require('./des/ede');
28002}, {"./des/utils":187,"./des/cipher":188,"./des/des":190,"./des/cbc":191,"./des/ede":192}],187: [function (exports, require, module, global) {'use strict';
28003
28004exports.readUInt32BE = function readUInt32BE(bytes, off) {
28005 var res = (bytes[0 + off] << 24) |
28006 (bytes[1 + off] << 16) |
28007 (bytes[2 + off] << 8) |
28008 bytes[3 + off];
28009 return res >>> 0;
28010};
28011
28012exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
28013 bytes[0 + off] = value >>> 24;
28014 bytes[1 + off] = (value >>> 16) & 0xff;
28015 bytes[2 + off] = (value >>> 8) & 0xff;
28016 bytes[3 + off] = value & 0xff;
28017};
28018
28019exports.ip = function ip(inL, inR, out, off) {
28020 var outL = 0;
28021 var outR = 0;
28022
28023 for (var i = 6; i >= 0; i -= 2) {
28024 for (var j = 0; j <= 24; j += 8) {
28025 outL <<= 1;
28026 outL |= (inR >>> (j + i)) & 1;
28027 }
28028 for (var j = 0; j <= 24; j += 8) {
28029 outL <<= 1;
28030 outL |= (inL >>> (j + i)) & 1;
28031 }
28032 }
28033
28034 for (var i = 6; i >= 0; i -= 2) {
28035 for (var j = 1; j <= 25; j += 8) {
28036 outR <<= 1;
28037 outR |= (inR >>> (j + i)) & 1;
28038 }
28039 for (var j = 1; j <= 25; j += 8) {
28040 outR <<= 1;
28041 outR |= (inL >>> (j + i)) & 1;
28042 }
28043 }
28044
28045 out[off + 0] = outL >>> 0;
28046 out[off + 1] = outR >>> 0;
28047};
28048
28049exports.rip = function rip(inL, inR, out, off) {
28050 var outL = 0;
28051 var outR = 0;
28052
28053 for (var i = 0; i < 4; i++) {
28054 for (var j = 24; j >= 0; j -= 8) {
28055 outL <<= 1;
28056 outL |= (inR >>> (j + i)) & 1;
28057 outL <<= 1;
28058 outL |= (inL >>> (j + i)) & 1;
28059 }
28060 }
28061 for (var i = 4; i < 8; i++) {
28062 for (var j = 24; j >= 0; j -= 8) {
28063 outR <<= 1;
28064 outR |= (inR >>> (j + i)) & 1;
28065 outR <<= 1;
28066 outR |= (inL >>> (j + i)) & 1;
28067 }
28068 }
28069
28070 out[off + 0] = outL >>> 0;
28071 out[off + 1] = outR >>> 0;
28072};
28073
28074exports.pc1 = function pc1(inL, inR, out, off) {
28075 var outL = 0;
28076 var outR = 0;
28077
28078 // 7, 15, 23, 31, 39, 47, 55, 63
28079 // 6, 14, 22, 30, 39, 47, 55, 63
28080 // 5, 13, 21, 29, 39, 47, 55, 63
28081 // 4, 12, 20, 28
28082 for (var i = 7; i >= 5; i--) {
28083 for (var j = 0; j <= 24; j += 8) {
28084 outL <<= 1;
28085 outL |= (inR >> (j + i)) & 1;
28086 }
28087 for (var j = 0; j <= 24; j += 8) {
28088 outL <<= 1;
28089 outL |= (inL >> (j + i)) & 1;
28090 }
28091 }
28092 for (var j = 0; j <= 24; j += 8) {
28093 outL <<= 1;
28094 outL |= (inR >> (j + i)) & 1;
28095 }
28096
28097 // 1, 9, 17, 25, 33, 41, 49, 57
28098 // 2, 10, 18, 26, 34, 42, 50, 58
28099 // 3, 11, 19, 27, 35, 43, 51, 59
28100 // 36, 44, 52, 60
28101 for (var i = 1; i <= 3; i++) {
28102 for (var j = 0; j <= 24; j += 8) {
28103 outR <<= 1;
28104 outR |= (inR >> (j + i)) & 1;
28105 }
28106 for (var j = 0; j <= 24; j += 8) {
28107 outR <<= 1;
28108 outR |= (inL >> (j + i)) & 1;
28109 }
28110 }
28111 for (var j = 0; j <= 24; j += 8) {
28112 outR <<= 1;
28113 outR |= (inL >> (j + i)) & 1;
28114 }
28115
28116 out[off + 0] = outL >>> 0;
28117 out[off + 1] = outR >>> 0;
28118};
28119
28120exports.r28shl = function r28shl(num, shift) {
28121 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
28122};
28123
28124var pc2table = [
28125 // inL => outL
28126 14, 11, 17, 4, 27, 23, 25, 0,
28127 13, 22, 7, 18, 5, 9, 16, 24,
28128 2, 20, 12, 21, 1, 8, 15, 26,
28129
28130 // inR => outR
28131 15, 4, 25, 19, 9, 1, 26, 16,
28132 5, 11, 23, 8, 12, 7, 17, 0,
28133 22, 3, 10, 14, 6, 20, 27, 24
28134];
28135
28136exports.pc2 = function pc2(inL, inR, out, off) {
28137 var outL = 0;
28138 var outR = 0;
28139
28140 var len = pc2table.length >>> 1;
28141 for (var i = 0; i < len; i++) {
28142 outL <<= 1;
28143 outL |= (inL >>> pc2table[i]) & 0x1;
28144 }
28145 for (var i = len; i < pc2table.length; i++) {
28146 outR <<= 1;
28147 outR |= (inR >>> pc2table[i]) & 0x1;
28148 }
28149
28150 out[off + 0] = outL >>> 0;
28151 out[off + 1] = outR >>> 0;
28152};
28153
28154exports.expand = function expand(r, out, off) {
28155 var outL = 0;
28156 var outR = 0;
28157
28158 outL = ((r & 1) << 5) | (r >>> 27);
28159 for (var i = 23; i >= 15; i -= 4) {
28160 outL <<= 6;
28161 outL |= (r >>> i) & 0x3f;
28162 }
28163 for (var i = 11; i >= 3; i -= 4) {
28164 outR |= (r >>> i) & 0x3f;
28165 outR <<= 6;
28166 }
28167 outR |= ((r & 0x1f) << 1) | (r >>> 31);
28168
28169 out[off + 0] = outL >>> 0;
28170 out[off + 1] = outR >>> 0;
28171};
28172
28173var sTable = [
28174 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
28175 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
28176 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
28177 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
28178
28179 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
28180 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
28181 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
28182 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
28183
28184 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
28185 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
28186 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
28187 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
28188
28189 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
28190 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
28191 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
28192 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
28193
28194 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
28195 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
28196 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
28197 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
28198
28199 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
28200 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
28201 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
28202 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
28203
28204 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
28205 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
28206 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
28207 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
28208
28209 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
28210 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
28211 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
28212 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
28213];
28214
28215exports.substitute = function substitute(inL, inR) {
28216 var out = 0;
28217 for (var i = 0; i < 4; i++) {
28218 var b = (inL >>> (18 - i * 6)) & 0x3f;
28219 var sb = sTable[i * 0x40 + b];
28220
28221 out <<= 4;
28222 out |= sb;
28223 }
28224 for (var i = 0; i < 4; i++) {
28225 var b = (inR >>> (18 - i * 6)) & 0x3f;
28226 var sb = sTable[4 * 0x40 + i * 0x40 + b];
28227
28228 out <<= 4;
28229 out |= sb;
28230 }
28231 return out >>> 0;
28232};
28233
28234var permuteTable = [
28235 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
28236 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
28237];
28238
28239exports.permute = function permute(num) {
28240 var out = 0;
28241 for (var i = 0; i < permuteTable.length; i++) {
28242 out <<= 1;
28243 out |= (num >>> permuteTable[i]) & 0x1;
28244 }
28245 return out >>> 0;
28246};
28247
28248exports.padSplit = function padSplit(num, size, group) {
28249 var str = num.toString(2);
28250 while (str.length < size)
28251 str = '0' + str;
28252
28253 var out = [];
28254 for (var i = 0; i < size; i += group)
28255 out.push(str.slice(i, i + group));
28256 return out.join(' ');
28257};
28258}, {}],188: [function (exports, require, module, global) {'use strict';
28259
28260var assert = require('minimalistic-assert');
28261
28262function Cipher(options) {
28263 this.options = options;
28264
28265 this.type = this.options.type;
28266 this.blockSize = 8;
28267 this._init();
28268
28269 this.buffer = new Array(this.blockSize);
28270 this.bufferOff = 0;
28271}
28272module.exports = Cipher;
28273
28274Cipher.prototype._init = function _init() {
28275 // Might be overrided
28276};
28277
28278Cipher.prototype.update = function update(data) {
28279 if (data.length === 0)
28280 return [];
28281
28282 if (this.type === 'decrypt')
28283 return this._updateDecrypt(data);
28284 else
28285 return this._updateEncrypt(data);
28286};
28287
28288Cipher.prototype._buffer = function _buffer(data, off) {
28289 // Append data to buffer
28290 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
28291 for (var i = 0; i < min; i++)
28292 this.buffer[this.bufferOff + i] = data[off + i];
28293 this.bufferOff += min;
28294
28295 // Shift next
28296 return min;
28297};
28298
28299Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
28300 this._update(this.buffer, 0, out, off);
28301 this.bufferOff = 0;
28302 return this.blockSize;
28303};
28304
28305Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
28306 var inputOff = 0;
28307 var outputOff = 0;
28308
28309 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
28310 var out = new Array(count * this.blockSize);
28311
28312 if (this.bufferOff !== 0) {
28313 inputOff += this._buffer(data, inputOff);
28314
28315 if (this.bufferOff === this.buffer.length)
28316 outputOff += this._flushBuffer(out, outputOff);
28317 }
28318
28319 // Write blocks
28320 var max = data.length - ((data.length - inputOff) % this.blockSize);
28321 for (; inputOff < max; inputOff += this.blockSize) {
28322 this._update(data, inputOff, out, outputOff);
28323 outputOff += this.blockSize;
28324 }
28325
28326 // Queue rest
28327 for (; inputOff < data.length; inputOff++, this.bufferOff++)
28328 this.buffer[this.bufferOff] = data[inputOff];
28329
28330 return out;
28331};
28332
28333Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
28334 var inputOff = 0;
28335 var outputOff = 0;
28336
28337 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
28338 var out = new Array(count * this.blockSize);
28339
28340 // TODO(indutny): optimize it, this is far from optimal
28341 for (; count > 0; count--) {
28342 inputOff += this._buffer(data, inputOff);
28343 outputOff += this._flushBuffer(out, outputOff);
28344 }
28345
28346 // Buffer rest of the input
28347 inputOff += this._buffer(data, inputOff);
28348
28349 return out;
28350};
28351
28352Cipher.prototype.final = function final(buffer) {
28353 var first;
28354 if (buffer)
28355 first = this.update(buffer);
28356
28357 var last;
28358 if (this.type === 'encrypt')
28359 last = this._finalEncrypt();
28360 else
28361 last = this._finalDecrypt();
28362
28363 if (first)
28364 return first.concat(last);
28365 else
28366 return last;
28367};
28368
28369Cipher.prototype._pad = function _pad(buffer, off) {
28370 if (off === 0)
28371 return false;
28372
28373 while (off < buffer.length)
28374 buffer[off++] = 0;
28375
28376 return true;
28377};
28378
28379Cipher.prototype._finalEncrypt = function _finalEncrypt() {
28380 if (!this._pad(this.buffer, this.bufferOff))
28381 return [];
28382
28383 var out = new Array(this.blockSize);
28384 this._update(this.buffer, 0, out, 0);
28385 return out;
28386};
28387
28388Cipher.prototype._unpad = function _unpad(buffer) {
28389 return buffer;
28390};
28391
28392Cipher.prototype._finalDecrypt = function _finalDecrypt() {
28393 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
28394 var out = new Array(this.blockSize);
28395 this._flushBuffer(out, 0);
28396
28397 return this._unpad(out);
28398};
28399}, {"minimalistic-assert":189}],189: [function (exports, require, module, global) {module.exports = assert;
28400
28401function assert(val, msg) {
28402 if (!val)
28403 throw new Error(msg || 'Assertion failed');
28404}
28405
28406assert.equal = function assertEqual(l, r, msg) {
28407 if (l != r)
28408 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
28409};
28410}, {}],190: [function (exports, require, module, global) {'use strict';
28411
28412var assert = require('minimalistic-assert');
28413var inherits = require('inherits');
28414
28415var des = require('../des');
28416var utils = des.utils;
28417var Cipher = des.Cipher;
28418
28419function DESState() {
28420 this.tmp = new Array(2);
28421 this.keys = null;
28422}
28423
28424function DES(options) {
28425 Cipher.call(this, options);
28426
28427 var state = new DESState();
28428 this._desState = state;
28429
28430 this.deriveKeys(state, options.key);
28431}
28432inherits(DES, Cipher);
28433module.exports = DES;
28434
28435DES.create = function create(options) {
28436 return new DES(options);
28437};
28438
28439var shiftTable = [
28440 1, 1, 2, 2, 2, 2, 2, 2,
28441 1, 2, 2, 2, 2, 2, 2, 1
28442];
28443
28444DES.prototype.deriveKeys = function deriveKeys(state, key) {
28445 state.keys = new Array(16 * 2);
28446
28447 assert.equal(key.length, this.blockSize, 'Invalid key length');
28448
28449 var kL = utils.readUInt32BE(key, 0);
28450 var kR = utils.readUInt32BE(key, 4);
28451
28452 utils.pc1(kL, kR, state.tmp, 0);
28453 kL = state.tmp[0];
28454 kR = state.tmp[1];
28455 for (var i = 0; i < state.keys.length; i += 2) {
28456 var shift = shiftTable[i >>> 1];
28457 kL = utils.r28shl(kL, shift);
28458 kR = utils.r28shl(kR, shift);
28459 utils.pc2(kL, kR, state.keys, i);
28460 }
28461};
28462
28463DES.prototype._update = function _update(inp, inOff, out, outOff) {
28464 var state = this._desState;
28465
28466 var l = utils.readUInt32BE(inp, inOff);
28467 var r = utils.readUInt32BE(inp, inOff + 4);
28468
28469 // Initial Permutation
28470 utils.ip(l, r, state.tmp, 0);
28471 l = state.tmp[0];
28472 r = state.tmp[1];
28473
28474 if (this.type === 'encrypt')
28475 this._encrypt(state, l, r, state.tmp, 0);
28476 else
28477 this._decrypt(state, l, r, state.tmp, 0);
28478
28479 l = state.tmp[0];
28480 r = state.tmp[1];
28481
28482 utils.writeUInt32BE(out, l, outOff);
28483 utils.writeUInt32BE(out, r, outOff + 4);
28484};
28485
28486DES.prototype._pad = function _pad(buffer, off) {
28487 var value = buffer.length - off;
28488 for (var i = off; i < buffer.length; i++)
28489 buffer[i] = value;
28490
28491 return true;
28492};
28493
28494DES.prototype._unpad = function _unpad(buffer) {
28495 var pad = buffer[buffer.length - 1];
28496 for (var i = buffer.length - pad; i < buffer.length; i++)
28497 assert.equal(buffer[i], pad);
28498
28499 return buffer.slice(0, buffer.length - pad);
28500};
28501
28502DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
28503 var l = lStart;
28504 var r = rStart;
28505
28506 // Apply f() x16 times
28507 for (var i = 0; i < state.keys.length; i += 2) {
28508 var keyL = state.keys[i];
28509 var keyR = state.keys[i + 1];
28510
28511 // f(r, k)
28512 utils.expand(r, state.tmp, 0);
28513
28514 keyL ^= state.tmp[0];
28515 keyR ^= state.tmp[1];
28516 var s = utils.substitute(keyL, keyR);
28517 var f = utils.permute(s);
28518
28519 var t = r;
28520 r = (l ^ f) >>> 0;
28521 l = t;
28522 }
28523
28524 // Reverse Initial Permutation
28525 utils.rip(r, l, out, off);
28526};
28527
28528DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
28529 var l = rStart;
28530 var r = lStart;
28531
28532 // Apply f() x16 times
28533 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
28534 var keyL = state.keys[i];
28535 var keyR = state.keys[i + 1];
28536
28537 // f(r, k)
28538 utils.expand(l, state.tmp, 0);
28539
28540 keyL ^= state.tmp[0];
28541 keyR ^= state.tmp[1];
28542 var s = utils.substitute(keyL, keyR);
28543 var f = utils.permute(s);
28544
28545 var t = l;
28546 l = (r ^ f) >>> 0;
28547 r = t;
28548 }
28549
28550 // Reverse Initial Permutation
28551 utils.rip(l, r, out, off);
28552};
28553}, {"minimalistic-assert":189,"inherits":149,"../des":186}],191: [function (exports, require, module, global) {'use strict';
28554
28555var assert = require('minimalistic-assert');
28556var inherits = require('inherits');
28557
28558var proto = {};
28559
28560function CBCState(iv) {
28561 assert.equal(iv.length, 8, 'Invalid IV length');
28562
28563 this.iv = new Array(8);
28564 for (var i = 0; i < this.iv.length; i++)
28565 this.iv[i] = iv[i];
28566}
28567
28568function instantiate(Base) {
28569 function CBC(options) {
28570 Base.call(this, options);
28571 this._cbcInit();
28572 }
28573 inherits(CBC, Base);
28574
28575 var keys = Object.keys(proto);
28576 for (var i = 0; i < keys.length; i++) {
28577 var key = keys[i];
28578 CBC.prototype[key] = proto[key];
28579 }
28580
28581 CBC.create = function create(options) {
28582 return new CBC(options);
28583 };
28584
28585 return CBC;
28586}
28587
28588exports.instantiate = instantiate;
28589
28590proto._cbcInit = function _cbcInit() {
28591 var state = new CBCState(this.options.iv);
28592 this._cbcState = state;
28593};
28594
28595proto._update = function _update(inp, inOff, out, outOff) {
28596 var state = this._cbcState;
28597 var superProto = this.constructor.super_.prototype;
28598
28599 var iv = state.iv;
28600 if (this.type === 'encrypt') {
28601 for (var i = 0; i < this.blockSize; i++)
28602 iv[i] ^= inp[inOff + i];
28603
28604 superProto._update.call(this, iv, 0, out, outOff);
28605
28606 for (var i = 0; i < this.blockSize; i++)
28607 iv[i] = out[outOff + i];
28608 } else {
28609 superProto._update.call(this, inp, inOff, out, outOff);
28610
28611 for (var i = 0; i < this.blockSize; i++)
28612 out[outOff + i] ^= iv[i];
28613
28614 for (var i = 0; i < this.blockSize; i++)
28615 iv[i] = inp[inOff + i];
28616 }
28617};
28618}, {"minimalistic-assert":189,"inherits":149}],192: [function (exports, require, module, global) {'use strict';
28619
28620var assert = require('minimalistic-assert');
28621var inherits = require('inherits');
28622
28623var des = require('../des');
28624var Cipher = des.Cipher;
28625var DES = des.DES;
28626
28627function EDEState(type, key) {
28628 assert.equal(key.length, 24, 'Invalid key length');
28629
28630 var k1 = key.slice(0, 8);
28631 var k2 = key.slice(8, 16);
28632 var k3 = key.slice(16, 24);
28633
28634 if (type === 'encrypt') {
28635 this.ciphers = [
28636 DES.create({ type: 'encrypt', key: k1 }),
28637 DES.create({ type: 'decrypt', key: k2 }),
28638 DES.create({ type: 'encrypt', key: k3 })
28639 ];
28640 } else {
28641 this.ciphers = [
28642 DES.create({ type: 'decrypt', key: k3 }),
28643 DES.create({ type: 'encrypt', key: k2 }),
28644 DES.create({ type: 'decrypt', key: k1 })
28645 ];
28646 }
28647}
28648
28649function EDE(options) {
28650 Cipher.call(this, options);
28651
28652 var state = new EDEState(this.type, this.options.key);
28653 this._edeState = state;
28654}
28655inherits(EDE, Cipher);
28656
28657module.exports = EDE;
28658
28659EDE.create = function create(options) {
28660 return new EDE(options);
28661};
28662
28663EDE.prototype._update = function _update(inp, inOff, out, outOff) {
28664 var state = this._edeState;
28665
28666 state.ciphers[0]._update(inp, inOff, out, outOff);
28667 state.ciphers[1]._update(out, outOff, out, outOff);
28668 state.ciphers[2]._update(out, outOff, out, outOff);
28669};
28670
28671EDE.prototype._pad = DES.prototype._pad;
28672EDE.prototype._unpad = DES.prototype._unpad;
28673}, {"minimalistic-assert":189,"inherits":149,"../des":186}],193: [function (exports, require, module, global) {exports['des-ecb'] = {
28674 key: 8,
28675 iv: 0
28676}
28677exports['des-cbc'] = exports.des = {
28678 key: 8,
28679 iv: 8
28680}
28681exports['des-ede3-cbc'] = exports.des3 = {
28682 key: 24,
28683 iv: 8
28684}
28685exports['des-ede3'] = {
28686 key: 24,
28687 iv: 0
28688}
28689exports['des-ede-cbc'] = {
28690 key: 16,
28691 iv: 8
28692}
28693exports['des-ede'] = {
28694 key: 16,
28695 iv: 0
28696}
28697}, {}],194: [function (exports, require, module, global) {var generatePrime = require('./lib/generatePrime');
28698var primes = require('./lib/primes');
28699
28700var DH = require('./lib/dh');
28701
28702function getDiffieHellman(mod) {
28703 var prime = new Buffer(primes[mod].prime, 'hex');
28704 var gen = new Buffer(primes[mod].gen, 'hex');
28705
28706 return new DH(prime, gen);
28707}
28708
28709function createDiffieHellman(prime, enc, generator, genc) {
28710 if (Buffer.isBuffer(enc) || (typeof enc === 'string' && ['hex', 'binary', 'base64'].indexOf(enc) === -1)) {
28711 genc = generator;
28712 generator = enc;
28713 enc = undefined;
28714 }
28715
28716 enc = enc || 'binary';
28717 genc = genc || 'binary';
28718 generator = generator || new Buffer([2]);
28719
28720 if (!Buffer.isBuffer(generator)) {
28721 generator = new Buffer(generator, genc);
28722 }
28723
28724 if (typeof prime === 'number') {
28725 return new DH(generatePrime(prime, generator), generator, true);
28726 }
28727
28728 if (!Buffer.isBuffer(prime)) {
28729 prime = new Buffer(prime, enc);
28730 }
28731
28732 return new DH(prime, generator, true);
28733}
28734
28735exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman;
28736exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman;
28737}, {"./lib/generatePrime":195,"./lib/primes":199,"./lib/dh":200}],195: [function (exports, require, module, global) {var randomBytes = require('randombytes');
28738module.exports = findPrime;
28739findPrime.simpleSieve = simpleSieve;
28740findPrime.fermatTest = fermatTest;
28741var BN = require('bn.js');
28742var TWENTYFOUR = new BN(24);
28743var MillerRabin = require('miller-rabin');
28744var millerRabin = new MillerRabin();
28745var ONE = new BN(1);
28746var TWO = new BN(2);
28747var FIVE = new BN(5);
28748var SIXTEEN = new BN(16);
28749var EIGHT = new BN(8);
28750var TEN = new BN(10);
28751var THREE = new BN(3);
28752var SEVEN = new BN(7);
28753var ELEVEN = new BN(11);
28754var FOUR = new BN(4);
28755var TWELVE = new BN(12);
28756var primes = null;
28757
28758function _getPrimes() {
28759 if (primes !== null)
28760 return primes;
28761
28762 var limit = 0x100000;
28763 var res = [];
28764 res[0] = 2;
28765 for (var i = 1, k = 3; k < limit; k += 2) {
28766 var sqrt = Math.ceil(Math.sqrt(k));
28767 for (var j = 0; j < i && res[j] <= sqrt; j++)
28768 if (k % res[j] === 0)
28769 break;
28770
28771 if (i !== j && res[j] <= sqrt)
28772 continue;
28773
28774 res[i++] = k;
28775 }
28776 primes = res;
28777 return res;
28778}
28779
28780function simpleSieve(p) {
28781 var primes = _getPrimes();
28782
28783 for (var i = 0; i < primes.length; i++)
28784 if (p.modn(primes[i]) === 0) {
28785 if (p.cmpn(primes[i]) === 0) {
28786 return true;
28787 } else {
28788 return false;
28789 }
28790 }
28791
28792 return true;
28793}
28794
28795function fermatTest(p) {
28796 var red = BN.mont(p);
28797 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
28798}
28799
28800function findPrime(bits, gen) {
28801 if (bits < 16) {
28802 // this is what openssl does
28803 if (gen === 2 || gen === 5) {
28804 return new BN([0x8c, 0x7b]);
28805 } else {
28806 return new BN([0x8c, 0x27]);
28807 }
28808 }
28809 gen = new BN(gen);
28810 var runs, comp;
28811 function generateRandom(bits) {
28812 runs = -1;
28813 var out = new BN(randomBytes(Math.ceil(bits / 8)));
28814 while (out.bitLength() > bits) {
28815 out.ishrn(1);
28816 }
28817 if (out.isEven()) {
28818 out.iadd(ONE);
28819 }
28820 if (!out.testn(1)) {
28821 out.iadd(TWO);
28822 }
28823 if (!gen.cmp(TWO)) {
28824 while (out.mod(TWENTYFOUR).cmp(ELEVEN)) {
28825 out.iadd(FOUR);
28826 }
28827 comp = {
28828 major: [TWENTYFOUR],
28829 minor: [TWELVE]
28830 };
28831 } else if (!gen.cmp(FIVE)) {
28832 rem = out.mod(TEN);
28833 while (rem.cmp(THREE)) {
28834 out.iadd(FOUR);
28835 rem = out.mod(TEN);
28836 }
28837 comp = {
28838 major: [FOUR, SIXTEEN],
28839 minor: [TWO, EIGHT]
28840 };
28841 } else {
28842 comp = {
28843 major: [FOUR],
28844 minor: [TWO]
28845 };
28846 }
28847 return out;
28848 }
28849 var num = generateRandom(bits);
28850
28851 var n2 = num.shrn(1);
28852
28853 while (true) {
28854 while (num.bitLength() > bits) {
28855 num = generateRandom(bits);
28856 n2 = num.shrn(1);
28857 }
28858 runs++;
28859 if (simpleSieve(n2) && simpleSieve(num) &&
28860 fermatTest(n2) && fermatTest(num) &&
28861 millerRabin.test(n2) && millerRabin.test(num)) {
28862 return num;
28863 }
28864 num.iadd(comp.major[runs%comp.major.length]);
28865 n2.iadd(comp.minor[runs%comp.minor.length]);
28866 }
28867
28868}}, {"randombytes":147,"bn.js":196,"miller-rabin":197}],196: [function (exports, require, module, global) {(function (module, exports) {
28869
28870'use strict';
28871
28872// Utils
28873
28874function assert(val, msg) {
28875 if (!val)
28876 throw new Error(msg || 'Assertion failed');
28877}
28878
28879// Could use `inherits` module, but don't want to move from single file
28880// architecture yet.
28881function inherits(ctor, superCtor) {
28882 ctor.super_ = superCtor;
28883 var TempCtor = function () {};
28884 TempCtor.prototype = superCtor.prototype;
28885 ctor.prototype = new TempCtor();
28886 ctor.prototype.constructor = ctor;
28887}
28888
28889// BN
28890
28891function BN(number, base, endian) {
28892 // May be `new BN(bn)` ?
28893 if (number !== null &&
28894 typeof number === 'object' &&
28895 Array.isArray(number.words)) {
28896 return number;
28897 }
28898
28899 this.sign = false;
28900 this.words = null;
28901 this.length = 0;
28902
28903 // Reduction context
28904 this.red = null;
28905
28906 if (base === 'le' || base === 'be') {
28907 endian = base;
28908 base = 10;
28909 }
28910
28911 if (number !== null)
28912 this._init(number || 0, base || 10, endian || 'be');
28913}
28914if (typeof module === 'object')
28915 module.exports = BN;
28916else
28917 exports.BN = BN;
28918
28919BN.BN = BN;
28920BN.wordSize = 26;
28921
28922BN.prototype._init = function init(number, base, endian) {
28923 if (typeof number === 'number') {
28924 return this._initNumber(number, base, endian);
28925 } else if (typeof number === 'object') {
28926 return this._initArray(number, base, endian);
28927 }
28928 if (base === 'hex')
28929 base = 16;
28930 assert(base === (base | 0) && base >= 2 && base <= 36);
28931
28932 number = number.toString().replace(/\s+/g, '');
28933 var start = 0;
28934 if (number[0] === '-')
28935 start++;
28936
28937 if (base === 16)
28938 this._parseHex(number, start);
28939 else
28940 this._parseBase(number, base, start);
28941
28942 if (number[0] === '-')
28943 this.sign = true;
28944
28945 this.strip();
28946
28947 if (endian !== 'le')
28948 return;
28949
28950 this._initArray(this.toArray(), base, endian);
28951};
28952
28953BN.prototype._initNumber = function _initNumber(number, base, endian) {
28954 if (number < 0) {
28955 this.sign = true;
28956 number = -number;
28957 }
28958 if (number < 0x4000000) {
28959 this.words = [ number & 0x3ffffff ];
28960 this.length = 1;
28961 } else if (number < 0x10000000000000) {
28962 this.words = [
28963 number & 0x3ffffff,
28964 (number / 0x4000000) & 0x3ffffff
28965 ];
28966 this.length = 2;
28967 } else {
28968 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
28969 this.words = [
28970 number & 0x3ffffff,
28971 (number / 0x4000000) & 0x3ffffff,
28972 1
28973 ];
28974 this.length = 3;
28975 }
28976
28977 if (endian !== 'le')
28978 return;
28979
28980 // Reverse the bytes
28981 this._initArray(this.toArray(), base, endian);
28982};
28983
28984BN.prototype._initArray = function _initArray(number, base, endian) {
28985 // Perhaps a Uint8Array
28986 assert(typeof number.length === 'number');
28987 if (number.length <= 0) {
28988 this.words = [ 0 ];
28989 this.length = 1;
28990 return this;
28991 }
28992
28993 this.length = Math.ceil(number.length / 3);
28994 this.words = new Array(this.length);
28995 for (var i = 0; i < this.length; i++)
28996 this.words[i] = 0;
28997
28998 var off = 0;
28999 if (endian === 'be') {
29000 for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
29001 var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
29002 this.words[j] |= (w << off) & 0x3ffffff;
29003 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
29004 off += 24;
29005 if (off >= 26) {
29006 off -= 26;
29007 j++;
29008 }
29009 }
29010 } else if (endian === 'le') {
29011 for (var i = 0, j = 0; i < number.length; i += 3) {
29012 var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
29013 this.words[j] |= (w << off) & 0x3ffffff;
29014 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
29015 off += 24;
29016 if (off >= 26) {
29017 off -= 26;
29018 j++;
29019 }
29020 }
29021 }
29022 return this.strip();
29023};
29024
29025function parseHex(str, start, end) {
29026 var r = 0;
29027 var len = Math.min(str.length, end);
29028 for (var i = start; i < len; i++) {
29029 var c = str.charCodeAt(i) - 48;
29030
29031 r <<= 4;
29032
29033 // 'a' - 'f'
29034 if (c >= 49 && c <= 54)
29035 r |= c - 49 + 0xa;
29036
29037 // 'A' - 'F'
29038 else if (c >= 17 && c <= 22)
29039 r |= c - 17 + 0xa;
29040
29041 // '0' - '9'
29042 else
29043 r |= c & 0xf;
29044 }
29045 return r;
29046}
29047
29048BN.prototype._parseHex = function _parseHex(number, start) {
29049 // Create possibly bigger array to ensure that it fits the number
29050 this.length = Math.ceil((number.length - start) / 6);
29051 this.words = new Array(this.length);
29052 for (var i = 0; i < this.length; i++)
29053 this.words[i] = 0;
29054
29055 // Scan 24-bit chunks and add them to the number
29056 var off = 0;
29057 for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
29058 var w = parseHex(number, i, i + 6);
29059 this.words[j] |= (w << off) & 0x3ffffff;
29060 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
29061 off += 24;
29062 if (off >= 26) {
29063 off -= 26;
29064 j++;
29065 }
29066 }
29067 if (i + 6 !== start) {
29068 var w = parseHex(number, start, i + 6);
29069 this.words[j] |= (w << off) & 0x3ffffff;
29070 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
29071 }
29072 this.strip();
29073};
29074
29075function parseBase(str, start, end, mul) {
29076 var r = 0;
29077 var len = Math.min(str.length, end);
29078 for (var i = start; i < len; i++) {
29079 var c = str.charCodeAt(i) - 48;
29080
29081 r *= mul;
29082
29083 // 'a'
29084 if (c >= 49)
29085 r += c - 49 + 0xa;
29086
29087 // 'A'
29088 else if (c >= 17)
29089 r += c - 17 + 0xa;
29090
29091 // '0' - '9'
29092 else
29093 r += c;
29094 }
29095 return r;
29096}
29097
29098BN.prototype._parseBase = function _parseBase(number, base, start) {
29099 // Initialize as zero
29100 this.words = [ 0 ];
29101 this.length = 1;
29102
29103 // Find length of limb in base
29104 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
29105 limbLen++;
29106 limbLen--;
29107 limbPow = (limbPow / base) | 0;
29108
29109 var total = number.length - start;
29110 var mod = total % limbLen;
29111 var end = Math.min(total, total - mod) + start;
29112
29113 var word = 0;
29114 for (var i = start; i < end; i += limbLen) {
29115 word = parseBase(number, i, i + limbLen, base);
29116
29117 this.imuln(limbPow);
29118 if (this.words[0] + word < 0x4000000)
29119 this.words[0] += word;
29120 else
29121 this._iaddn(word);
29122 }
29123
29124 if (mod !== 0) {
29125 var pow = 1;
29126 var word = parseBase(number, i, number.length, base);
29127
29128 for (var i = 0; i < mod; i++)
29129 pow *= base;
29130 this.imuln(pow);
29131 if (this.words[0] + word < 0x4000000)
29132 this.words[0] += word;
29133 else
29134 this._iaddn(word);
29135 }
29136};
29137
29138BN.prototype.copy = function copy(dest) {
29139 dest.words = new Array(this.length);
29140 for (var i = 0; i < this.length; i++)
29141 dest.words[i] = this.words[i];
29142 dest.length = this.length;
29143 dest.sign = this.sign;
29144 dest.red = this.red;
29145};
29146
29147BN.prototype.clone = function clone() {
29148 var r = new BN(null);
29149 this.copy(r);
29150 return r;
29151};
29152
29153// Remove leading `0` from `this`
29154BN.prototype.strip = function strip() {
29155 while (this.length > 1 && this.words[this.length - 1] === 0)
29156 this.length--;
29157 return this._normSign();
29158};
29159
29160BN.prototype._normSign = function _normSign() {
29161 // -0 = 0
29162 if (this.length === 1 && this.words[0] === 0)
29163 this.sign = false;
29164 return this;
29165};
29166
29167BN.prototype.inspect = function inspect() {
29168 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
29169};
29170
29171/*
29172
29173var zeros = [];
29174var groupSizes = [];
29175var groupBases = [];
29176
29177var s = '';
29178var i = -1;
29179while (++i < BN.wordSize) {
29180 zeros[i] = s;
29181 s += '0';
29182}
29183groupSizes[0] = 0;
29184groupSizes[1] = 0;
29185groupBases[0] = 0;
29186groupBases[1] = 0;
29187var base = 2 - 1;
29188while (++base < 36 + 1) {
29189 var groupSize = 0;
29190 var groupBase = 1;
29191 while (groupBase < (1 << BN.wordSize) / base) {
29192 groupBase *= base;
29193 groupSize += 1;
29194 }
29195 groupSizes[base] = groupSize;
29196 groupBases[base] = groupBase;
29197}
29198
29199*/
29200
29201var zeros = [
29202 '',
29203 '0',
29204 '00',
29205 '000',
29206 '0000',
29207 '00000',
29208 '000000',
29209 '0000000',
29210 '00000000',
29211 '000000000',
29212 '0000000000',
29213 '00000000000',
29214 '000000000000',
29215 '0000000000000',
29216 '00000000000000',
29217 '000000000000000',
29218 '0000000000000000',
29219 '00000000000000000',
29220 '000000000000000000',
29221 '0000000000000000000',
29222 '00000000000000000000',
29223 '000000000000000000000',
29224 '0000000000000000000000',
29225 '00000000000000000000000',
29226 '000000000000000000000000',
29227 '0000000000000000000000000'
29228];
29229
29230var groupSizes = [
29231 0, 0,
29232 25, 16, 12, 11, 10, 9, 8,
29233 8, 7, 7, 7, 7, 6, 6,
29234 6, 6, 6, 6, 6, 5, 5,
29235 5, 5, 5, 5, 5, 5, 5,
29236 5, 5, 5, 5, 5, 5, 5
29237];
29238
29239var groupBases = [
29240 0, 0,
29241 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
29242 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
29243 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
29244 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
29245 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
29246];
29247
29248BN.prototype.toString = function toString(base, padding) {
29249 base = base || 10;
29250 if (base === 16 || base === 'hex') {
29251 var out = '';
29252 var off = 0;
29253 var padding = padding | 0 || 1;
29254 var carry = 0;
29255 for (var i = 0; i < this.length; i++) {
29256 var w = this.words[i];
29257 var word = (((w << off) | carry) & 0xffffff).toString(16);
29258 carry = (w >>> (24 - off)) & 0xffffff;
29259 if (carry !== 0 || i !== this.length - 1)
29260 out = zeros[6 - word.length] + word + out;
29261 else
29262 out = word + out;
29263 off += 2;
29264 if (off >= 26) {
29265 off -= 26;
29266 i--;
29267 }
29268 }
29269 if (carry !== 0)
29270 out = carry.toString(16) + out;
29271 while (out.length % padding !== 0)
29272 out = '0' + out;
29273 if (this.sign)
29274 out = '-' + out;
29275 return out;
29276 } else if (base === (base | 0) && base >= 2 && base <= 36) {
29277 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
29278 var groupSize = groupSizes[base];
29279 // var groupBase = Math.pow(base, groupSize);
29280 var groupBase = groupBases[base];
29281 var out = '';
29282 var c = this.clone();
29283 c.sign = false;
29284 while (c.cmpn(0) !== 0) {
29285 var r = c.modn(groupBase).toString(base);
29286 c = c.idivn(groupBase);
29287
29288 if (c.cmpn(0) !== 0)
29289 out = zeros[groupSize - r.length] + r + out;
29290 else
29291 out = r + out;
29292 }
29293 if (this.cmpn(0) === 0)
29294 out = '0' + out;
29295 if (this.sign)
29296 out = '-' + out;
29297 return out;
29298 } else {
29299 assert(false, 'Base should be between 2 and 36');
29300 }
29301};
29302
29303BN.prototype.toJSON = function toJSON() {
29304 return this.toString(16);
29305};
29306
29307BN.prototype.toArray = function toArray(endian) {
29308 this.strip();
29309 var res = new Array(this.byteLength());
29310 res[0] = 0;
29311
29312 var q = this.clone();
29313 if (endian !== 'le') {
29314 // Assume big-endian
29315 for (var i = 0; q.cmpn(0) !== 0; i++) {
29316 var b = q.andln(0xff);
29317 q.ishrn(8);
29318
29319 res[res.length - i - 1] = b;
29320 }
29321 } else {
29322 // Assume little-endian
29323 for (var i = 0; q.cmpn(0) !== 0; i++) {
29324 var b = q.andln(0xff);
29325 q.ishrn(8);
29326
29327 res[i] = b;
29328 }
29329 }
29330
29331 return res;
29332};
29333
29334if (Math.clz32) {
29335 BN.prototype._countBits = function _countBits(w) {
29336 return 32 - Math.clz32(w);
29337 };
29338} else {
29339 BN.prototype._countBits = function _countBits(w) {
29340 var t = w;
29341 var r = 0;
29342 if (t >= 0x1000) {
29343 r += 13;
29344 t >>>= 13;
29345 }
29346 if (t >= 0x40) {
29347 r += 7;
29348 t >>>= 7;
29349 }
29350 if (t >= 0x8) {
29351 r += 4;
29352 t >>>= 4;
29353 }
29354 if (t >= 0x02) {
29355 r += 2;
29356 t >>>= 2;
29357 }
29358 return r + t;
29359 };
29360}
29361
29362BN.prototype._zeroBits = function _zeroBits(w) {
29363 // Short-cut
29364 if (w === 0)
29365 return 26;
29366
29367 var t = w;
29368 var r = 0;
29369 if ((t & 0x1fff) === 0) {
29370 r += 13;
29371 t >>>= 13;
29372 }
29373 if ((t & 0x7f) === 0) {
29374 r += 7;
29375 t >>>= 7;
29376 }
29377 if ((t & 0xf) === 0) {
29378 r += 4;
29379 t >>>= 4;
29380 }
29381 if ((t & 0x3) === 0) {
29382 r += 2;
29383 t >>>= 2;
29384 }
29385 if ((t & 0x1) === 0)
29386 r++;
29387 return r;
29388};
29389
29390// Return number of used bits in a BN
29391BN.prototype.bitLength = function bitLength() {
29392 var hi = 0;
29393 var w = this.words[this.length - 1];
29394 var hi = this._countBits(w);
29395 return (this.length - 1) * 26 + hi;
29396};
29397
29398// Number of trailing zero bits
29399BN.prototype.zeroBits = function zeroBits() {
29400 if (this.cmpn(0) === 0)
29401 return 0;
29402
29403 var r = 0;
29404 for (var i = 0; i < this.length; i++) {
29405 var b = this._zeroBits(this.words[i]);
29406 r += b;
29407 if (b !== 26)
29408 break;
29409 }
29410 return r;
29411};
29412
29413BN.prototype.byteLength = function byteLength() {
29414 return Math.ceil(this.bitLength() / 8);
29415};
29416
29417// Return negative clone of `this`
29418BN.prototype.neg = function neg() {
29419 if (this.cmpn(0) === 0)
29420 return this.clone();
29421
29422 var r = this.clone();
29423 r.sign = !this.sign;
29424 return r;
29425};
29426
29427
29428// Or `num` with `this` in-place
29429BN.prototype.ior = function ior(num) {
29430 this.sign = this.sign || num.sign;
29431
29432 while (this.length < num.length)
29433 this.words[this.length++] = 0;
29434
29435 for (var i = 0; i < num.length; i++)
29436 this.words[i] = this.words[i] | num.words[i];
29437
29438 return this.strip();
29439};
29440
29441
29442// Or `num` with `this`
29443BN.prototype.or = function or(num) {
29444 if (this.length > num.length)
29445 return this.clone().ior(num);
29446 else
29447 return num.clone().ior(this);
29448};
29449
29450
29451// And `num` with `this` in-place
29452BN.prototype.iand = function iand(num) {
29453 this.sign = this.sign && num.sign;
29454
29455 // b = min-length(num, this)
29456 var b;
29457 if (this.length > num.length)
29458 b = num;
29459 else
29460 b = this;
29461
29462 for (var i = 0; i < b.length; i++)
29463 this.words[i] = this.words[i] & num.words[i];
29464
29465 this.length = b.length;
29466
29467 return this.strip();
29468};
29469
29470
29471// And `num` with `this`
29472BN.prototype.and = function and(num) {
29473 if (this.length > num.length)
29474 return this.clone().iand(num);
29475 else
29476 return num.clone().iand(this);
29477};
29478
29479
29480// Xor `num` with `this` in-place
29481BN.prototype.ixor = function ixor(num) {
29482 this.sign = this.sign || num.sign;
29483
29484 // a.length > b.length
29485 var a;
29486 var b;
29487 if (this.length > num.length) {
29488 a = this;
29489 b = num;
29490 } else {
29491 a = num;
29492 b = this;
29493 }
29494
29495 for (var i = 0; i < b.length; i++)
29496 this.words[i] = a.words[i] ^ b.words[i];
29497
29498 if (this !== a)
29499 for (; i < a.length; i++)
29500 this.words[i] = a.words[i];
29501
29502 this.length = a.length;
29503
29504 return this.strip();
29505};
29506
29507
29508// Xor `num` with `this`
29509BN.prototype.xor = function xor(num) {
29510 if (this.length > num.length)
29511 return this.clone().ixor(num);
29512 else
29513 return num.clone().ixor(this);
29514};
29515
29516
29517// Set `bit` of `this`
29518BN.prototype.setn = function setn(bit, val) {
29519 assert(typeof bit === 'number' && bit >= 0);
29520
29521 var off = (bit / 26) | 0;
29522 var wbit = bit % 26;
29523
29524 while (this.length <= off)
29525 this.words[this.length++] = 0;
29526
29527 if (val)
29528 this.words[off] = this.words[off] | (1 << wbit);
29529 else
29530 this.words[off] = this.words[off] & ~(1 << wbit);
29531
29532 return this.strip();
29533};
29534
29535
29536// Add `num` to `this` in-place
29537BN.prototype.iadd = function iadd(num) {
29538 // negative + positive
29539 if (this.sign && !num.sign) {
29540 this.sign = false;
29541 var r = this.isub(num);
29542 this.sign = !this.sign;
29543 return this._normSign();
29544
29545 // positive + negative
29546 } else if (!this.sign && num.sign) {
29547 num.sign = false;
29548 var r = this.isub(num);
29549 num.sign = true;
29550 return r._normSign();
29551 }
29552
29553 // a.length > b.length
29554 var a;
29555 var b;
29556 if (this.length > num.length) {
29557 a = this;
29558 b = num;
29559 } else {
29560 a = num;
29561 b = this;
29562 }
29563
29564 var carry = 0;
29565 for (var i = 0; i < b.length; i++) {
29566 var r = a.words[i] + b.words[i] + carry;
29567 this.words[i] = r & 0x3ffffff;
29568 carry = r >>> 26;
29569 }
29570 for (; carry !== 0 && i < a.length; i++) {
29571 var r = a.words[i] + carry;
29572 this.words[i] = r & 0x3ffffff;
29573 carry = r >>> 26;
29574 }
29575
29576 this.length = a.length;
29577 if (carry !== 0) {
29578 this.words[this.length] = carry;
29579 this.length++;
29580 // Copy the rest of the words
29581 } else if (a !== this) {
29582 for (; i < a.length; i++)
29583 this.words[i] = a.words[i];
29584 }
29585
29586 return this;
29587};
29588
29589// Add `num` to `this`
29590BN.prototype.add = function add(num) {
29591 if (num.sign && !this.sign) {
29592 num.sign = false;
29593 var res = this.sub(num);
29594 num.sign = true;
29595 return res;
29596 } else if (!num.sign && this.sign) {
29597 this.sign = false;
29598 var res = num.sub(this);
29599 this.sign = true;
29600 return res;
29601 }
29602
29603 if (this.length > num.length)
29604 return this.clone().iadd(num);
29605 else
29606 return num.clone().iadd(this);
29607};
29608
29609// Subtract `num` from `this` in-place
29610BN.prototype.isub = function isub(num) {
29611 // this - (-num) = this + num
29612 if (num.sign) {
29613 num.sign = false;
29614 var r = this.iadd(num);
29615 num.sign = true;
29616 return r._normSign();
29617
29618 // -this - num = -(this + num)
29619 } else if (this.sign) {
29620 this.sign = false;
29621 this.iadd(num);
29622 this.sign = true;
29623 return this._normSign();
29624 }
29625
29626 // At this point both numbers are positive
29627 var cmp = this.cmp(num);
29628
29629 // Optimization - zeroify
29630 if (cmp === 0) {
29631 this.sign = false;
29632 this.length = 1;
29633 this.words[0] = 0;
29634 return this;
29635 }
29636
29637 // a > b
29638 var a;
29639 var b;
29640 if (cmp > 0) {
29641 a = this;
29642 b = num;
29643 } else {
29644 a = num;
29645 b = this;
29646 }
29647
29648 var carry = 0;
29649 for (var i = 0; i < b.length; i++) {
29650 var r = a.words[i] - b.words[i] + carry;
29651 carry = r >> 26;
29652 this.words[i] = r & 0x3ffffff;
29653 }
29654 for (; carry !== 0 && i < a.length; i++) {
29655 var r = a.words[i] + carry;
29656 carry = r >> 26;
29657 this.words[i] = r & 0x3ffffff;
29658 }
29659
29660 // Copy rest of the words
29661 if (carry === 0 && i < a.length && a !== this)
29662 for (; i < a.length; i++)
29663 this.words[i] = a.words[i];
29664 this.length = Math.max(this.length, i);
29665
29666 if (a !== this)
29667 this.sign = true;
29668
29669 return this.strip();
29670};
29671
29672// Subtract `num` from `this`
29673BN.prototype.sub = function sub(num) {
29674 return this.clone().isub(num);
29675};
29676
29677/*
29678// NOTE: This could be potentionally used to generate loop-less multiplications
29679function _genCombMulTo(alen, blen) {
29680 var len = alen + blen - 1;
29681 var src = [
29682 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
29683 'mask = 0x3ffffff, shift = 0x4000000;',
29684 'out.length = ' + len + ';'
29685 ];
29686 for (var k = 0; k < len; k++) {
29687 var minJ = Math.max(0, k - alen + 1);
29688 var maxJ = Math.min(k, blen - 1);
29689
29690 for (var j = minJ; j <= maxJ; j++) {
29691 var i = k - j;
29692 var mul = 'a[' + i + '] * b[' + j + ']';
29693
29694 if (j === minJ) {
29695 src.push('w = ' + mul + ' + c;');
29696 src.push('c = (w / shift) | 0;');
29697 } else {
29698 src.push('w += ' + mul + ';');
29699 src.push('c += (w / shift) | 0;');
29700 }
29701 src.push('w &= mask;');
29702 }
29703 src.push('o[' + k + '] = w;');
29704 }
29705 src.push('if (c !== 0) {',
29706 ' o[' + k + '] = c;',
29707 ' out.length++;',
29708 '}',
29709 'return out;');
29710
29711 return src.join('\n');
29712}
29713*/
29714
29715BN.prototype._smallMulTo = function _smallMulTo(num, out) {
29716 out.sign = num.sign !== this.sign;
29717 out.length = this.length + num.length;
29718
29719 var carry = 0;
29720 for (var k = 0; k < out.length - 1; k++) {
29721 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
29722 // note that ncarry could be >= 0x3ffffff
29723 var ncarry = carry >>> 26;
29724 var rword = carry & 0x3ffffff;
29725 var maxJ = Math.min(k, num.length - 1);
29726 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
29727 var i = k - j;
29728 var a = this.words[i] | 0;
29729 var b = num.words[j] | 0;
29730 var r = a * b;
29731
29732 var lo = r & 0x3ffffff;
29733 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
29734 lo = (lo + rword) | 0;
29735 rword = lo & 0x3ffffff;
29736 ncarry = (ncarry + (lo >>> 26)) | 0;
29737 }
29738 out.words[k] = rword;
29739 carry = ncarry;
29740 }
29741 if (carry !== 0) {
29742 out.words[k] = carry;
29743 } else {
29744 out.length--;
29745 }
29746
29747 return out.strip();
29748};
29749
29750BN.prototype._bigMulTo = function _bigMulTo(num, out) {
29751 out.sign = num.sign !== this.sign;
29752 out.length = this.length + num.length;
29753
29754 var carry = 0;
29755 var hncarry = 0;
29756 for (var k = 0; k < out.length - 1; k++) {
29757 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
29758 // note that ncarry could be >= 0x3ffffff
29759 var ncarry = hncarry;
29760 hncarry = 0;
29761 var rword = carry & 0x3ffffff;
29762 var maxJ = Math.min(k, num.length - 1);
29763 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
29764 var i = k - j;
29765 var a = this.words[i] | 0;
29766 var b = num.words[j] | 0;
29767 var r = a * b;
29768
29769 var lo = r & 0x3ffffff;
29770 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
29771 lo = (lo + rword) | 0;
29772 rword = lo & 0x3ffffff;
29773 ncarry = (ncarry + (lo >>> 26)) | 0;
29774
29775 hncarry += ncarry >>> 26;
29776 ncarry &= 0x3ffffff;
29777 }
29778 out.words[k] = rword;
29779 carry = ncarry;
29780 ncarry = hncarry;
29781 }
29782 if (carry !== 0) {
29783 out.words[k] = carry;
29784 } else {
29785 out.length--;
29786 }
29787
29788 return out.strip();
29789};
29790
29791BN.prototype.mulTo = function mulTo(num, out) {
29792 var res;
29793 if (this.length + num.length < 63)
29794 res = this._smallMulTo(num, out);
29795 else
29796 res = this._bigMulTo(num, out);
29797 return res;
29798};
29799
29800// Multiply `this` by `num`
29801BN.prototype.mul = function mul(num) {
29802 var out = new BN(null);
29803 out.words = new Array(this.length + num.length);
29804 return this.mulTo(num, out);
29805};
29806
29807// In-place Multiplication
29808BN.prototype.imul = function imul(num) {
29809 if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
29810 this.words[0] = 0;
29811 this.length = 1;
29812 return this;
29813 }
29814
29815 var tlen = this.length;
29816 var nlen = num.length;
29817
29818 this.sign = num.sign !== this.sign;
29819 this.length = this.length + num.length;
29820 this.words[this.length - 1] = 0;
29821
29822 for (var k = this.length - 2; k >= 0; k--) {
29823 // Sum all words with the same `i + j = k` and accumulate `carry`,
29824 // note that carry could be >= 0x3ffffff
29825 var carry = 0;
29826 var rword = 0;
29827 var maxJ = Math.min(k, nlen - 1);
29828 for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
29829 var i = k - j;
29830 var a = this.words[i];
29831 var b = num.words[j];
29832 var r = a * b;
29833
29834 var lo = r & 0x3ffffff;
29835 carry += (r / 0x4000000) | 0;
29836 lo += rword;
29837 rword = lo & 0x3ffffff;
29838 carry += lo >>> 26;
29839 }
29840 this.words[k] = rword;
29841 this.words[k + 1] += carry;
29842 carry = 0;
29843 }
29844
29845 // Propagate overflows
29846 var carry = 0;
29847 for (var i = 1; i < this.length; i++) {
29848 var w = this.words[i] + carry;
29849 this.words[i] = w & 0x3ffffff;
29850 carry = w >>> 26;
29851 }
29852
29853 return this.strip();
29854};
29855
29856BN.prototype.imuln = function imuln(num) {
29857 assert(typeof num === 'number');
29858
29859 // Carry
29860 var carry = 0;
29861 for (var i = 0; i < this.length; i++) {
29862 var w = this.words[i] * num;
29863 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
29864 carry >>= 26;
29865 carry += (w / 0x4000000) | 0;
29866 // NOTE: lo is 27bit maximum
29867 carry += lo >>> 26;
29868 this.words[i] = lo & 0x3ffffff;
29869 }
29870
29871 if (carry !== 0) {
29872 this.words[i] = carry;
29873 this.length++;
29874 }
29875
29876 return this;
29877};
29878
29879BN.prototype.muln = function muln(num) {
29880 return this.clone().imuln(num);
29881};
29882
29883// `this` * `this`
29884BN.prototype.sqr = function sqr() {
29885 return this.mul(this);
29886};
29887
29888// `this` * `this` in-place
29889BN.prototype.isqr = function isqr() {
29890 return this.mul(this);
29891};
29892
29893// Shift-left in-place
29894BN.prototype.ishln = function ishln(bits) {
29895 assert(typeof bits === 'number' && bits >= 0);
29896 var r = bits % 26;
29897 var s = (bits - r) / 26;
29898 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
29899
29900 if (r !== 0) {
29901 var carry = 0;
29902 for (var i = 0; i < this.length; i++) {
29903 var newCarry = this.words[i] & carryMask;
29904 var c = (this.words[i] - newCarry) << r;
29905 this.words[i] = c | carry;
29906 carry = newCarry >>> (26 - r);
29907 }
29908 if (carry) {
29909 this.words[i] = carry;
29910 this.length++;
29911 }
29912 }
29913
29914 if (s !== 0) {
29915 for (var i = this.length - 1; i >= 0; i--)
29916 this.words[i + s] = this.words[i];
29917 for (var i = 0; i < s; i++)
29918 this.words[i] = 0;
29919 this.length += s;
29920 }
29921
29922 return this.strip();
29923};
29924
29925// Shift-right in-place
29926// NOTE: `hint` is a lowest bit before trailing zeroes
29927// NOTE: if `extended` is present - it will be filled with destroyed bits
29928BN.prototype.ishrn = function ishrn(bits, hint, extended) {
29929 assert(typeof bits === 'number' && bits >= 0);
29930 var h;
29931 if (hint)
29932 h = (hint - (hint % 26)) / 26;
29933 else
29934 h = 0;
29935
29936 var r = bits % 26;
29937 var s = Math.min((bits - r) / 26, this.length);
29938 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
29939 var maskedWords = extended;
29940
29941 h -= s;
29942 h = Math.max(0, h);
29943
29944 // Extended mode, copy masked part
29945 if (maskedWords) {
29946 for (var i = 0; i < s; i++)
29947 maskedWords.words[i] = this.words[i];
29948 maskedWords.length = s;
29949 }
29950
29951 if (s === 0) {
29952 // No-op, we should not move anything at all
29953 } else if (this.length > s) {
29954 this.length -= s;
29955 for (var i = 0; i < this.length; i++)
29956 this.words[i] = this.words[i + s];
29957 } else {
29958 this.words[0] = 0;
29959 this.length = 1;
29960 }
29961
29962 var carry = 0;
29963 for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
29964 var word = this.words[i];
29965 this.words[i] = (carry << (26 - r)) | (word >>> r);
29966 carry = word & mask;
29967 }
29968
29969 // Push carried bits as a mask
29970 if (maskedWords && carry !== 0)
29971 maskedWords.words[maskedWords.length++] = carry;
29972
29973 if (this.length === 0) {
29974 this.words[0] = 0;
29975 this.length = 1;
29976 }
29977
29978 this.strip();
29979
29980 return this;
29981};
29982
29983// Shift-left
29984BN.prototype.shln = function shln(bits) {
29985 return this.clone().ishln(bits);
29986};
29987
29988// Shift-right
29989BN.prototype.shrn = function shrn(bits) {
29990 return this.clone().ishrn(bits);
29991};
29992
29993// Test if n bit is set
29994BN.prototype.testn = function testn(bit) {
29995 assert(typeof bit === 'number' && bit >= 0);
29996 var r = bit % 26;
29997 var s = (bit - r) / 26;
29998 var q = 1 << r;
29999
30000 // Fast case: bit is much higher than all existing words
30001 if (this.length <= s) {
30002 return false;
30003 }
30004
30005 // Check bit and return
30006 var w = this.words[s];
30007
30008 return !!(w & q);
30009};
30010
30011// Return only lowers bits of number (in-place)
30012BN.prototype.imaskn = function imaskn(bits) {
30013 assert(typeof bits === 'number' && bits >= 0);
30014 var r = bits % 26;
30015 var s = (bits - r) / 26;
30016
30017 assert(!this.sign, 'imaskn works only with positive numbers');
30018
30019 if (r !== 0)
30020 s++;
30021 this.length = Math.min(s, this.length);
30022
30023 if (r !== 0) {
30024 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
30025 this.words[this.length - 1] &= mask;
30026 }
30027
30028 return this.strip();
30029};
30030
30031// Return only lowers bits of number
30032BN.prototype.maskn = function maskn(bits) {
30033 return this.clone().imaskn(bits);
30034};
30035
30036// Add plain number `num` to `this`
30037BN.prototype.iaddn = function iaddn(num) {
30038 assert(typeof num === 'number');
30039 if (num < 0)
30040 return this.isubn(-num);
30041
30042 // Possible sign change
30043 if (this.sign) {
30044 if (this.length === 1 && this.words[0] < num) {
30045 this.words[0] = num - this.words[0];
30046 this.sign = false;
30047 return this;
30048 }
30049
30050 this.sign = false;
30051 this.isubn(num);
30052 this.sign = true;
30053 return this;
30054 }
30055
30056 // Add without checks
30057 return this._iaddn(num);
30058};
30059
30060BN.prototype._iaddn = function _iaddn(num) {
30061 this.words[0] += num;
30062
30063 // Carry
30064 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
30065 this.words[i] -= 0x4000000;
30066 if (i === this.length - 1)
30067 this.words[i + 1] = 1;
30068 else
30069 this.words[i + 1]++;
30070 }
30071 this.length = Math.max(this.length, i + 1);
30072
30073 return this;
30074};
30075
30076// Subtract plain number `num` from `this`
30077BN.prototype.isubn = function isubn(num) {
30078 assert(typeof num === 'number');
30079 if (num < 0)
30080 return this.iaddn(-num);
30081
30082 if (this.sign) {
30083 this.sign = false;
30084 this.iaddn(num);
30085 this.sign = true;
30086 return this;
30087 }
30088
30089 this.words[0] -= num;
30090
30091 // Carry
30092 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
30093 this.words[i] += 0x4000000;
30094 this.words[i + 1] -= 1;
30095 }
30096
30097 return this.strip();
30098};
30099
30100BN.prototype.addn = function addn(num) {
30101 return this.clone().iaddn(num);
30102};
30103
30104BN.prototype.subn = function subn(num) {
30105 return this.clone().isubn(num);
30106};
30107
30108BN.prototype.iabs = function iabs() {
30109 this.sign = false;
30110
30111 return this;
30112};
30113
30114BN.prototype.abs = function abs() {
30115 return this.clone().iabs();
30116};
30117
30118BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
30119 // Bigger storage is needed
30120 var len = num.length + shift;
30121 var i;
30122 if (this.words.length < len) {
30123 var t = new Array(len);
30124 for (var i = 0; i < this.length; i++)
30125 t[i] = this.words[i];
30126 this.words = t;
30127 } else {
30128 i = this.length;
30129 }
30130
30131 // Zeroify rest
30132 this.length = Math.max(this.length, len);
30133 for (; i < this.length; i++)
30134 this.words[i] = 0;
30135
30136 var carry = 0;
30137 for (var i = 0; i < num.length; i++) {
30138 var w = this.words[i + shift] + carry;
30139 var right = num.words[i] * mul;
30140 w -= right & 0x3ffffff;
30141 carry = (w >> 26) - ((right / 0x4000000) | 0);
30142 this.words[i + shift] = w & 0x3ffffff;
30143 }
30144 for (; i < this.length - shift; i++) {
30145 var w = this.words[i + shift] + carry;
30146 carry = w >> 26;
30147 this.words[i + shift] = w & 0x3ffffff;
30148 }
30149
30150 if (carry === 0)
30151 return this.strip();
30152
30153 // Subtraction overflow
30154 assert(carry === -1);
30155 carry = 0;
30156 for (var i = 0; i < this.length; i++) {
30157 var w = -this.words[i] + carry;
30158 carry = w >> 26;
30159 this.words[i] = w & 0x3ffffff;
30160 }
30161 this.sign = true;
30162
30163 return this.strip();
30164};
30165
30166BN.prototype._wordDiv = function _wordDiv(num, mode) {
30167 var shift = this.length - num.length;
30168
30169 var a = this.clone();
30170 var b = num;
30171
30172 // Normalize
30173 var bhi = b.words[b.length - 1];
30174 var bhiBits = this._countBits(bhi);
30175 shift = 26 - bhiBits;
30176 if (shift !== 0) {
30177 b = b.shln(shift);
30178 a.ishln(shift);
30179 bhi = b.words[b.length - 1];
30180 }
30181
30182 // Initialize quotient
30183 var m = a.length - b.length;
30184 var q;
30185
30186 if (mode !== 'mod') {
30187 q = new BN(null);
30188 q.length = m + 1;
30189 q.words = new Array(q.length);
30190 for (var i = 0; i < q.length; i++)
30191 q.words[i] = 0;
30192 }
30193
30194 var diff = a.clone()._ishlnsubmul(b, 1, m);
30195 if (!diff.sign) {
30196 a = diff;
30197 if (q)
30198 q.words[m] = 1;
30199 }
30200
30201 for (var j = m - 1; j >= 0; j--) {
30202 var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
30203
30204 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
30205 // (0x7ffffff)
30206 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
30207
30208 a._ishlnsubmul(b, qj, j);
30209 while (a.sign) {
30210 qj--;
30211 a.sign = false;
30212 a._ishlnsubmul(b, 1, j);
30213 if (a.cmpn(0) !== 0)
30214 a.sign = !a.sign;
30215 }
30216 if (q)
30217 q.words[j] = qj;
30218 }
30219 if (q)
30220 q.strip();
30221 a.strip();
30222
30223 // Denormalize
30224 if (mode !== 'div' && shift !== 0)
30225 a.ishrn(shift);
30226 return { div: q ? q : null, mod: a };
30227};
30228
30229BN.prototype.divmod = function divmod(num, mode) {
30230 assert(num.cmpn(0) !== 0);
30231
30232 if (this.sign && !num.sign) {
30233 var res = this.neg().divmod(num, mode);
30234 var div;
30235 var mod;
30236 if (mode !== 'mod')
30237 div = res.div.neg();
30238 if (mode !== 'div')
30239 mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod);
30240 return {
30241 div: div,
30242 mod: mod
30243 };
30244 } else if (!this.sign && num.sign) {
30245 var res = this.divmod(num.neg(), mode);
30246 var div;
30247 if (mode !== 'mod')
30248 div = res.div.neg();
30249 return { div: div, mod: res.mod };
30250 } else if (this.sign && num.sign) {
30251 return this.neg().divmod(num.neg(), mode);
30252 }
30253
30254 // Both numbers are positive at this point
30255
30256 // Strip both numbers to approximate shift value
30257 if (num.length > this.length || this.cmp(num) < 0)
30258 return { div: new BN(0), mod: this };
30259
30260 // Very short reduction
30261 if (num.length === 1) {
30262 if (mode === 'div')
30263 return { div: this.divn(num.words[0]), mod: null };
30264 else if (mode === 'mod')
30265 return { div: null, mod: new BN(this.modn(num.words[0])) };
30266 return {
30267 div: this.divn(num.words[0]),
30268 mod: new BN(this.modn(num.words[0]))
30269 };
30270 }
30271
30272 return this._wordDiv(num, mode);
30273};
30274
30275// Find `this` / `num`
30276BN.prototype.div = function div(num) {
30277 return this.divmod(num, 'div').div;
30278};
30279
30280// Find `this` % `num`
30281BN.prototype.mod = function mod(num) {
30282 return this.divmod(num, 'mod').mod;
30283};
30284
30285// Find Round(`this` / `num`)
30286BN.prototype.divRound = function divRound(num) {
30287 var dm = this.divmod(num);
30288
30289 // Fast case - exact division
30290 if (dm.mod.cmpn(0) === 0)
30291 return dm.div;
30292
30293 var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
30294
30295 var half = num.shrn(1);
30296 var r2 = num.andln(1);
30297 var cmp = mod.cmp(half);
30298
30299 // Round down
30300 if (cmp < 0 || r2 === 1 && cmp === 0)
30301 return dm.div;
30302
30303 // Round up
30304 return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
30305};
30306
30307BN.prototype.modn = function modn(num) {
30308 assert(num <= 0x3ffffff);
30309 var p = (1 << 26) % num;
30310
30311 var acc = 0;
30312 for (var i = this.length - 1; i >= 0; i--)
30313 acc = (p * acc + this.words[i]) % num;
30314
30315 return acc;
30316};
30317
30318// In-place division by number
30319BN.prototype.idivn = function idivn(num) {
30320 assert(num <= 0x3ffffff);
30321
30322 var carry = 0;
30323 for (var i = this.length - 1; i >= 0; i--) {
30324 var w = this.words[i] + carry * 0x4000000;
30325 this.words[i] = (w / num) | 0;
30326 carry = w % num;
30327 }
30328
30329 return this.strip();
30330};
30331
30332BN.prototype.divn = function divn(num) {
30333 return this.clone().idivn(num);
30334};
30335
30336BN.prototype.egcd = function egcd(p) {
30337 assert(!p.sign);
30338 assert(p.cmpn(0) !== 0);
30339
30340 var x = this;
30341 var y = p.clone();
30342
30343 if (x.sign)
30344 x = x.mod(p);
30345 else
30346 x = x.clone();
30347
30348 // A * x + B * y = x
30349 var A = new BN(1);
30350 var B = new BN(0);
30351
30352 // C * x + D * y = y
30353 var C = new BN(0);
30354 var D = new BN(1);
30355
30356 var g = 0;
30357
30358 while (x.isEven() && y.isEven()) {
30359 x.ishrn(1);
30360 y.ishrn(1);
30361 ++g;
30362 }
30363
30364 var yp = y.clone();
30365 var xp = x.clone();
30366
30367 while (x.cmpn(0) !== 0) {
30368 while (x.isEven()) {
30369 x.ishrn(1);
30370 if (A.isEven() && B.isEven()) {
30371 A.ishrn(1);
30372 B.ishrn(1);
30373 } else {
30374 A.iadd(yp).ishrn(1);
30375 B.isub(xp).ishrn(1);
30376 }
30377 }
30378
30379 while (y.isEven()) {
30380 y.ishrn(1);
30381 if (C.isEven() && D.isEven()) {
30382 C.ishrn(1);
30383 D.ishrn(1);
30384 } else {
30385 C.iadd(yp).ishrn(1);
30386 D.isub(xp).ishrn(1);
30387 }
30388 }
30389
30390 if (x.cmp(y) >= 0) {
30391 x.isub(y);
30392 A.isub(C);
30393 B.isub(D);
30394 } else {
30395 y.isub(x);
30396 C.isub(A);
30397 D.isub(B);
30398 }
30399 }
30400
30401 return {
30402 a: C,
30403 b: D,
30404 gcd: y.ishln(g)
30405 };
30406};
30407
30408// This is reduced incarnation of the binary EEA
30409// above, designated to invert members of the
30410// _prime_ fields F(p) at a maximal speed
30411BN.prototype._invmp = function _invmp(p) {
30412 assert(!p.sign);
30413 assert(p.cmpn(0) !== 0);
30414
30415 var a = this;
30416 var b = p.clone();
30417
30418 if (a.sign)
30419 a = a.mod(p);
30420 else
30421 a = a.clone();
30422
30423 var x1 = new BN(1);
30424 var x2 = new BN(0);
30425
30426 var delta = b.clone();
30427
30428 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
30429 while (a.isEven()) {
30430 a.ishrn(1);
30431 if (x1.isEven())
30432 x1.ishrn(1);
30433 else
30434 x1.iadd(delta).ishrn(1);
30435 }
30436 while (b.isEven()) {
30437 b.ishrn(1);
30438 if (x2.isEven())
30439 x2.ishrn(1);
30440 else
30441 x2.iadd(delta).ishrn(1);
30442 }
30443 if (a.cmp(b) >= 0) {
30444 a.isub(b);
30445 x1.isub(x2);
30446 } else {
30447 b.isub(a);
30448 x2.isub(x1);
30449 }
30450 }
30451 if (a.cmpn(1) === 0)
30452 return x1;
30453 else
30454 return x2;
30455};
30456
30457BN.prototype.gcd = function gcd(num) {
30458 if (this.cmpn(0) === 0)
30459 return num.clone();
30460 if (num.cmpn(0) === 0)
30461 return this.clone();
30462
30463 var a = this.clone();
30464 var b = num.clone();
30465 a.sign = false;
30466 b.sign = false;
30467
30468 // Remove common factor of two
30469 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
30470 a.ishrn(1);
30471 b.ishrn(1);
30472 }
30473
30474 do {
30475 while (a.isEven())
30476 a.ishrn(1);
30477 while (b.isEven())
30478 b.ishrn(1);
30479
30480 var r = a.cmp(b);
30481 if (r < 0) {
30482 // Swap `a` and `b` to make `a` always bigger than `b`
30483 var t = a;
30484 a = b;
30485 b = t;
30486 } else if (r === 0 || b.cmpn(1) === 0) {
30487 break;
30488 }
30489
30490 a.isub(b);
30491 } while (true);
30492
30493 return b.ishln(shift);
30494};
30495
30496// Invert number in the field F(num)
30497BN.prototype.invm = function invm(num) {
30498 return this.egcd(num).a.mod(num);
30499};
30500
30501BN.prototype.isEven = function isEven() {
30502 return (this.words[0] & 1) === 0;
30503};
30504
30505BN.prototype.isOdd = function isOdd() {
30506 return (this.words[0] & 1) === 1;
30507};
30508
30509// And first word and num
30510BN.prototype.andln = function andln(num) {
30511 return this.words[0] & num;
30512};
30513
30514// Increment at the bit position in-line
30515BN.prototype.bincn = function bincn(bit) {
30516 assert(typeof bit === 'number');
30517 var r = bit % 26;
30518 var s = (bit - r) / 26;
30519 var q = 1 << r;
30520
30521 // Fast case: bit is much higher than all existing words
30522 if (this.length <= s) {
30523 for (var i = this.length; i < s + 1; i++)
30524 this.words[i] = 0;
30525 this.words[s] |= q;
30526 this.length = s + 1;
30527 return this;
30528 }
30529
30530 // Add bit and propagate, if needed
30531 var carry = q;
30532 for (var i = s; carry !== 0 && i < this.length; i++) {
30533 var w = this.words[i];
30534 w += carry;
30535 carry = w >>> 26;
30536 w &= 0x3ffffff;
30537 this.words[i] = w;
30538 }
30539 if (carry !== 0) {
30540 this.words[i] = carry;
30541 this.length++;
30542 }
30543 return this;
30544};
30545
30546BN.prototype.cmpn = function cmpn(num) {
30547 var sign = num < 0;
30548 if (sign)
30549 num = -num;
30550
30551 if (this.sign && !sign)
30552 return -1;
30553 else if (!this.sign && sign)
30554 return 1;
30555
30556 num &= 0x3ffffff;
30557 this.strip();
30558
30559 var res;
30560 if (this.length > 1) {
30561 res = 1;
30562 } else {
30563 var w = this.words[0];
30564 res = w === num ? 0 : w < num ? -1 : 1;
30565 }
30566 if (this.sign)
30567 res = -res;
30568 return res;
30569};
30570
30571// Compare two numbers and return:
30572// 1 - if `this` > `num`
30573// 0 - if `this` == `num`
30574// -1 - if `this` < `num`
30575BN.prototype.cmp = function cmp(num) {
30576 if (this.sign && !num.sign)
30577 return -1;
30578 else if (!this.sign && num.sign)
30579 return 1;
30580
30581 var res = this.ucmp(num);
30582 if (this.sign)
30583 return -res;
30584 else
30585 return res;
30586};
30587
30588// Unsigned comparison
30589BN.prototype.ucmp = function ucmp(num) {
30590 // At this point both numbers have the same sign
30591 if (this.length > num.length)
30592 return 1;
30593 else if (this.length < num.length)
30594 return -1;
30595
30596 var res = 0;
30597 for (var i = this.length - 1; i >= 0; i--) {
30598 var a = this.words[i];
30599 var b = num.words[i];
30600
30601 if (a === b)
30602 continue;
30603 if (a < b)
30604 res = -1;
30605 else if (a > b)
30606 res = 1;
30607 break;
30608 }
30609 return res;
30610};
30611
30612//
30613// A reduce context, could be using montgomery or something better, depending
30614// on the `m` itself.
30615//
30616BN.red = function red(num) {
30617 return new Red(num);
30618};
30619
30620BN.prototype.toRed = function toRed(ctx) {
30621 assert(!this.red, 'Already a number in reduction context');
30622 assert(!this.sign, 'red works only with positives');
30623 return ctx.convertTo(this)._forceRed(ctx);
30624};
30625
30626BN.prototype.fromRed = function fromRed() {
30627 assert(this.red, 'fromRed works only with numbers in reduction context');
30628 return this.red.convertFrom(this);
30629};
30630
30631BN.prototype._forceRed = function _forceRed(ctx) {
30632 this.red = ctx;
30633 return this;
30634};
30635
30636BN.prototype.forceRed = function forceRed(ctx) {
30637 assert(!this.red, 'Already a number in reduction context');
30638 return this._forceRed(ctx);
30639};
30640
30641BN.prototype.redAdd = function redAdd(num) {
30642 assert(this.red, 'redAdd works only with red numbers');
30643 return this.red.add(this, num);
30644};
30645
30646BN.prototype.redIAdd = function redIAdd(num) {
30647 assert(this.red, 'redIAdd works only with red numbers');
30648 return this.red.iadd(this, num);
30649};
30650
30651BN.prototype.redSub = function redSub(num) {
30652 assert(this.red, 'redSub works only with red numbers');
30653 return this.red.sub(this, num);
30654};
30655
30656BN.prototype.redISub = function redISub(num) {
30657 assert(this.red, 'redISub works only with red numbers');
30658 return this.red.isub(this, num);
30659};
30660
30661BN.prototype.redShl = function redShl(num) {
30662 assert(this.red, 'redShl works only with red numbers');
30663 return this.red.shl(this, num);
30664};
30665
30666BN.prototype.redMul = function redMul(num) {
30667 assert(this.red, 'redMul works only with red numbers');
30668 this.red._verify2(this, num);
30669 return this.red.mul(this, num);
30670};
30671
30672BN.prototype.redIMul = function redIMul(num) {
30673 assert(this.red, 'redMul works only with red numbers');
30674 this.red._verify2(this, num);
30675 return this.red.imul(this, num);
30676};
30677
30678BN.prototype.redSqr = function redSqr() {
30679 assert(this.red, 'redSqr works only with red numbers');
30680 this.red._verify1(this);
30681 return this.red.sqr(this);
30682};
30683
30684BN.prototype.redISqr = function redISqr() {
30685 assert(this.red, 'redISqr works only with red numbers');
30686 this.red._verify1(this);
30687 return this.red.isqr(this);
30688};
30689
30690// Square root over p
30691BN.prototype.redSqrt = function redSqrt() {
30692 assert(this.red, 'redSqrt works only with red numbers');
30693 this.red._verify1(this);
30694 return this.red.sqrt(this);
30695};
30696
30697BN.prototype.redInvm = function redInvm() {
30698 assert(this.red, 'redInvm works only with red numbers');
30699 this.red._verify1(this);
30700 return this.red.invm(this);
30701};
30702
30703// Return negative clone of `this` % `red modulo`
30704BN.prototype.redNeg = function redNeg() {
30705 assert(this.red, 'redNeg works only with red numbers');
30706 this.red._verify1(this);
30707 return this.red.neg(this);
30708};
30709
30710BN.prototype.redPow = function redPow(num) {
30711 assert(this.red && !num.red, 'redPow(normalNum)');
30712 this.red._verify1(this);
30713 return this.red.pow(this, num);
30714};
30715
30716// Prime numbers with efficient reduction
30717var primes = {
30718 k256: null,
30719 p224: null,
30720 p192: null,
30721 p25519: null
30722};
30723
30724// Pseudo-Mersenne prime
30725function MPrime(name, p) {
30726 // P = 2 ^ N - K
30727 this.name = name;
30728 this.p = new BN(p, 16);
30729 this.n = this.p.bitLength();
30730 this.k = new BN(1).ishln(this.n).isub(this.p);
30731
30732 this.tmp = this._tmp();
30733}
30734
30735MPrime.prototype._tmp = function _tmp() {
30736 var tmp = new BN(null);
30737 tmp.words = new Array(Math.ceil(this.n / 13));
30738 return tmp;
30739};
30740
30741MPrime.prototype.ireduce = function ireduce(num) {
30742 // Assumes that `num` is less than `P^2`
30743 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
30744 var r = num;
30745 var rlen;
30746
30747 do {
30748 this.split(r, this.tmp);
30749 r = this.imulK(r);
30750 r = r.iadd(this.tmp);
30751 rlen = r.bitLength();
30752 } while (rlen > this.n);
30753
30754 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
30755 if (cmp === 0) {
30756 r.words[0] = 0;
30757 r.length = 1;
30758 } else if (cmp > 0) {
30759 r.isub(this.p);
30760 } else {
30761 r.strip();
30762 }
30763
30764 return r;
30765};
30766
30767MPrime.prototype.split = function split(input, out) {
30768 input.ishrn(this.n, 0, out);
30769};
30770
30771MPrime.prototype.imulK = function imulK(num) {
30772 return num.imul(this.k);
30773};
30774
30775function K256() {
30776 MPrime.call(
30777 this,
30778 'k256',
30779 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
30780}
30781inherits(K256, MPrime);
30782
30783K256.prototype.split = function split(input, output) {
30784 // 256 = 9 * 26 + 22
30785 var mask = 0x3fffff;
30786
30787 var outLen = Math.min(input.length, 9);
30788 for (var i = 0; i < outLen; i++)
30789 output.words[i] = input.words[i];
30790 output.length = outLen;
30791
30792 if (input.length <= 9) {
30793 input.words[0] = 0;
30794 input.length = 1;
30795 return;
30796 }
30797
30798 // Shift by 9 limbs
30799 var prev = input.words[9];
30800 output.words[output.length++] = prev & mask;
30801
30802 for (var i = 10; i < input.length; i++) {
30803 var next = input.words[i];
30804 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
30805 prev = next;
30806 }
30807 input.words[i - 10] = prev >>> 22;
30808 input.length -= 9;
30809};
30810
30811K256.prototype.imulK = function imulK(num) {
30812 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
30813 num.words[num.length] = 0;
30814 num.words[num.length + 1] = 0;
30815 num.length += 2;
30816
30817 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
30818 var hi;
30819 var lo = 0;
30820 for (var i = 0; i < num.length; i++) {
30821 var w = num.words[i];
30822 hi = w * 0x40;
30823 lo += w * 0x3d1;
30824 hi += (lo / 0x4000000) | 0;
30825 lo &= 0x3ffffff;
30826
30827 num.words[i] = lo;
30828
30829 lo = hi;
30830 }
30831
30832 // Fast length reduction
30833 if (num.words[num.length - 1] === 0) {
30834 num.length--;
30835 if (num.words[num.length - 1] === 0)
30836 num.length--;
30837 }
30838 return num;
30839};
30840
30841function P224() {
30842 MPrime.call(
30843 this,
30844 'p224',
30845 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
30846}
30847inherits(P224, MPrime);
30848
30849function P192() {
30850 MPrime.call(
30851 this,
30852 'p192',
30853 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
30854}
30855inherits(P192, MPrime);
30856
30857function P25519() {
30858 // 2 ^ 255 - 19
30859 MPrime.call(
30860 this,
30861 '25519',
30862 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
30863}
30864inherits(P25519, MPrime);
30865
30866P25519.prototype.imulK = function imulK(num) {
30867 // K = 0x13
30868 var carry = 0;
30869 for (var i = 0; i < num.length; i++) {
30870 var hi = num.words[i] * 0x13 + carry;
30871 var lo = hi & 0x3ffffff;
30872 hi >>>= 26;
30873
30874 num.words[i] = lo;
30875 carry = hi;
30876 }
30877 if (carry !== 0)
30878 num.words[num.length++] = carry;
30879 return num;
30880};
30881
30882// Exported mostly for testing purposes, use plain name instead
30883BN._prime = function prime(name) {
30884 // Cached version of prime
30885 if (primes[name])
30886 return primes[name];
30887
30888 var prime;
30889 if (name === 'k256')
30890 prime = new K256();
30891 else if (name === 'p224')
30892 prime = new P224();
30893 else if (name === 'p192')
30894 prime = new P192();
30895 else if (name === 'p25519')
30896 prime = new P25519();
30897 else
30898 throw new Error('Unknown prime ' + name);
30899 primes[name] = prime;
30900
30901 return prime;
30902};
30903
30904//
30905// Base reduction engine
30906//
30907function Red(m) {
30908 if (typeof m === 'string') {
30909 var prime = BN._prime(m);
30910 this.m = prime.p;
30911 this.prime = prime;
30912 } else {
30913 this.m = m;
30914 this.prime = null;
30915 }
30916}
30917
30918Red.prototype._verify1 = function _verify1(a) {
30919 assert(!a.sign, 'red works only with positives');
30920 assert(a.red, 'red works only with red numbers');
30921};
30922
30923Red.prototype._verify2 = function _verify2(a, b) {
30924 assert(!a.sign && !b.sign, 'red works only with positives');
30925 assert(a.red && a.red === b.red,
30926 'red works only with red numbers');
30927};
30928
30929Red.prototype.imod = function imod(a) {
30930 if (this.prime)
30931 return this.prime.ireduce(a)._forceRed(this);
30932 return a.mod(this.m)._forceRed(this);
30933};
30934
30935Red.prototype.neg = function neg(a) {
30936 var r = a.clone();
30937 r.sign = !r.sign;
30938 return r.iadd(this.m)._forceRed(this);
30939};
30940
30941Red.prototype.add = function add(a, b) {
30942 this._verify2(a, b);
30943
30944 var res = a.add(b);
30945 if (res.cmp(this.m) >= 0)
30946 res.isub(this.m);
30947 return res._forceRed(this);
30948};
30949
30950Red.prototype.iadd = function iadd(a, b) {
30951 this._verify2(a, b);
30952
30953 var res = a.iadd(b);
30954 if (res.cmp(this.m) >= 0)
30955 res.isub(this.m);
30956 return res;
30957};
30958
30959Red.prototype.sub = function sub(a, b) {
30960 this._verify2(a, b);
30961
30962 var res = a.sub(b);
30963 if (res.cmpn(0) < 0)
30964 res.iadd(this.m);
30965 return res._forceRed(this);
30966};
30967
30968Red.prototype.isub = function isub(a, b) {
30969 this._verify2(a, b);
30970
30971 var res = a.isub(b);
30972 if (res.cmpn(0) < 0)
30973 res.iadd(this.m);
30974 return res;
30975};
30976
30977Red.prototype.shl = function shl(a, num) {
30978 this._verify1(a);
30979 return this.imod(a.shln(num));
30980};
30981
30982Red.prototype.imul = function imul(a, b) {
30983 this._verify2(a, b);
30984 return this.imod(a.imul(b));
30985};
30986
30987Red.prototype.mul = function mul(a, b) {
30988 this._verify2(a, b);
30989 return this.imod(a.mul(b));
30990};
30991
30992Red.prototype.isqr = function isqr(a) {
30993 return this.imul(a, a);
30994};
30995
30996Red.prototype.sqr = function sqr(a) {
30997 return this.mul(a, a);
30998};
30999
31000Red.prototype.sqrt = function sqrt(a) {
31001 if (a.cmpn(0) === 0)
31002 return a.clone();
31003
31004 var mod3 = this.m.andln(3);
31005 assert(mod3 % 2 === 1);
31006
31007 // Fast case
31008 if (mod3 === 3) {
31009 var pow = this.m.add(new BN(1)).ishrn(2);
31010 var r = this.pow(a, pow);
31011 return r;
31012 }
31013
31014 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
31015 //
31016 // Find Q and S, that Q * 2 ^ S = (P - 1)
31017 var q = this.m.subn(1);
31018 var s = 0;
31019 while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
31020 s++;
31021 q.ishrn(1);
31022 }
31023 assert(q.cmpn(0) !== 0);
31024
31025 var one = new BN(1).toRed(this);
31026 var nOne = one.redNeg();
31027
31028 // Find quadratic non-residue
31029 // NOTE: Max is such because of generalized Riemann hypothesis.
31030 var lpow = this.m.subn(1).ishrn(1);
31031 var z = this.m.bitLength();
31032 z = new BN(2 * z * z).toRed(this);
31033 while (this.pow(z, lpow).cmp(nOne) !== 0)
31034 z.redIAdd(nOne);
31035
31036 var c = this.pow(z, q);
31037 var r = this.pow(a, q.addn(1).ishrn(1));
31038 var t = this.pow(a, q);
31039 var m = s;
31040 while (t.cmp(one) !== 0) {
31041 var tmp = t;
31042 for (var i = 0; tmp.cmp(one) !== 0; i++)
31043 tmp = tmp.redSqr();
31044 assert(i < m);
31045 var b = this.pow(c, new BN(1).ishln(m - i - 1));
31046
31047 r = r.redMul(b);
31048 c = b.redSqr();
31049 t = t.redMul(c);
31050 m = i;
31051 }
31052
31053 return r;
31054};
31055
31056Red.prototype.invm = function invm(a) {
31057 var inv = a._invmp(this.m);
31058 if (inv.sign) {
31059 inv.sign = false;
31060 return this.imod(inv).redNeg();
31061 } else {
31062 return this.imod(inv);
31063 }
31064};
31065
31066Red.prototype.pow = function pow(a, num) {
31067 var w = [];
31068
31069 if (num.cmpn(0) === 0)
31070 return new BN(1);
31071
31072 var q = num.clone();
31073
31074 while (q.cmpn(0) !== 0) {
31075 w.push(q.andln(1));
31076 q.ishrn(1);
31077 }
31078
31079 // Skip leading zeroes
31080 var res = a;
31081 for (var i = 0; i < w.length; i++, res = this.sqr(res))
31082 if (w[i] !== 0)
31083 break;
31084
31085 if (++i < w.length) {
31086 for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
31087 if (w[i] === 0)
31088 continue;
31089 res = this.mul(res, q);
31090 }
31091 }
31092
31093 return res;
31094};
31095
31096Red.prototype.convertTo = function convertTo(num) {
31097 var r = num.mod(this.m);
31098 if (r === num)
31099 return r.clone();
31100 else
31101 return r;
31102};
31103
31104Red.prototype.convertFrom = function convertFrom(num) {
31105 var res = num.clone();
31106 res.red = null;
31107 return res;
31108};
31109
31110//
31111// Montgomery method engine
31112//
31113
31114BN.mont = function mont(num) {
31115 return new Mont(num);
31116};
31117
31118function Mont(m) {
31119 Red.call(this, m);
31120
31121 this.shift = this.m.bitLength();
31122 if (this.shift % 26 !== 0)
31123 this.shift += 26 - (this.shift % 26);
31124 this.r = new BN(1).ishln(this.shift);
31125 this.r2 = this.imod(this.r.sqr());
31126 this.rinv = this.r._invmp(this.m);
31127
31128 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
31129 this.minv.sign = true;
31130 this.minv = this.minv.mod(this.r);
31131}
31132inherits(Mont, Red);
31133
31134Mont.prototype.convertTo = function convertTo(num) {
31135 return this.imod(num.shln(this.shift));
31136};
31137
31138Mont.prototype.convertFrom = function convertFrom(num) {
31139 var r = this.imod(num.mul(this.rinv));
31140 r.red = null;
31141 return r;
31142};
31143
31144Mont.prototype.imul = function imul(a, b) {
31145 if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
31146 a.words[0] = 0;
31147 a.length = 1;
31148 return a;
31149 }
31150
31151 var t = a.imul(b);
31152 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
31153 var u = t.isub(c).ishrn(this.shift);
31154 var res = u;
31155 if (u.cmp(this.m) >= 0)
31156 res = u.isub(this.m);
31157 else if (u.cmpn(0) < 0)
31158 res = u.iadd(this.m);
31159
31160 return res._forceRed(this);
31161};
31162
31163Mont.prototype.mul = function mul(a, b) {
31164 if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
31165 return new BN(0)._forceRed(this);
31166
31167 var t = a.mul(b);
31168 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
31169 var u = t.isub(c).ishrn(this.shift);
31170 var res = u;
31171 if (u.cmp(this.m) >= 0)
31172 res = u.isub(this.m);
31173 else if (u.cmpn(0) < 0)
31174 res = u.iadd(this.m);
31175
31176 return res._forceRed(this);
31177};
31178
31179Mont.prototype.invm = function invm(a) {
31180 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
31181 var res = this.imod(a._invmp(this.m).mul(this.r2));
31182 return res._forceRed(this);
31183};
31184
31185})(typeof module === 'undefined' || module, this);
31186}, {}],197: [function (exports, require, module, global) {var bn = require('bn.js');
31187var brorand = require('brorand');
31188
31189function MillerRabin(rand) {
31190 this.rand = rand || new brorand.Rand();
31191}
31192module.exports = MillerRabin;
31193
31194MillerRabin.create = function create(rand) {
31195 return new MillerRabin(rand);
31196};
31197
31198MillerRabin.prototype._rand = function _rand(n) {
31199 var len = n.bitLength();
31200 var buf = this.rand.generate(Math.ceil(len / 8));
31201
31202 // Set low bits
31203 buf[0] |= 3;
31204
31205 // Mask high bits
31206 var mask = len & 0x7;
31207 if (mask !== 0)
31208 buf[buf.length - 1] >>= 7 - mask;
31209
31210 return new bn(buf);
31211}
31212
31213MillerRabin.prototype.test = function test(n, k, cb) {
31214 var len = n.bitLength();
31215 var red = bn.mont(n);
31216 var rone = new bn(1).toRed(red);
31217
31218 if (!k)
31219 k = Math.max(1, (len / 48) | 0);
31220
31221 // Find d and s, (n - 1) = (2 ^ s) * d;
31222 var n1 = n.subn(1);
31223 var n2 = n1.subn(1);
31224 for (var s = 0; !n1.testn(s); s++) {}
31225 var d = n.shrn(s);
31226
31227 var rn1 = n1.toRed(red);
31228
31229 var prime = true;
31230 for (; k > 0; k--) {
31231 var a = this._rand(n2);
31232 if (cb)
31233 cb(a);
31234
31235 var x = a.toRed(red).redPow(d);
31236 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
31237 continue;
31238
31239 for (var i = 1; i < s; i++) {
31240 x = x.redSqr();
31241
31242 if (x.cmp(rone) === 0)
31243 return false;
31244 if (x.cmp(rn1) === 0)
31245 break;
31246 }
31247
31248 if (i === s)
31249 return false;
31250 }
31251
31252 return prime;
31253};
31254
31255MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
31256 var len = n.bitLength();
31257 var red = bn.mont(n);
31258 var rone = new bn(1).toRed(red);
31259
31260 if (!k)
31261 k = Math.max(1, (len / 48) | 0);
31262
31263 // Find d and s, (n - 1) = (2 ^ s) * d;
31264 var n1 = n.subn(1);
31265 var n2 = n1.subn(1);
31266 for (var s = 0; !n1.testn(s); s++) {}
31267 var d = n.shrn(s);
31268
31269 var rn1 = n1.toRed(red);
31270
31271 for (; k > 0; k--) {
31272 var a = this._rand(n2);
31273
31274 var g = n.gcd(a);
31275 if (g.cmpn(1) !== 0)
31276 return g;
31277
31278 var x = a.toRed(red).redPow(d);
31279 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
31280 continue;
31281
31282 for (var i = 1; i < s; i++) {
31283 x = x.redSqr();
31284
31285 if (x.cmp(rone) === 0)
31286 return x.fromRed().subn(1).gcd(n);
31287 if (x.cmp(rn1) === 0)
31288 break;
31289 }
31290
31291 if (i === s) {
31292 x = x.redSqr();
31293 return x.fromRed().subn(1).gcd(n);
31294 }
31295 }
31296
31297 return false;
31298};
31299}, {"bn.js":196,"brorand":198}],198: [function (exports, require, module, global) {var r;
31300
31301module.exports = function rand(len) {
31302 if (!r)
31303 r = new Rand(null);
31304
31305 return r.generate(len);
31306};
31307
31308function Rand(rand) {
31309 this.rand = rand;
31310}
31311module.exports.Rand = Rand;
31312
31313Rand.prototype.generate = function generate(len) {
31314 return this._rand(len);
31315};
31316
31317if (typeof window === 'object') {
31318 if (window.crypto && window.crypto.getRandomValues) {
31319 // Modern browsers
31320 Rand.prototype._rand = function _rand(n) {
31321 var arr = new Uint8Array(n);
31322 window.crypto.getRandomValues(arr);
31323 return arr;
31324 };
31325 } else if (window.msCrypto && window.msCrypto.getRandomValues) {
31326 // IE
31327 Rand.prototype._rand = function _rand(n) {
31328 var arr = new Uint8Array(n);
31329 window.msCrypto.getRandomValues(arr);
31330 return arr;
31331 };
31332 } else {
31333 // Old junk
31334 Rand.prototype._rand = function() {
31335 throw new Error('Not implemented yet');
31336 };
31337 }
31338} else {
31339 // Node.js or Web worker
31340 try {
31341 var crypto = require('cry' + 'pto');
31342
31343 Rand.prototype._rand = function _rand(n) {
31344 return crypto.randomBytes(n);
31345 };
31346 } catch (e) {
31347 // Emulate crypto API using randy
31348 Rand.prototype._rand = function _rand(n) {
31349 var res = new Uint8Array(n);
31350 for (var i = 0; i < res.length; i++)
31351 res[i] = this.rand.getByte();
31352 return res;
31353 };
31354 }
31355}
31356}, {}],199: [function (exports, require, module, global) {module.exports = {
31357 "modp1": {
31358 "gen": "02",
31359 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
31360 },
31361 "modp2": {
31362 "gen": "02",
31363 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
31364 },
31365 "modp5": {
31366 "gen": "02",
31367 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
31368 },
31369 "modp14": {
31370 "gen": "02",
31371 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
31372 },
31373 "modp15": {
31374 "gen": "02",
31375 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
31376 },
31377 "modp16": {
31378 "gen": "02",
31379 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
31380 },
31381 "modp17": {
31382 "gen": "02",
31383 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
31384 },
31385 "modp18": {
31386 "gen": "02",
31387 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
31388 }
31389}}, {}],200: [function (exports, require, module, global) {var BN = require('bn.js');
31390var MillerRabin = require('miller-rabin');
31391var millerRabin = new MillerRabin();
31392var TWENTYFOUR = new BN(24);
31393var ELEVEN = new BN(11);
31394var TEN = new BN(10);
31395var THREE = new BN(3);
31396var SEVEN = new BN(7);
31397var primes = require('./generatePrime');
31398var randomBytes = require('randombytes');
31399module.exports = DH;
31400
31401function setPublicKey(pub, enc) {
31402 enc = enc || 'utf8';
31403 if (!Buffer.isBuffer(pub)) {
31404 pub = new Buffer(pub, enc);
31405 }
31406 this._pub = new BN(pub);
31407 return this;
31408}
31409
31410function setPrivateKey(priv, enc) {
31411 enc = enc || 'utf8';
31412 if (!Buffer.isBuffer(priv)) {
31413 priv = new Buffer(priv, enc);
31414 }
31415 this._priv = new BN(priv);
31416 return this;
31417}
31418
31419var primeCache = {};
31420function checkPrime(prime, generator) {
31421 var gen = generator.toString('hex');
31422 var hex = [gen, prime.toString(16)].join('_');
31423 if (hex in primeCache) {
31424 return primeCache[hex];
31425 }
31426 var error = 0;
31427
31428 if (prime.isEven() ||
31429 !primes.simpleSieve ||
31430 !primes.fermatTest(prime) ||
31431 !millerRabin.test(prime)) {
31432 //not a prime so +1
31433 error += 1;
31434
31435 if (gen === '02' || gen === '05') {
31436 // we'd be able to check the generator
31437 // it would fail so +8
31438 error += 8;
31439 } else {
31440 //we wouldn't be able to test the generator
31441 // so +4
31442 error += 4;
31443 }
31444 primeCache[hex] = error;
31445 return error;
31446 }
31447 if (!millerRabin.test(prime.shrn(1))) {
31448 //not a safe prime
31449 error += 2;
31450 }
31451 var rem;
31452 switch (gen) {
31453 case '02':
31454 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
31455 // unsuidable generator
31456 error += 8;
31457 }
31458 break;
31459 case '05':
31460 rem = prime.mod(TEN);
31461 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
31462 // prime mod 10 needs to equal 3 or 7
31463 error += 8;
31464 }
31465 break;
31466 default:
31467 error += 4;
31468 }
31469 primeCache[hex] = error;
31470 return error;
31471}
31472
31473function defineError (self, error) {
31474 try {
31475 Object.defineProperty(self, 'verifyError', {
31476 enumerable: true,
31477 value: error,
31478 writable: false
31479 });
31480 } catch(e) {
31481 self.verifyError = error;
31482 }
31483}
31484function DH(prime, generator, malleable) {
31485 this.setGenerator(generator);
31486 this.__prime = new BN(prime);
31487 this._prime = BN.mont(this.__prime);
31488 this._primeLen = prime.length;
31489 this._pub = void 0;
31490 this._priv = void 0;
31491
31492 if (malleable) {
31493 this.setPublicKey = setPublicKey;
31494 this.setPrivateKey = setPrivateKey;
31495 defineError(this, checkPrime(this.__prime, generator));
31496 } else {
31497 defineError(this, 8);
31498 }
31499}
31500
31501DH.prototype.generateKeys = function () {
31502 if (!this._priv) {
31503 this._priv = new BN(randomBytes(this._primeLen));
31504 }
31505 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
31506 return this.getPublicKey();
31507};
31508
31509DH.prototype.computeSecret = function (other) {
31510 other = new BN(other);
31511 other = other.toRed(this._prime);
31512 var secret = other.redPow(this._priv).fromRed();
31513 var out = new Buffer(secret.toArray());
31514 var prime = this.getPrime();
31515 if (out.length < prime.length) {
31516 var front = new Buffer(prime.length - out.length);
31517 front.fill(0);
31518 out = Buffer.concat([front, out]);
31519 }
31520 return out;
31521};
31522
31523DH.prototype.getPublicKey = function getPublicKey(enc) {
31524 return formatReturnValue(this._pub, enc);
31525};
31526
31527DH.prototype.getPrivateKey = function getPrivateKey(enc) {
31528 return formatReturnValue(this._priv, enc);
31529};
31530
31531DH.prototype.getPrime = function (enc) {
31532 return formatReturnValue(this.__prime, enc);
31533};
31534
31535DH.prototype.getGenerator = function (enc) {
31536 return formatReturnValue(this._gen, enc);
31537};
31538
31539DH.prototype.setGenerator = function (gen, enc) {
31540 enc = enc || 'utf8';
31541 if (!Buffer.isBuffer(gen)) {
31542 gen = new Buffer(gen, enc);
31543 }
31544 this._gen = new BN(gen);
31545 return this;
31546};
31547
31548function formatReturnValue(bn, enc) {
31549 var buf = new Buffer(bn.toArray());
31550 if (!enc) {
31551 return buf;
31552 } else {
31553 return buf.toString(enc);
31554 }
31555}}, {"bn.js":196,"miller-rabin":197,"./generatePrime":195,"randombytes":147}],201: [function (exports, require, module, global) {var _algos = require('./algos')
31556var createHash = require('create-hash')
31557var inherits = require('inherits')
31558var sign = require('./sign')
31559var stream = require('stream')
31560var verify = require('./verify')
31561
31562var algos = {}
31563Object.keys(_algos).forEach(function (key) {
31564 algos[key] = algos[key.toLowerCase()] = _algos[key]
31565})
31566
31567function Sign (algorithm) {
31568 stream.Writable.call(this)
31569
31570 var data = algos[algorithm]
31571 if (!data) {
31572 throw new Error('Unknown message digest')
31573 }
31574
31575 this._hashType = data.hash
31576 this._hash = createHash(data.hash)
31577 this._tag = data.id
31578 this._signType = data.sign
31579}
31580inherits(Sign, stream.Writable)
31581
31582Sign.prototype._write = function _write (data, _, done) {
31583 this._hash.update(data)
31584 done()
31585}
31586
31587Sign.prototype.update = function update (data, enc) {
31588 if (typeof data === 'string') {
31589 data = new Buffer(data, enc)
31590 }
31591
31592 this._hash.update(data)
31593 return this
31594}
31595
31596Sign.prototype.sign = function signMethod (key, enc) {
31597 this.end()
31598 var hash = this._hash.digest()
31599 var sig = sign(Buffer.concat([this._tag, hash]), key, this._hashType, this._signType)
31600
31601 return enc ? sig.toString(enc) : sig
31602}
31603
31604function Verify (algorithm) {
31605 stream.Writable.call(this)
31606
31607 var data = algos[algorithm]
31608 if (!data) {
31609 throw new Error('Unknown message digest')
31610 }
31611
31612 this._hash = createHash(data.hash)
31613 this._tag = data.id
31614 this._signType = data.sign
31615}
31616inherits(Verify, stream.Writable)
31617
31618Verify.prototype._write = function _write (data, _, done) {
31619 this._hash.update(data)
31620
31621 done()
31622}
31623
31624Verify.prototype.update = function update (data, enc) {
31625 if (typeof data === 'string') {
31626 data = new Buffer(data, enc)
31627 }
31628
31629 this._hash.update(data)
31630 return this
31631}
31632
31633Verify.prototype.verify = function verifyMethod (key, sig, enc) {
31634 if (typeof sig === 'string') {
31635 sig = new Buffer(sig, enc)
31636 }
31637
31638 this.end()
31639 var hash = this._hash.digest()
31640
31641 return verify(sig, Buffer.concat([this._tag, hash]), key, this._signType)
31642}
31643
31644function createSign (algorithm) {
31645 return new Sign(algorithm)
31646}
31647
31648function createVerify (algorithm) {
31649 return new Verify(algorithm)
31650}
31651
31652module.exports = {
31653 Sign: createSign,
31654 Verify: createVerify,
31655 createSign: createSign,
31656 createVerify: createVerify
31657}
31658}, {"./algos":163,"create-hash":148,"inherits":149,"./sign":202,"stream":52,"./verify":266}],202: [function (exports, require, module, global) {// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
31659var createHmac = require('create-hmac')
31660var crt = require('browserify-rsa')
31661var curves = require('./curves')
31662var elliptic = require('elliptic')
31663var parseKeys = require('parse-asn1')
31664
31665var BN = require('bn.js')
31666var EC = elliptic.ec
31667
31668function sign (hash, key, hashType, signType) {
31669 var priv = parseKeys(key)
31670 if (priv.curve) {
31671 if (signType !== 'ecdsa') throw new Error('wrong private key type')
31672
31673 return ecSign(hash, priv)
31674 } else if (priv.type === 'dsa') {
31675 if (signType !== 'dsa') {
31676 throw new Error('wrong private key type')
31677 }
31678 return dsaSign(hash, priv, hashType)
31679 } else {
31680 if (signType !== 'rsa') throw new Error('wrong private key type')
31681 }
31682
31683 var len = priv.modulus.byteLength()
31684 var pad = [ 0, 1 ]
31685 while (hash.length + pad.length + 1 < len) {
31686 pad.push(0xff)
31687 }
31688 pad.push(0x00)
31689 var i = -1
31690 while (++i < hash.length) {
31691 pad.push(hash[i])
31692 }
31693
31694 var out = crt(pad, priv)
31695 return out
31696}
31697
31698function ecSign (hash, priv) {
31699 var curveId = curves[priv.curve.join('.')]
31700 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
31701
31702 var curve = new EC(curveId)
31703 var key = curve.genKeyPair()
31704
31705 key._importPrivate(priv.privateKey)
31706 var out = key.sign(hash)
31707
31708 return new Buffer(out.toDER())
31709}
31710
31711function dsaSign (hash, priv, algo) {
31712 var x = priv.params.priv_key
31713 var p = priv.params.p
31714 var q = priv.params.q
31715 var g = priv.params.g
31716 var r = new BN(0)
31717 var k
31718 var H = bits2int(hash, q).mod(q)
31719 var s = false
31720 var kv = getKey(x, q, hash, algo)
31721 while (s === false) {
31722 k = makeKey(q, kv, algo)
31723 r = makeR(g, k, p, q)
31724 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
31725 if (!s.cmpn(0)) {
31726 s = false
31727 r = new BN(0)
31728 }
31729 }
31730 return toDER(r, s)
31731}
31732
31733function toDER (r, s) {
31734 r = r.toArray()
31735 s = s.toArray()
31736
31737 // Pad values
31738 if (r[0] & 0x80) {
31739 r = [ 0 ].concat(r)
31740 }
31741 // Pad values
31742 if (s[0] & 0x80) {
31743 s = [0].concat(s)
31744 }
31745
31746 var total = r.length + s.length + 4
31747 var res = [ 0x30, total, 0x02, r.length ]
31748 res = res.concat(r, [ 0x02, s.length ], s)
31749 return new Buffer(res)
31750}
31751
31752function getKey (x, q, hash, algo) {
31753 x = new Buffer(x.toArray())
31754 if (x.length < q.byteLength()) {
31755 var zeros = new Buffer(q.byteLength() - x.length)
31756 zeros.fill(0)
31757 x = Buffer.concat([zeros, x])
31758 }
31759 var hlen = hash.length
31760 var hbits = bits2octets(hash, q)
31761 var v = new Buffer(hlen)
31762 v.fill(1)
31763 var k = new Buffer(hlen)
31764 k.fill(0)
31765 k = createHmac(algo, k)
31766 .update(v)
31767 .update(new Buffer([0]))
31768 .update(x)
31769 .update(hbits)
31770 .digest()
31771 v = createHmac(algo, k)
31772 .update(v)
31773 .digest()
31774 k = createHmac(algo, k)
31775 .update(v)
31776 .update(new Buffer([1]))
31777 .update(x)
31778 .update(hbits)
31779 .digest()
31780 v = createHmac(algo, k)
31781 .update(v)
31782 .digest()
31783 return {
31784 k: k,
31785 v: v
31786 }
31787}
31788
31789function bits2int (obits, q) {
31790 var bits = new BN(obits)
31791 var shift = (obits.length << 3) - q.bitLength()
31792 if (shift > 0) {
31793 bits.ishrn(shift)
31794 }
31795 return bits
31796}
31797
31798function bits2octets (bits, q) {
31799 bits = bits2int(bits, q)
31800 bits = bits.mod(q)
31801 var out = new Buffer(bits.toArray())
31802 if (out.length < q.byteLength()) {
31803 var zeros = new Buffer(q.byteLength() - out.length)
31804 zeros.fill(0)
31805 out = Buffer.concat([zeros, out])
31806 }
31807 return out
31808}
31809
31810function makeKey (q, kv, algo) {
31811 var t, k
31812
31813 do {
31814 t = new Buffer('')
31815
31816 while (t.length * 8 < q.bitLength()) {
31817 kv.v = createHmac(algo, kv.k)
31818 .update(kv.v)
31819 .digest()
31820 t = Buffer.concat([t, kv.v])
31821 }
31822
31823 k = bits2int(t, q)
31824 kv.k = createHmac(algo, kv.k)
31825 .update(kv.v)
31826 .update(new Buffer([0]))
31827 .digest()
31828 kv.v = createHmac(algo, kv.k)
31829 .update(kv.v)
31830 .digest()
31831 } while (k.cmp(q) !== -1)
31832
31833 return k
31834}
31835
31836function makeR (g, k, p, q) {
31837 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
31838}
31839
31840module.exports = sign
31841module.exports.getKey = getKey
31842module.exports.makeKey = makeKey
31843}, {"create-hmac":162,"browserify-rsa":203,"./curves":205,"elliptic":206,"parse-asn1":227,"bn.js":204}],203: [function (exports, require, module, global) {var bn = require('bn.js');
31844var randomBytes = require('randombytes');
31845module.exports = crt;
31846function blind(priv) {
31847 var r = getr(priv);
31848 var blinder = r.toRed(bn.mont(priv.modulus))
31849 .redPow(new bn(priv.publicExponent)).fromRed();
31850 return {
31851 blinder: blinder,
31852 unblinder:r.invm(priv.modulus)
31853 };
31854}
31855function crt(msg, priv) {
31856 var blinds = blind(priv);
31857 var len = priv.modulus.byteLength();
31858 var mod = bn.mont(priv.modulus);
31859 var blinded = new bn(msg).mul(blinds.blinder).mod(priv.modulus);
31860 var c1 = blinded.toRed(bn.mont(priv.prime1));
31861 var c2 = blinded.toRed(bn.mont(priv.prime2));
31862 var qinv = priv.coefficient;
31863 var p = priv.prime1;
31864 var q = priv.prime2;
31865 var m1 = c1.redPow(priv.exponent1);
31866 var m2 = c2.redPow(priv.exponent2);
31867 m1 = m1.fromRed();
31868 m2 = m2.fromRed();
31869 var h = m1.isub(m2).imul(qinv).mod(p);
31870 h.imul(q);
31871 m2.iadd(h);
31872 var out = new Buffer(m2.imul(blinds.unblinder).mod(priv.modulus).toArray());
31873 if (out.length < len) {
31874 var prefix = new Buffer(len - out.length);
31875 prefix.fill(0);
31876 out = Buffer.concat([prefix, out], len);
31877 }
31878 return out;
31879}
31880crt.getr = getr;
31881function getr(priv) {
31882 var len = priv.modulus.byteLength();
31883 var r = new bn(randomBytes(len));
31884 while (r.cmp(priv.modulus) >= 0 || !r.mod(priv.prime1) || !r.mod(priv.prime2)) {
31885 r = new bn(randomBytes(len));
31886 }
31887 return r;
31888}}, {"bn.js":204,"randombytes":147}],204: [function (exports, require, module, global) {(function (module, exports) {
31889
31890'use strict';
31891
31892// Utils
31893
31894function assert(val, msg) {
31895 if (!val)
31896 throw new Error(msg || 'Assertion failed');
31897}
31898
31899// Could use `inherits` module, but don't want to move from single file
31900// architecture yet.
31901function inherits(ctor, superCtor) {
31902 ctor.super_ = superCtor;
31903 var TempCtor = function () {};
31904 TempCtor.prototype = superCtor.prototype;
31905 ctor.prototype = new TempCtor();
31906 ctor.prototype.constructor = ctor;
31907}
31908
31909// BN
31910
31911function BN(number, base, endian) {
31912 // May be `new BN(bn)` ?
31913 if (number !== null &&
31914 typeof number === 'object' &&
31915 Array.isArray(number.words)) {
31916 return number;
31917 }
31918
31919 this.sign = false;
31920 this.words = null;
31921 this.length = 0;
31922
31923 // Reduction context
31924 this.red = null;
31925
31926 if (base === 'le' || base === 'be') {
31927 endian = base;
31928 base = 10;
31929 }
31930
31931 if (number !== null)
31932 this._init(number || 0, base || 10, endian || 'be');
31933}
31934if (typeof module === 'object')
31935 module.exports = BN;
31936else
31937 exports.BN = BN;
31938
31939BN.BN = BN;
31940BN.wordSize = 26;
31941
31942BN.prototype._init = function init(number, base, endian) {
31943 if (typeof number === 'number') {
31944 return this._initNumber(number, base, endian);
31945 } else if (typeof number === 'object') {
31946 return this._initArray(number, base, endian);
31947 }
31948 if (base === 'hex')
31949 base = 16;
31950 assert(base === (base | 0) && base >= 2 && base <= 36);
31951
31952 number = number.toString().replace(/\s+/g, '');
31953 var start = 0;
31954 if (number[0] === '-')
31955 start++;
31956
31957 if (base === 16)
31958 this._parseHex(number, start);
31959 else
31960 this._parseBase(number, base, start);
31961
31962 if (number[0] === '-')
31963 this.sign = true;
31964
31965 this.strip();
31966
31967 if (endian !== 'le')
31968 return;
31969
31970 this._initArray(this.toArray(), base, endian);
31971};
31972
31973BN.prototype._initNumber = function _initNumber(number, base, endian) {
31974 if (number < 0) {
31975 this.sign = true;
31976 number = -number;
31977 }
31978 if (number < 0x4000000) {
31979 this.words = [ number & 0x3ffffff ];
31980 this.length = 1;
31981 } else if (number < 0x10000000000000) {
31982 this.words = [
31983 number & 0x3ffffff,
31984 (number / 0x4000000) & 0x3ffffff
31985 ];
31986 this.length = 2;
31987 } else {
31988 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
31989 this.words = [
31990 number & 0x3ffffff,
31991 (number / 0x4000000) & 0x3ffffff,
31992 1
31993 ];
31994 this.length = 3;
31995 }
31996
31997 if (endian !== 'le')
31998 return;
31999
32000 // Reverse the bytes
32001 this._initArray(this.toArray(), base, endian);
32002};
32003
32004BN.prototype._initArray = function _initArray(number, base, endian) {
32005 // Perhaps a Uint8Array
32006 assert(typeof number.length === 'number');
32007 if (number.length <= 0) {
32008 this.words = [ 0 ];
32009 this.length = 1;
32010 return this;
32011 }
32012
32013 this.length = Math.ceil(number.length / 3);
32014 this.words = new Array(this.length);
32015 for (var i = 0; i < this.length; i++)
32016 this.words[i] = 0;
32017
32018 var off = 0;
32019 if (endian === 'be') {
32020 for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
32021 var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
32022 this.words[j] |= (w << off) & 0x3ffffff;
32023 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
32024 off += 24;
32025 if (off >= 26) {
32026 off -= 26;
32027 j++;
32028 }
32029 }
32030 } else if (endian === 'le') {
32031 for (var i = 0, j = 0; i < number.length; i += 3) {
32032 var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
32033 this.words[j] |= (w << off) & 0x3ffffff;
32034 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
32035 off += 24;
32036 if (off >= 26) {
32037 off -= 26;
32038 j++;
32039 }
32040 }
32041 }
32042 return this.strip();
32043};
32044
32045function parseHex(str, start, end) {
32046 var r = 0;
32047 var len = Math.min(str.length, end);
32048 for (var i = start; i < len; i++) {
32049 var c = str.charCodeAt(i) - 48;
32050
32051 r <<= 4;
32052
32053 // 'a' - 'f'
32054 if (c >= 49 && c <= 54)
32055 r |= c - 49 + 0xa;
32056
32057 // 'A' - 'F'
32058 else if (c >= 17 && c <= 22)
32059 r |= c - 17 + 0xa;
32060
32061 // '0' - '9'
32062 else
32063 r |= c & 0xf;
32064 }
32065 return r;
32066}
32067
32068BN.prototype._parseHex = function _parseHex(number, start) {
32069 // Create possibly bigger array to ensure that it fits the number
32070 this.length = Math.ceil((number.length - start) / 6);
32071 this.words = new Array(this.length);
32072 for (var i = 0; i < this.length; i++)
32073 this.words[i] = 0;
32074
32075 // Scan 24-bit chunks and add them to the number
32076 var off = 0;
32077 for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
32078 var w = parseHex(number, i, i + 6);
32079 this.words[j] |= (w << off) & 0x3ffffff;
32080 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
32081 off += 24;
32082 if (off >= 26) {
32083 off -= 26;
32084 j++;
32085 }
32086 }
32087 if (i + 6 !== start) {
32088 var w = parseHex(number, start, i + 6);
32089 this.words[j] |= (w << off) & 0x3ffffff;
32090 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
32091 }
32092 this.strip();
32093};
32094
32095function parseBase(str, start, end, mul) {
32096 var r = 0;
32097 var len = Math.min(str.length, end);
32098 for (var i = start; i < len; i++) {
32099 var c = str.charCodeAt(i) - 48;
32100
32101 r *= mul;
32102
32103 // 'a'
32104 if (c >= 49)
32105 r += c - 49 + 0xa;
32106
32107 // 'A'
32108 else if (c >= 17)
32109 r += c - 17 + 0xa;
32110
32111 // '0' - '9'
32112 else
32113 r += c;
32114 }
32115 return r;
32116}
32117
32118BN.prototype._parseBase = function _parseBase(number, base, start) {
32119 // Initialize as zero
32120 this.words = [ 0 ];
32121 this.length = 1;
32122
32123 // Find length of limb in base
32124 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
32125 limbLen++;
32126 limbLen--;
32127 limbPow = (limbPow / base) | 0;
32128
32129 var total = number.length - start;
32130 var mod = total % limbLen;
32131 var end = Math.min(total, total - mod) + start;
32132
32133 var word = 0;
32134 for (var i = start; i < end; i += limbLen) {
32135 word = parseBase(number, i, i + limbLen, base);
32136
32137 this.imuln(limbPow);
32138 if (this.words[0] + word < 0x4000000)
32139 this.words[0] += word;
32140 else
32141 this._iaddn(word);
32142 }
32143
32144 if (mod !== 0) {
32145 var pow = 1;
32146 var word = parseBase(number, i, number.length, base);
32147
32148 for (var i = 0; i < mod; i++)
32149 pow *= base;
32150 this.imuln(pow);
32151 if (this.words[0] + word < 0x4000000)
32152 this.words[0] += word;
32153 else
32154 this._iaddn(word);
32155 }
32156};
32157
32158BN.prototype.copy = function copy(dest) {
32159 dest.words = new Array(this.length);
32160 for (var i = 0; i < this.length; i++)
32161 dest.words[i] = this.words[i];
32162 dest.length = this.length;
32163 dest.sign = this.sign;
32164 dest.red = this.red;
32165};
32166
32167BN.prototype.clone = function clone() {
32168 var r = new BN(null);
32169 this.copy(r);
32170 return r;
32171};
32172
32173// Remove leading `0` from `this`
32174BN.prototype.strip = function strip() {
32175 while (this.length > 1 && this.words[this.length - 1] === 0)
32176 this.length--;
32177 return this._normSign();
32178};
32179
32180BN.prototype._normSign = function _normSign() {
32181 // -0 = 0
32182 if (this.length === 1 && this.words[0] === 0)
32183 this.sign = false;
32184 return this;
32185};
32186
32187BN.prototype.inspect = function inspect() {
32188 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
32189};
32190
32191/*
32192
32193var zeros = [];
32194var groupSizes = [];
32195var groupBases = [];
32196
32197var s = '';
32198var i = -1;
32199while (++i < BN.wordSize) {
32200 zeros[i] = s;
32201 s += '0';
32202}
32203groupSizes[0] = 0;
32204groupSizes[1] = 0;
32205groupBases[0] = 0;
32206groupBases[1] = 0;
32207var base = 2 - 1;
32208while (++base < 36 + 1) {
32209 var groupSize = 0;
32210 var groupBase = 1;
32211 while (groupBase < (1 << BN.wordSize) / base) {
32212 groupBase *= base;
32213 groupSize += 1;
32214 }
32215 groupSizes[base] = groupSize;
32216 groupBases[base] = groupBase;
32217}
32218
32219*/
32220
32221var zeros = [
32222 '',
32223 '0',
32224 '00',
32225 '000',
32226 '0000',
32227 '00000',
32228 '000000',
32229 '0000000',
32230 '00000000',
32231 '000000000',
32232 '0000000000',
32233 '00000000000',
32234 '000000000000',
32235 '0000000000000',
32236 '00000000000000',
32237 '000000000000000',
32238 '0000000000000000',
32239 '00000000000000000',
32240 '000000000000000000',
32241 '0000000000000000000',
32242 '00000000000000000000',
32243 '000000000000000000000',
32244 '0000000000000000000000',
32245 '00000000000000000000000',
32246 '000000000000000000000000',
32247 '0000000000000000000000000'
32248];
32249
32250var groupSizes = [
32251 0, 0,
32252 25, 16, 12, 11, 10, 9, 8,
32253 8, 7, 7, 7, 7, 6, 6,
32254 6, 6, 6, 6, 6, 5, 5,
32255 5, 5, 5, 5, 5, 5, 5,
32256 5, 5, 5, 5, 5, 5, 5
32257];
32258
32259var groupBases = [
32260 0, 0,
32261 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
32262 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
32263 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
32264 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
32265 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
32266];
32267
32268BN.prototype.toString = function toString(base, padding) {
32269 base = base || 10;
32270 if (base === 16 || base === 'hex') {
32271 var out = '';
32272 var off = 0;
32273 var padding = padding | 0 || 1;
32274 var carry = 0;
32275 for (var i = 0; i < this.length; i++) {
32276 var w = this.words[i];
32277 var word = (((w << off) | carry) & 0xffffff).toString(16);
32278 carry = (w >>> (24 - off)) & 0xffffff;
32279 if (carry !== 0 || i !== this.length - 1)
32280 out = zeros[6 - word.length] + word + out;
32281 else
32282 out = word + out;
32283 off += 2;
32284 if (off >= 26) {
32285 off -= 26;
32286 i--;
32287 }
32288 }
32289 if (carry !== 0)
32290 out = carry.toString(16) + out;
32291 while (out.length % padding !== 0)
32292 out = '0' + out;
32293 if (this.sign)
32294 out = '-' + out;
32295 return out;
32296 } else if (base === (base | 0) && base >= 2 && base <= 36) {
32297 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
32298 var groupSize = groupSizes[base];
32299 // var groupBase = Math.pow(base, groupSize);
32300 var groupBase = groupBases[base];
32301 var out = '';
32302 var c = this.clone();
32303 c.sign = false;
32304 while (c.cmpn(0) !== 0) {
32305 var r = c.modn(groupBase).toString(base);
32306 c = c.idivn(groupBase);
32307
32308 if (c.cmpn(0) !== 0)
32309 out = zeros[groupSize - r.length] + r + out;
32310 else
32311 out = r + out;
32312 }
32313 if (this.cmpn(0) === 0)
32314 out = '0' + out;
32315 if (this.sign)
32316 out = '-' + out;
32317 return out;
32318 } else {
32319 assert(false, 'Base should be between 2 and 36');
32320 }
32321};
32322
32323BN.prototype.toJSON = function toJSON() {
32324 return this.toString(16);
32325};
32326
32327BN.prototype.toArray = function toArray(endian) {
32328 this.strip();
32329 var res = new Array(this.byteLength());
32330 res[0] = 0;
32331
32332 var q = this.clone();
32333 if (endian !== 'le') {
32334 // Assume big-endian
32335 for (var i = 0; q.cmpn(0) !== 0; i++) {
32336 var b = q.andln(0xff);
32337 q.ishrn(8);
32338
32339 res[res.length - i - 1] = b;
32340 }
32341 } else {
32342 // Assume little-endian
32343 for (var i = 0; q.cmpn(0) !== 0; i++) {
32344 var b = q.andln(0xff);
32345 q.ishrn(8);
32346
32347 res[i] = b;
32348 }
32349 }
32350
32351 return res;
32352};
32353
32354if (Math.clz32) {
32355 BN.prototype._countBits = function _countBits(w) {
32356 return 32 - Math.clz32(w);
32357 };
32358} else {
32359 BN.prototype._countBits = function _countBits(w) {
32360 var t = w;
32361 var r = 0;
32362 if (t >= 0x1000) {
32363 r += 13;
32364 t >>>= 13;
32365 }
32366 if (t >= 0x40) {
32367 r += 7;
32368 t >>>= 7;
32369 }
32370 if (t >= 0x8) {
32371 r += 4;
32372 t >>>= 4;
32373 }
32374 if (t >= 0x02) {
32375 r += 2;
32376 t >>>= 2;
32377 }
32378 return r + t;
32379 };
32380}
32381
32382BN.prototype._zeroBits = function _zeroBits(w) {
32383 // Short-cut
32384 if (w === 0)
32385 return 26;
32386
32387 var t = w;
32388 var r = 0;
32389 if ((t & 0x1fff) === 0) {
32390 r += 13;
32391 t >>>= 13;
32392 }
32393 if ((t & 0x7f) === 0) {
32394 r += 7;
32395 t >>>= 7;
32396 }
32397 if ((t & 0xf) === 0) {
32398 r += 4;
32399 t >>>= 4;
32400 }
32401 if ((t & 0x3) === 0) {
32402 r += 2;
32403 t >>>= 2;
32404 }
32405 if ((t & 0x1) === 0)
32406 r++;
32407 return r;
32408};
32409
32410// Return number of used bits in a BN
32411BN.prototype.bitLength = function bitLength() {
32412 var hi = 0;
32413 var w = this.words[this.length - 1];
32414 var hi = this._countBits(w);
32415 return (this.length - 1) * 26 + hi;
32416};
32417
32418// Number of trailing zero bits
32419BN.prototype.zeroBits = function zeroBits() {
32420 if (this.cmpn(0) === 0)
32421 return 0;
32422
32423 var r = 0;
32424 for (var i = 0; i < this.length; i++) {
32425 var b = this._zeroBits(this.words[i]);
32426 r += b;
32427 if (b !== 26)
32428 break;
32429 }
32430 return r;
32431};
32432
32433BN.prototype.byteLength = function byteLength() {
32434 return Math.ceil(this.bitLength() / 8);
32435};
32436
32437// Return negative clone of `this`
32438BN.prototype.neg = function neg() {
32439 if (this.cmpn(0) === 0)
32440 return this.clone();
32441
32442 var r = this.clone();
32443 r.sign = !this.sign;
32444 return r;
32445};
32446
32447
32448// Or `num` with `this` in-place
32449BN.prototype.ior = function ior(num) {
32450 this.sign = this.sign || num.sign;
32451
32452 while (this.length < num.length)
32453 this.words[this.length++] = 0;
32454
32455 for (var i = 0; i < num.length; i++)
32456 this.words[i] = this.words[i] | num.words[i];
32457
32458 return this.strip();
32459};
32460
32461
32462// Or `num` with `this`
32463BN.prototype.or = function or(num) {
32464 if (this.length > num.length)
32465 return this.clone().ior(num);
32466 else
32467 return num.clone().ior(this);
32468};
32469
32470
32471// And `num` with `this` in-place
32472BN.prototype.iand = function iand(num) {
32473 this.sign = this.sign && num.sign;
32474
32475 // b = min-length(num, this)
32476 var b;
32477 if (this.length > num.length)
32478 b = num;
32479 else
32480 b = this;
32481
32482 for (var i = 0; i < b.length; i++)
32483 this.words[i] = this.words[i] & num.words[i];
32484
32485 this.length = b.length;
32486
32487 return this.strip();
32488};
32489
32490
32491// And `num` with `this`
32492BN.prototype.and = function and(num) {
32493 if (this.length > num.length)
32494 return this.clone().iand(num);
32495 else
32496 return num.clone().iand(this);
32497};
32498
32499
32500// Xor `num` with `this` in-place
32501BN.prototype.ixor = function ixor(num) {
32502 this.sign = this.sign || num.sign;
32503
32504 // a.length > b.length
32505 var a;
32506 var b;
32507 if (this.length > num.length) {
32508 a = this;
32509 b = num;
32510 } else {
32511 a = num;
32512 b = this;
32513 }
32514
32515 for (var i = 0; i < b.length; i++)
32516 this.words[i] = a.words[i] ^ b.words[i];
32517
32518 if (this !== a)
32519 for (; i < a.length; i++)
32520 this.words[i] = a.words[i];
32521
32522 this.length = a.length;
32523
32524 return this.strip();
32525};
32526
32527
32528// Xor `num` with `this`
32529BN.prototype.xor = function xor(num) {
32530 if (this.length > num.length)
32531 return this.clone().ixor(num);
32532 else
32533 return num.clone().ixor(this);
32534};
32535
32536
32537// Set `bit` of `this`
32538BN.prototype.setn = function setn(bit, val) {
32539 assert(typeof bit === 'number' && bit >= 0);
32540
32541 var off = (bit / 26) | 0;
32542 var wbit = bit % 26;
32543
32544 while (this.length <= off)
32545 this.words[this.length++] = 0;
32546
32547 if (val)
32548 this.words[off] = this.words[off] | (1 << wbit);
32549 else
32550 this.words[off] = this.words[off] & ~(1 << wbit);
32551
32552 return this.strip();
32553};
32554
32555
32556// Add `num` to `this` in-place
32557BN.prototype.iadd = function iadd(num) {
32558 // negative + positive
32559 if (this.sign && !num.sign) {
32560 this.sign = false;
32561 var r = this.isub(num);
32562 this.sign = !this.sign;
32563 return this._normSign();
32564
32565 // positive + negative
32566 } else if (!this.sign && num.sign) {
32567 num.sign = false;
32568 var r = this.isub(num);
32569 num.sign = true;
32570 return r._normSign();
32571 }
32572
32573 // a.length > b.length
32574 var a;
32575 var b;
32576 if (this.length > num.length) {
32577 a = this;
32578 b = num;
32579 } else {
32580 a = num;
32581 b = this;
32582 }
32583
32584 var carry = 0;
32585 for (var i = 0; i < b.length; i++) {
32586 var r = a.words[i] + b.words[i] + carry;
32587 this.words[i] = r & 0x3ffffff;
32588 carry = r >>> 26;
32589 }
32590 for (; carry !== 0 && i < a.length; i++) {
32591 var r = a.words[i] + carry;
32592 this.words[i] = r & 0x3ffffff;
32593 carry = r >>> 26;
32594 }
32595
32596 this.length = a.length;
32597 if (carry !== 0) {
32598 this.words[this.length] = carry;
32599 this.length++;
32600 // Copy the rest of the words
32601 } else if (a !== this) {
32602 for (; i < a.length; i++)
32603 this.words[i] = a.words[i];
32604 }
32605
32606 return this;
32607};
32608
32609// Add `num` to `this`
32610BN.prototype.add = function add(num) {
32611 if (num.sign && !this.sign) {
32612 num.sign = false;
32613 var res = this.sub(num);
32614 num.sign = true;
32615 return res;
32616 } else if (!num.sign && this.sign) {
32617 this.sign = false;
32618 var res = num.sub(this);
32619 this.sign = true;
32620 return res;
32621 }
32622
32623 if (this.length > num.length)
32624 return this.clone().iadd(num);
32625 else
32626 return num.clone().iadd(this);
32627};
32628
32629// Subtract `num` from `this` in-place
32630BN.prototype.isub = function isub(num) {
32631 // this - (-num) = this + num
32632 if (num.sign) {
32633 num.sign = false;
32634 var r = this.iadd(num);
32635 num.sign = true;
32636 return r._normSign();
32637
32638 // -this - num = -(this + num)
32639 } else if (this.sign) {
32640 this.sign = false;
32641 this.iadd(num);
32642 this.sign = true;
32643 return this._normSign();
32644 }
32645
32646 // At this point both numbers are positive
32647 var cmp = this.cmp(num);
32648
32649 // Optimization - zeroify
32650 if (cmp === 0) {
32651 this.sign = false;
32652 this.length = 1;
32653 this.words[0] = 0;
32654 return this;
32655 }
32656
32657 // a > b
32658 var a;
32659 var b;
32660 if (cmp > 0) {
32661 a = this;
32662 b = num;
32663 } else {
32664 a = num;
32665 b = this;
32666 }
32667
32668 var carry = 0;
32669 for (var i = 0; i < b.length; i++) {
32670 var r = a.words[i] - b.words[i] + carry;
32671 carry = r >> 26;
32672 this.words[i] = r & 0x3ffffff;
32673 }
32674 for (; carry !== 0 && i < a.length; i++) {
32675 var r = a.words[i] + carry;
32676 carry = r >> 26;
32677 this.words[i] = r & 0x3ffffff;
32678 }
32679
32680 // Copy rest of the words
32681 if (carry === 0 && i < a.length && a !== this)
32682 for (; i < a.length; i++)
32683 this.words[i] = a.words[i];
32684 this.length = Math.max(this.length, i);
32685
32686 if (a !== this)
32687 this.sign = true;
32688
32689 return this.strip();
32690};
32691
32692// Subtract `num` from `this`
32693BN.prototype.sub = function sub(num) {
32694 return this.clone().isub(num);
32695};
32696
32697/*
32698// NOTE: This could be potentionally used to generate loop-less multiplications
32699function _genCombMulTo(alen, blen) {
32700 var len = alen + blen - 1;
32701 var src = [
32702 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
32703 'mask = 0x3ffffff, shift = 0x4000000;',
32704 'out.length = ' + len + ';'
32705 ];
32706 for (var k = 0; k < len; k++) {
32707 var minJ = Math.max(0, k - alen + 1);
32708 var maxJ = Math.min(k, blen - 1);
32709
32710 for (var j = minJ; j <= maxJ; j++) {
32711 var i = k - j;
32712 var mul = 'a[' + i + '] * b[' + j + ']';
32713
32714 if (j === minJ) {
32715 src.push('w = ' + mul + ' + c;');
32716 src.push('c = (w / shift) | 0;');
32717 } else {
32718 src.push('w += ' + mul + ';');
32719 src.push('c += (w / shift) | 0;');
32720 }
32721 src.push('w &= mask;');
32722 }
32723 src.push('o[' + k + '] = w;');
32724 }
32725 src.push('if (c !== 0) {',
32726 ' o[' + k + '] = c;',
32727 ' out.length++;',
32728 '}',
32729 'return out;');
32730
32731 return src.join('\n');
32732}
32733*/
32734
32735BN.prototype._smallMulTo = function _smallMulTo(num, out) {
32736 out.sign = num.sign !== this.sign;
32737 out.length = this.length + num.length;
32738
32739 var carry = 0;
32740 for (var k = 0; k < out.length - 1; k++) {
32741 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
32742 // note that ncarry could be >= 0x3ffffff
32743 var ncarry = carry >>> 26;
32744 var rword = carry & 0x3ffffff;
32745 var maxJ = Math.min(k, num.length - 1);
32746 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
32747 var i = k - j;
32748 var a = this.words[i] | 0;
32749 var b = num.words[j] | 0;
32750 var r = a * b;
32751
32752 var lo = r & 0x3ffffff;
32753 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
32754 lo = (lo + rword) | 0;
32755 rword = lo & 0x3ffffff;
32756 ncarry = (ncarry + (lo >>> 26)) | 0;
32757 }
32758 out.words[k] = rword;
32759 carry = ncarry;
32760 }
32761 if (carry !== 0) {
32762 out.words[k] = carry;
32763 } else {
32764 out.length--;
32765 }
32766
32767 return out.strip();
32768};
32769
32770BN.prototype._bigMulTo = function _bigMulTo(num, out) {
32771 out.sign = num.sign !== this.sign;
32772 out.length = this.length + num.length;
32773
32774 var carry = 0;
32775 var hncarry = 0;
32776 for (var k = 0; k < out.length - 1; k++) {
32777 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
32778 // note that ncarry could be >= 0x3ffffff
32779 var ncarry = hncarry;
32780 hncarry = 0;
32781 var rword = carry & 0x3ffffff;
32782 var maxJ = Math.min(k, num.length - 1);
32783 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
32784 var i = k - j;
32785 var a = this.words[i] | 0;
32786 var b = num.words[j] | 0;
32787 var r = a * b;
32788
32789 var lo = r & 0x3ffffff;
32790 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
32791 lo = (lo + rword) | 0;
32792 rword = lo & 0x3ffffff;
32793 ncarry = (ncarry + (lo >>> 26)) | 0;
32794
32795 hncarry += ncarry >>> 26;
32796 ncarry &= 0x3ffffff;
32797 }
32798 out.words[k] = rword;
32799 carry = ncarry;
32800 ncarry = hncarry;
32801 }
32802 if (carry !== 0) {
32803 out.words[k] = carry;
32804 } else {
32805 out.length--;
32806 }
32807
32808 return out.strip();
32809};
32810
32811BN.prototype.mulTo = function mulTo(num, out) {
32812 var res;
32813 if (this.length + num.length < 63)
32814 res = this._smallMulTo(num, out);
32815 else
32816 res = this._bigMulTo(num, out);
32817 return res;
32818};
32819
32820// Multiply `this` by `num`
32821BN.prototype.mul = function mul(num) {
32822 var out = new BN(null);
32823 out.words = new Array(this.length + num.length);
32824 return this.mulTo(num, out);
32825};
32826
32827// In-place Multiplication
32828BN.prototype.imul = function imul(num) {
32829 if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
32830 this.words[0] = 0;
32831 this.length = 1;
32832 return this;
32833 }
32834
32835 var tlen = this.length;
32836 var nlen = num.length;
32837
32838 this.sign = num.sign !== this.sign;
32839 this.length = this.length + num.length;
32840 this.words[this.length - 1] = 0;
32841
32842 for (var k = this.length - 2; k >= 0; k--) {
32843 // Sum all words with the same `i + j = k` and accumulate `carry`,
32844 // note that carry could be >= 0x3ffffff
32845 var carry = 0;
32846 var rword = 0;
32847 var maxJ = Math.min(k, nlen - 1);
32848 for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
32849 var i = k - j;
32850 var a = this.words[i];
32851 var b = num.words[j];
32852 var r = a * b;
32853
32854 var lo = r & 0x3ffffff;
32855 carry += (r / 0x4000000) | 0;
32856 lo += rword;
32857 rword = lo & 0x3ffffff;
32858 carry += lo >>> 26;
32859 }
32860 this.words[k] = rword;
32861 this.words[k + 1] += carry;
32862 carry = 0;
32863 }
32864
32865 // Propagate overflows
32866 var carry = 0;
32867 for (var i = 1; i < this.length; i++) {
32868 var w = this.words[i] + carry;
32869 this.words[i] = w & 0x3ffffff;
32870 carry = w >>> 26;
32871 }
32872
32873 return this.strip();
32874};
32875
32876BN.prototype.imuln = function imuln(num) {
32877 assert(typeof num === 'number');
32878
32879 // Carry
32880 var carry = 0;
32881 for (var i = 0; i < this.length; i++) {
32882 var w = this.words[i] * num;
32883 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
32884 carry >>= 26;
32885 carry += (w / 0x4000000) | 0;
32886 // NOTE: lo is 27bit maximum
32887 carry += lo >>> 26;
32888 this.words[i] = lo & 0x3ffffff;
32889 }
32890
32891 if (carry !== 0) {
32892 this.words[i] = carry;
32893 this.length++;
32894 }
32895
32896 return this;
32897};
32898
32899BN.prototype.muln = function muln(num) {
32900 return this.clone().imuln(num);
32901};
32902
32903// `this` * `this`
32904BN.prototype.sqr = function sqr() {
32905 return this.mul(this);
32906};
32907
32908// `this` * `this` in-place
32909BN.prototype.isqr = function isqr() {
32910 return this.mul(this);
32911};
32912
32913// Shift-left in-place
32914BN.prototype.ishln = function ishln(bits) {
32915 assert(typeof bits === 'number' && bits >= 0);
32916 var r = bits % 26;
32917 var s = (bits - r) / 26;
32918 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
32919
32920 if (r !== 0) {
32921 var carry = 0;
32922 for (var i = 0; i < this.length; i++) {
32923 var newCarry = this.words[i] & carryMask;
32924 var c = (this.words[i] - newCarry) << r;
32925 this.words[i] = c | carry;
32926 carry = newCarry >>> (26 - r);
32927 }
32928 if (carry) {
32929 this.words[i] = carry;
32930 this.length++;
32931 }
32932 }
32933
32934 if (s !== 0) {
32935 for (var i = this.length - 1; i >= 0; i--)
32936 this.words[i + s] = this.words[i];
32937 for (var i = 0; i < s; i++)
32938 this.words[i] = 0;
32939 this.length += s;
32940 }
32941
32942 return this.strip();
32943};
32944
32945// Shift-right in-place
32946// NOTE: `hint` is a lowest bit before trailing zeroes
32947// NOTE: if `extended` is present - it will be filled with destroyed bits
32948BN.prototype.ishrn = function ishrn(bits, hint, extended) {
32949 assert(typeof bits === 'number' && bits >= 0);
32950 var h;
32951 if (hint)
32952 h = (hint - (hint % 26)) / 26;
32953 else
32954 h = 0;
32955
32956 var r = bits % 26;
32957 var s = Math.min((bits - r) / 26, this.length);
32958 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
32959 var maskedWords = extended;
32960
32961 h -= s;
32962 h = Math.max(0, h);
32963
32964 // Extended mode, copy masked part
32965 if (maskedWords) {
32966 for (var i = 0; i < s; i++)
32967 maskedWords.words[i] = this.words[i];
32968 maskedWords.length = s;
32969 }
32970
32971 if (s === 0) {
32972 // No-op, we should not move anything at all
32973 } else if (this.length > s) {
32974 this.length -= s;
32975 for (var i = 0; i < this.length; i++)
32976 this.words[i] = this.words[i + s];
32977 } else {
32978 this.words[0] = 0;
32979 this.length = 1;
32980 }
32981
32982 var carry = 0;
32983 for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
32984 var word = this.words[i];
32985 this.words[i] = (carry << (26 - r)) | (word >>> r);
32986 carry = word & mask;
32987 }
32988
32989 // Push carried bits as a mask
32990 if (maskedWords && carry !== 0)
32991 maskedWords.words[maskedWords.length++] = carry;
32992
32993 if (this.length === 0) {
32994 this.words[0] = 0;
32995 this.length = 1;
32996 }
32997
32998 this.strip();
32999
33000 return this;
33001};
33002
33003// Shift-left
33004BN.prototype.shln = function shln(bits) {
33005 return this.clone().ishln(bits);
33006};
33007
33008// Shift-right
33009BN.prototype.shrn = function shrn(bits) {
33010 return this.clone().ishrn(bits);
33011};
33012
33013// Test if n bit is set
33014BN.prototype.testn = function testn(bit) {
33015 assert(typeof bit === 'number' && bit >= 0);
33016 var r = bit % 26;
33017 var s = (bit - r) / 26;
33018 var q = 1 << r;
33019
33020 // Fast case: bit is much higher than all existing words
33021 if (this.length <= s) {
33022 return false;
33023 }
33024
33025 // Check bit and return
33026 var w = this.words[s];
33027
33028 return !!(w & q);
33029};
33030
33031// Return only lowers bits of number (in-place)
33032BN.prototype.imaskn = function imaskn(bits) {
33033 assert(typeof bits === 'number' && bits >= 0);
33034 var r = bits % 26;
33035 var s = (bits - r) / 26;
33036
33037 assert(!this.sign, 'imaskn works only with positive numbers');
33038
33039 if (r !== 0)
33040 s++;
33041 this.length = Math.min(s, this.length);
33042
33043 if (r !== 0) {
33044 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
33045 this.words[this.length - 1] &= mask;
33046 }
33047
33048 return this.strip();
33049};
33050
33051// Return only lowers bits of number
33052BN.prototype.maskn = function maskn(bits) {
33053 return this.clone().imaskn(bits);
33054};
33055
33056// Add plain number `num` to `this`
33057BN.prototype.iaddn = function iaddn(num) {
33058 assert(typeof num === 'number');
33059 if (num < 0)
33060 return this.isubn(-num);
33061
33062 // Possible sign change
33063 if (this.sign) {
33064 if (this.length === 1 && this.words[0] < num) {
33065 this.words[0] = num - this.words[0];
33066 this.sign = false;
33067 return this;
33068 }
33069
33070 this.sign = false;
33071 this.isubn(num);
33072 this.sign = true;
33073 return this;
33074 }
33075
33076 // Add without checks
33077 return this._iaddn(num);
33078};
33079
33080BN.prototype._iaddn = function _iaddn(num) {
33081 this.words[0] += num;
33082
33083 // Carry
33084 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
33085 this.words[i] -= 0x4000000;
33086 if (i === this.length - 1)
33087 this.words[i + 1] = 1;
33088 else
33089 this.words[i + 1]++;
33090 }
33091 this.length = Math.max(this.length, i + 1);
33092
33093 return this;
33094};
33095
33096// Subtract plain number `num` from `this`
33097BN.prototype.isubn = function isubn(num) {
33098 assert(typeof num === 'number');
33099 if (num < 0)
33100 return this.iaddn(-num);
33101
33102 if (this.sign) {
33103 this.sign = false;
33104 this.iaddn(num);
33105 this.sign = true;
33106 return this;
33107 }
33108
33109 this.words[0] -= num;
33110
33111 // Carry
33112 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
33113 this.words[i] += 0x4000000;
33114 this.words[i + 1] -= 1;
33115 }
33116
33117 return this.strip();
33118};
33119
33120BN.prototype.addn = function addn(num) {
33121 return this.clone().iaddn(num);
33122};
33123
33124BN.prototype.subn = function subn(num) {
33125 return this.clone().isubn(num);
33126};
33127
33128BN.prototype.iabs = function iabs() {
33129 this.sign = false;
33130
33131 return this;
33132};
33133
33134BN.prototype.abs = function abs() {
33135 return this.clone().iabs();
33136};
33137
33138BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
33139 // Bigger storage is needed
33140 var len = num.length + shift;
33141 var i;
33142 if (this.words.length < len) {
33143 var t = new Array(len);
33144 for (var i = 0; i < this.length; i++)
33145 t[i] = this.words[i];
33146 this.words = t;
33147 } else {
33148 i = this.length;
33149 }
33150
33151 // Zeroify rest
33152 this.length = Math.max(this.length, len);
33153 for (; i < this.length; i++)
33154 this.words[i] = 0;
33155
33156 var carry = 0;
33157 for (var i = 0; i < num.length; i++) {
33158 var w = this.words[i + shift] + carry;
33159 var right = num.words[i] * mul;
33160 w -= right & 0x3ffffff;
33161 carry = (w >> 26) - ((right / 0x4000000) | 0);
33162 this.words[i + shift] = w & 0x3ffffff;
33163 }
33164 for (; i < this.length - shift; i++) {
33165 var w = this.words[i + shift] + carry;
33166 carry = w >> 26;
33167 this.words[i + shift] = w & 0x3ffffff;
33168 }
33169
33170 if (carry === 0)
33171 return this.strip();
33172
33173 // Subtraction overflow
33174 assert(carry === -1);
33175 carry = 0;
33176 for (var i = 0; i < this.length; i++) {
33177 var w = -this.words[i] + carry;
33178 carry = w >> 26;
33179 this.words[i] = w & 0x3ffffff;
33180 }
33181 this.sign = true;
33182
33183 return this.strip();
33184};
33185
33186BN.prototype._wordDiv = function _wordDiv(num, mode) {
33187 var shift = this.length - num.length;
33188
33189 var a = this.clone();
33190 var b = num;
33191
33192 // Normalize
33193 var bhi = b.words[b.length - 1];
33194 var bhiBits = this._countBits(bhi);
33195 shift = 26 - bhiBits;
33196 if (shift !== 0) {
33197 b = b.shln(shift);
33198 a.ishln(shift);
33199 bhi = b.words[b.length - 1];
33200 }
33201
33202 // Initialize quotient
33203 var m = a.length - b.length;
33204 var q;
33205
33206 if (mode !== 'mod') {
33207 q = new BN(null);
33208 q.length = m + 1;
33209 q.words = new Array(q.length);
33210 for (var i = 0; i < q.length; i++)
33211 q.words[i] = 0;
33212 }
33213
33214 var diff = a.clone()._ishlnsubmul(b, 1, m);
33215 if (!diff.sign) {
33216 a = diff;
33217 if (q)
33218 q.words[m] = 1;
33219 }
33220
33221 for (var j = m - 1; j >= 0; j--) {
33222 var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
33223
33224 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
33225 // (0x7ffffff)
33226 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
33227
33228 a._ishlnsubmul(b, qj, j);
33229 while (a.sign) {
33230 qj--;
33231 a.sign = false;
33232 a._ishlnsubmul(b, 1, j);
33233 if (a.cmpn(0) !== 0)
33234 a.sign = !a.sign;
33235 }
33236 if (q)
33237 q.words[j] = qj;
33238 }
33239 if (q)
33240 q.strip();
33241 a.strip();
33242
33243 // Denormalize
33244 if (mode !== 'div' && shift !== 0)
33245 a.ishrn(shift);
33246 return { div: q ? q : null, mod: a };
33247};
33248
33249BN.prototype.divmod = function divmod(num, mode) {
33250 assert(num.cmpn(0) !== 0);
33251
33252 if (this.sign && !num.sign) {
33253 var res = this.neg().divmod(num, mode);
33254 var div;
33255 var mod;
33256 if (mode !== 'mod')
33257 div = res.div.neg();
33258 if (mode !== 'div')
33259 mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod);
33260 return {
33261 div: div,
33262 mod: mod
33263 };
33264 } else if (!this.sign && num.sign) {
33265 var res = this.divmod(num.neg(), mode);
33266 var div;
33267 if (mode !== 'mod')
33268 div = res.div.neg();
33269 return { div: div, mod: res.mod };
33270 } else if (this.sign && num.sign) {
33271 return this.neg().divmod(num.neg(), mode);
33272 }
33273
33274 // Both numbers are positive at this point
33275
33276 // Strip both numbers to approximate shift value
33277 if (num.length > this.length || this.cmp(num) < 0)
33278 return { div: new BN(0), mod: this };
33279
33280 // Very short reduction
33281 if (num.length === 1) {
33282 if (mode === 'div')
33283 return { div: this.divn(num.words[0]), mod: null };
33284 else if (mode === 'mod')
33285 return { div: null, mod: new BN(this.modn(num.words[0])) };
33286 return {
33287 div: this.divn(num.words[0]),
33288 mod: new BN(this.modn(num.words[0]))
33289 };
33290 }
33291
33292 return this._wordDiv(num, mode);
33293};
33294
33295// Find `this` / `num`
33296BN.prototype.div = function div(num) {
33297 return this.divmod(num, 'div').div;
33298};
33299
33300// Find `this` % `num`
33301BN.prototype.mod = function mod(num) {
33302 return this.divmod(num, 'mod').mod;
33303};
33304
33305// Find Round(`this` / `num`)
33306BN.prototype.divRound = function divRound(num) {
33307 var dm = this.divmod(num);
33308
33309 // Fast case - exact division
33310 if (dm.mod.cmpn(0) === 0)
33311 return dm.div;
33312
33313 var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
33314
33315 var half = num.shrn(1);
33316 var r2 = num.andln(1);
33317 var cmp = mod.cmp(half);
33318
33319 // Round down
33320 if (cmp < 0 || r2 === 1 && cmp === 0)
33321 return dm.div;
33322
33323 // Round up
33324 return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
33325};
33326
33327BN.prototype.modn = function modn(num) {
33328 assert(num <= 0x3ffffff);
33329 var p = (1 << 26) % num;
33330
33331 var acc = 0;
33332 for (var i = this.length - 1; i >= 0; i--)
33333 acc = (p * acc + this.words[i]) % num;
33334
33335 return acc;
33336};
33337
33338// In-place division by number
33339BN.prototype.idivn = function idivn(num) {
33340 assert(num <= 0x3ffffff);
33341
33342 var carry = 0;
33343 for (var i = this.length - 1; i >= 0; i--) {
33344 var w = this.words[i] + carry * 0x4000000;
33345 this.words[i] = (w / num) | 0;
33346 carry = w % num;
33347 }
33348
33349 return this.strip();
33350};
33351
33352BN.prototype.divn = function divn(num) {
33353 return this.clone().idivn(num);
33354};
33355
33356BN.prototype.egcd = function egcd(p) {
33357 assert(!p.sign);
33358 assert(p.cmpn(0) !== 0);
33359
33360 var x = this;
33361 var y = p.clone();
33362
33363 if (x.sign)
33364 x = x.mod(p);
33365 else
33366 x = x.clone();
33367
33368 // A * x + B * y = x
33369 var A = new BN(1);
33370 var B = new BN(0);
33371
33372 // C * x + D * y = y
33373 var C = new BN(0);
33374 var D = new BN(1);
33375
33376 var g = 0;
33377
33378 while (x.isEven() && y.isEven()) {
33379 x.ishrn(1);
33380 y.ishrn(1);
33381 ++g;
33382 }
33383
33384 var yp = y.clone();
33385 var xp = x.clone();
33386
33387 while (x.cmpn(0) !== 0) {
33388 while (x.isEven()) {
33389 x.ishrn(1);
33390 if (A.isEven() && B.isEven()) {
33391 A.ishrn(1);
33392 B.ishrn(1);
33393 } else {
33394 A.iadd(yp).ishrn(1);
33395 B.isub(xp).ishrn(1);
33396 }
33397 }
33398
33399 while (y.isEven()) {
33400 y.ishrn(1);
33401 if (C.isEven() && D.isEven()) {
33402 C.ishrn(1);
33403 D.ishrn(1);
33404 } else {
33405 C.iadd(yp).ishrn(1);
33406 D.isub(xp).ishrn(1);
33407 }
33408 }
33409
33410 if (x.cmp(y) >= 0) {
33411 x.isub(y);
33412 A.isub(C);
33413 B.isub(D);
33414 } else {
33415 y.isub(x);
33416 C.isub(A);
33417 D.isub(B);
33418 }
33419 }
33420
33421 return {
33422 a: C,
33423 b: D,
33424 gcd: y.ishln(g)
33425 };
33426};
33427
33428// This is reduced incarnation of the binary EEA
33429// above, designated to invert members of the
33430// _prime_ fields F(p) at a maximal speed
33431BN.prototype._invmp = function _invmp(p) {
33432 assert(!p.sign);
33433 assert(p.cmpn(0) !== 0);
33434
33435 var a = this;
33436 var b = p.clone();
33437
33438 if (a.sign)
33439 a = a.mod(p);
33440 else
33441 a = a.clone();
33442
33443 var x1 = new BN(1);
33444 var x2 = new BN(0);
33445
33446 var delta = b.clone();
33447
33448 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
33449 while (a.isEven()) {
33450 a.ishrn(1);
33451 if (x1.isEven())
33452 x1.ishrn(1);
33453 else
33454 x1.iadd(delta).ishrn(1);
33455 }
33456 while (b.isEven()) {
33457 b.ishrn(1);
33458 if (x2.isEven())
33459 x2.ishrn(1);
33460 else
33461 x2.iadd(delta).ishrn(1);
33462 }
33463 if (a.cmp(b) >= 0) {
33464 a.isub(b);
33465 x1.isub(x2);
33466 } else {
33467 b.isub(a);
33468 x2.isub(x1);
33469 }
33470 }
33471 if (a.cmpn(1) === 0)
33472 return x1;
33473 else
33474 return x2;
33475};
33476
33477BN.prototype.gcd = function gcd(num) {
33478 if (this.cmpn(0) === 0)
33479 return num.clone();
33480 if (num.cmpn(0) === 0)
33481 return this.clone();
33482
33483 var a = this.clone();
33484 var b = num.clone();
33485 a.sign = false;
33486 b.sign = false;
33487
33488 // Remove common factor of two
33489 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
33490 a.ishrn(1);
33491 b.ishrn(1);
33492 }
33493
33494 do {
33495 while (a.isEven())
33496 a.ishrn(1);
33497 while (b.isEven())
33498 b.ishrn(1);
33499
33500 var r = a.cmp(b);
33501 if (r < 0) {
33502 // Swap `a` and `b` to make `a` always bigger than `b`
33503 var t = a;
33504 a = b;
33505 b = t;
33506 } else if (r === 0 || b.cmpn(1) === 0) {
33507 break;
33508 }
33509
33510 a.isub(b);
33511 } while (true);
33512
33513 return b.ishln(shift);
33514};
33515
33516// Invert number in the field F(num)
33517BN.prototype.invm = function invm(num) {
33518 return this.egcd(num).a.mod(num);
33519};
33520
33521BN.prototype.isEven = function isEven() {
33522 return (this.words[0] & 1) === 0;
33523};
33524
33525BN.prototype.isOdd = function isOdd() {
33526 return (this.words[0] & 1) === 1;
33527};
33528
33529// And first word and num
33530BN.prototype.andln = function andln(num) {
33531 return this.words[0] & num;
33532};
33533
33534// Increment at the bit position in-line
33535BN.prototype.bincn = function bincn(bit) {
33536 assert(typeof bit === 'number');
33537 var r = bit % 26;
33538 var s = (bit - r) / 26;
33539 var q = 1 << r;
33540
33541 // Fast case: bit is much higher than all existing words
33542 if (this.length <= s) {
33543 for (var i = this.length; i < s + 1; i++)
33544 this.words[i] = 0;
33545 this.words[s] |= q;
33546 this.length = s + 1;
33547 return this;
33548 }
33549
33550 // Add bit and propagate, if needed
33551 var carry = q;
33552 for (var i = s; carry !== 0 && i < this.length; i++) {
33553 var w = this.words[i];
33554 w += carry;
33555 carry = w >>> 26;
33556 w &= 0x3ffffff;
33557 this.words[i] = w;
33558 }
33559 if (carry !== 0) {
33560 this.words[i] = carry;
33561 this.length++;
33562 }
33563 return this;
33564};
33565
33566BN.prototype.cmpn = function cmpn(num) {
33567 var sign = num < 0;
33568 if (sign)
33569 num = -num;
33570
33571 if (this.sign && !sign)
33572 return -1;
33573 else if (!this.sign && sign)
33574 return 1;
33575
33576 num &= 0x3ffffff;
33577 this.strip();
33578
33579 var res;
33580 if (this.length > 1) {
33581 res = 1;
33582 } else {
33583 var w = this.words[0];
33584 res = w === num ? 0 : w < num ? -1 : 1;
33585 }
33586 if (this.sign)
33587 res = -res;
33588 return res;
33589};
33590
33591// Compare two numbers and return:
33592// 1 - if `this` > `num`
33593// 0 - if `this` == `num`
33594// -1 - if `this` < `num`
33595BN.prototype.cmp = function cmp(num) {
33596 if (this.sign && !num.sign)
33597 return -1;
33598 else if (!this.sign && num.sign)
33599 return 1;
33600
33601 var res = this.ucmp(num);
33602 if (this.sign)
33603 return -res;
33604 else
33605 return res;
33606};
33607
33608// Unsigned comparison
33609BN.prototype.ucmp = function ucmp(num) {
33610 // At this point both numbers have the same sign
33611 if (this.length > num.length)
33612 return 1;
33613 else if (this.length < num.length)
33614 return -1;
33615
33616 var res = 0;
33617 for (var i = this.length - 1; i >= 0; i--) {
33618 var a = this.words[i];
33619 var b = num.words[i];
33620
33621 if (a === b)
33622 continue;
33623 if (a < b)
33624 res = -1;
33625 else if (a > b)
33626 res = 1;
33627 break;
33628 }
33629 return res;
33630};
33631
33632//
33633// A reduce context, could be using montgomery or something better, depending
33634// on the `m` itself.
33635//
33636BN.red = function red(num) {
33637 return new Red(num);
33638};
33639
33640BN.prototype.toRed = function toRed(ctx) {
33641 assert(!this.red, 'Already a number in reduction context');
33642 assert(!this.sign, 'red works only with positives');
33643 return ctx.convertTo(this)._forceRed(ctx);
33644};
33645
33646BN.prototype.fromRed = function fromRed() {
33647 assert(this.red, 'fromRed works only with numbers in reduction context');
33648 return this.red.convertFrom(this);
33649};
33650
33651BN.prototype._forceRed = function _forceRed(ctx) {
33652 this.red = ctx;
33653 return this;
33654};
33655
33656BN.prototype.forceRed = function forceRed(ctx) {
33657 assert(!this.red, 'Already a number in reduction context');
33658 return this._forceRed(ctx);
33659};
33660
33661BN.prototype.redAdd = function redAdd(num) {
33662 assert(this.red, 'redAdd works only with red numbers');
33663 return this.red.add(this, num);
33664};
33665
33666BN.prototype.redIAdd = function redIAdd(num) {
33667 assert(this.red, 'redIAdd works only with red numbers');
33668 return this.red.iadd(this, num);
33669};
33670
33671BN.prototype.redSub = function redSub(num) {
33672 assert(this.red, 'redSub works only with red numbers');
33673 return this.red.sub(this, num);
33674};
33675
33676BN.prototype.redISub = function redISub(num) {
33677 assert(this.red, 'redISub works only with red numbers');
33678 return this.red.isub(this, num);
33679};
33680
33681BN.prototype.redShl = function redShl(num) {
33682 assert(this.red, 'redShl works only with red numbers');
33683 return this.red.shl(this, num);
33684};
33685
33686BN.prototype.redMul = function redMul(num) {
33687 assert(this.red, 'redMul works only with red numbers');
33688 this.red._verify2(this, num);
33689 return this.red.mul(this, num);
33690};
33691
33692BN.prototype.redIMul = function redIMul(num) {
33693 assert(this.red, 'redMul works only with red numbers');
33694 this.red._verify2(this, num);
33695 return this.red.imul(this, num);
33696};
33697
33698BN.prototype.redSqr = function redSqr() {
33699 assert(this.red, 'redSqr works only with red numbers');
33700 this.red._verify1(this);
33701 return this.red.sqr(this);
33702};
33703
33704BN.prototype.redISqr = function redISqr() {
33705 assert(this.red, 'redISqr works only with red numbers');
33706 this.red._verify1(this);
33707 return this.red.isqr(this);
33708};
33709
33710// Square root over p
33711BN.prototype.redSqrt = function redSqrt() {
33712 assert(this.red, 'redSqrt works only with red numbers');
33713 this.red._verify1(this);
33714 return this.red.sqrt(this);
33715};
33716
33717BN.prototype.redInvm = function redInvm() {
33718 assert(this.red, 'redInvm works only with red numbers');
33719 this.red._verify1(this);
33720 return this.red.invm(this);
33721};
33722
33723// Return negative clone of `this` % `red modulo`
33724BN.prototype.redNeg = function redNeg() {
33725 assert(this.red, 'redNeg works only with red numbers');
33726 this.red._verify1(this);
33727 return this.red.neg(this);
33728};
33729
33730BN.prototype.redPow = function redPow(num) {
33731 assert(this.red && !num.red, 'redPow(normalNum)');
33732 this.red._verify1(this);
33733 return this.red.pow(this, num);
33734};
33735
33736// Prime numbers with efficient reduction
33737var primes = {
33738 k256: null,
33739 p224: null,
33740 p192: null,
33741 p25519: null
33742};
33743
33744// Pseudo-Mersenne prime
33745function MPrime(name, p) {
33746 // P = 2 ^ N - K
33747 this.name = name;
33748 this.p = new BN(p, 16);
33749 this.n = this.p.bitLength();
33750 this.k = new BN(1).ishln(this.n).isub(this.p);
33751
33752 this.tmp = this._tmp();
33753}
33754
33755MPrime.prototype._tmp = function _tmp() {
33756 var tmp = new BN(null);
33757 tmp.words = new Array(Math.ceil(this.n / 13));
33758 return tmp;
33759};
33760
33761MPrime.prototype.ireduce = function ireduce(num) {
33762 // Assumes that `num` is less than `P^2`
33763 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
33764 var r = num;
33765 var rlen;
33766
33767 do {
33768 this.split(r, this.tmp);
33769 r = this.imulK(r);
33770 r = r.iadd(this.tmp);
33771 rlen = r.bitLength();
33772 } while (rlen > this.n);
33773
33774 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
33775 if (cmp === 0) {
33776 r.words[0] = 0;
33777 r.length = 1;
33778 } else if (cmp > 0) {
33779 r.isub(this.p);
33780 } else {
33781 r.strip();
33782 }
33783
33784 return r;
33785};
33786
33787MPrime.prototype.split = function split(input, out) {
33788 input.ishrn(this.n, 0, out);
33789};
33790
33791MPrime.prototype.imulK = function imulK(num) {
33792 return num.imul(this.k);
33793};
33794
33795function K256() {
33796 MPrime.call(
33797 this,
33798 'k256',
33799 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
33800}
33801inherits(K256, MPrime);
33802
33803K256.prototype.split = function split(input, output) {
33804 // 256 = 9 * 26 + 22
33805 var mask = 0x3fffff;
33806
33807 var outLen = Math.min(input.length, 9);
33808 for (var i = 0; i < outLen; i++)
33809 output.words[i] = input.words[i];
33810 output.length = outLen;
33811
33812 if (input.length <= 9) {
33813 input.words[0] = 0;
33814 input.length = 1;
33815 return;
33816 }
33817
33818 // Shift by 9 limbs
33819 var prev = input.words[9];
33820 output.words[output.length++] = prev & mask;
33821
33822 for (var i = 10; i < input.length; i++) {
33823 var next = input.words[i];
33824 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
33825 prev = next;
33826 }
33827 input.words[i - 10] = prev >>> 22;
33828 input.length -= 9;
33829};
33830
33831K256.prototype.imulK = function imulK(num) {
33832 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
33833 num.words[num.length] = 0;
33834 num.words[num.length + 1] = 0;
33835 num.length += 2;
33836
33837 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
33838 var hi;
33839 var lo = 0;
33840 for (var i = 0; i < num.length; i++) {
33841 var w = num.words[i];
33842 hi = w * 0x40;
33843 lo += w * 0x3d1;
33844 hi += (lo / 0x4000000) | 0;
33845 lo &= 0x3ffffff;
33846
33847 num.words[i] = lo;
33848
33849 lo = hi;
33850 }
33851
33852 // Fast length reduction
33853 if (num.words[num.length - 1] === 0) {
33854 num.length--;
33855 if (num.words[num.length - 1] === 0)
33856 num.length--;
33857 }
33858 return num;
33859};
33860
33861function P224() {
33862 MPrime.call(
33863 this,
33864 'p224',
33865 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
33866}
33867inherits(P224, MPrime);
33868
33869function P192() {
33870 MPrime.call(
33871 this,
33872 'p192',
33873 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
33874}
33875inherits(P192, MPrime);
33876
33877function P25519() {
33878 // 2 ^ 255 - 19
33879 MPrime.call(
33880 this,
33881 '25519',
33882 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
33883}
33884inherits(P25519, MPrime);
33885
33886P25519.prototype.imulK = function imulK(num) {
33887 // K = 0x13
33888 var carry = 0;
33889 for (var i = 0; i < num.length; i++) {
33890 var hi = num.words[i] * 0x13 + carry;
33891 var lo = hi & 0x3ffffff;
33892 hi >>>= 26;
33893
33894 num.words[i] = lo;
33895 carry = hi;
33896 }
33897 if (carry !== 0)
33898 num.words[num.length++] = carry;
33899 return num;
33900};
33901
33902// Exported mostly for testing purposes, use plain name instead
33903BN._prime = function prime(name) {
33904 // Cached version of prime
33905 if (primes[name])
33906 return primes[name];
33907
33908 var prime;
33909 if (name === 'k256')
33910 prime = new K256();
33911 else if (name === 'p224')
33912 prime = new P224();
33913 else if (name === 'p192')
33914 prime = new P192();
33915 else if (name === 'p25519')
33916 prime = new P25519();
33917 else
33918 throw new Error('Unknown prime ' + name);
33919 primes[name] = prime;
33920
33921 return prime;
33922};
33923
33924//
33925// Base reduction engine
33926//
33927function Red(m) {
33928 if (typeof m === 'string') {
33929 var prime = BN._prime(m);
33930 this.m = prime.p;
33931 this.prime = prime;
33932 } else {
33933 this.m = m;
33934 this.prime = null;
33935 }
33936}
33937
33938Red.prototype._verify1 = function _verify1(a) {
33939 assert(!a.sign, 'red works only with positives');
33940 assert(a.red, 'red works only with red numbers');
33941};
33942
33943Red.prototype._verify2 = function _verify2(a, b) {
33944 assert(!a.sign && !b.sign, 'red works only with positives');
33945 assert(a.red && a.red === b.red,
33946 'red works only with red numbers');
33947};
33948
33949Red.prototype.imod = function imod(a) {
33950 if (this.prime)
33951 return this.prime.ireduce(a)._forceRed(this);
33952 return a.mod(this.m)._forceRed(this);
33953};
33954
33955Red.prototype.neg = function neg(a) {
33956 var r = a.clone();
33957 r.sign = !r.sign;
33958 return r.iadd(this.m)._forceRed(this);
33959};
33960
33961Red.prototype.add = function add(a, b) {
33962 this._verify2(a, b);
33963
33964 var res = a.add(b);
33965 if (res.cmp(this.m) >= 0)
33966 res.isub(this.m);
33967 return res._forceRed(this);
33968};
33969
33970Red.prototype.iadd = function iadd(a, b) {
33971 this._verify2(a, b);
33972
33973 var res = a.iadd(b);
33974 if (res.cmp(this.m) >= 0)
33975 res.isub(this.m);
33976 return res;
33977};
33978
33979Red.prototype.sub = function sub(a, b) {
33980 this._verify2(a, b);
33981
33982 var res = a.sub(b);
33983 if (res.cmpn(0) < 0)
33984 res.iadd(this.m);
33985 return res._forceRed(this);
33986};
33987
33988Red.prototype.isub = function isub(a, b) {
33989 this._verify2(a, b);
33990
33991 var res = a.isub(b);
33992 if (res.cmpn(0) < 0)
33993 res.iadd(this.m);
33994 return res;
33995};
33996
33997Red.prototype.shl = function shl(a, num) {
33998 this._verify1(a);
33999 return this.imod(a.shln(num));
34000};
34001
34002Red.prototype.imul = function imul(a, b) {
34003 this._verify2(a, b);
34004 return this.imod(a.imul(b));
34005};
34006
34007Red.prototype.mul = function mul(a, b) {
34008 this._verify2(a, b);
34009 return this.imod(a.mul(b));
34010};
34011
34012Red.prototype.isqr = function isqr(a) {
34013 return this.imul(a, a);
34014};
34015
34016Red.prototype.sqr = function sqr(a) {
34017 return this.mul(a, a);
34018};
34019
34020Red.prototype.sqrt = function sqrt(a) {
34021 if (a.cmpn(0) === 0)
34022 return a.clone();
34023
34024 var mod3 = this.m.andln(3);
34025 assert(mod3 % 2 === 1);
34026
34027 // Fast case
34028 if (mod3 === 3) {
34029 var pow = this.m.add(new BN(1)).ishrn(2);
34030 var r = this.pow(a, pow);
34031 return r;
34032 }
34033
34034 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
34035 //
34036 // Find Q and S, that Q * 2 ^ S = (P - 1)
34037 var q = this.m.subn(1);
34038 var s = 0;
34039 while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
34040 s++;
34041 q.ishrn(1);
34042 }
34043 assert(q.cmpn(0) !== 0);
34044
34045 var one = new BN(1).toRed(this);
34046 var nOne = one.redNeg();
34047
34048 // Find quadratic non-residue
34049 // NOTE: Max is such because of generalized Riemann hypothesis.
34050 var lpow = this.m.subn(1).ishrn(1);
34051 var z = this.m.bitLength();
34052 z = new BN(2 * z * z).toRed(this);
34053 while (this.pow(z, lpow).cmp(nOne) !== 0)
34054 z.redIAdd(nOne);
34055
34056 var c = this.pow(z, q);
34057 var r = this.pow(a, q.addn(1).ishrn(1));
34058 var t = this.pow(a, q);
34059 var m = s;
34060 while (t.cmp(one) !== 0) {
34061 var tmp = t;
34062 for (var i = 0; tmp.cmp(one) !== 0; i++)
34063 tmp = tmp.redSqr();
34064 assert(i < m);
34065 var b = this.pow(c, new BN(1).ishln(m - i - 1));
34066
34067 r = r.redMul(b);
34068 c = b.redSqr();
34069 t = t.redMul(c);
34070 m = i;
34071 }
34072
34073 return r;
34074};
34075
34076Red.prototype.invm = function invm(a) {
34077 var inv = a._invmp(this.m);
34078 if (inv.sign) {
34079 inv.sign = false;
34080 return this.imod(inv).redNeg();
34081 } else {
34082 return this.imod(inv);
34083 }
34084};
34085
34086Red.prototype.pow = function pow(a, num) {
34087 var w = [];
34088
34089 if (num.cmpn(0) === 0)
34090 return new BN(1);
34091
34092 var q = num.clone();
34093
34094 while (q.cmpn(0) !== 0) {
34095 w.push(q.andln(1));
34096 q.ishrn(1);
34097 }
34098
34099 // Skip leading zeroes
34100 var res = a;
34101 for (var i = 0; i < w.length; i++, res = this.sqr(res))
34102 if (w[i] !== 0)
34103 break;
34104
34105 if (++i < w.length) {
34106 for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
34107 if (w[i] === 0)
34108 continue;
34109 res = this.mul(res, q);
34110 }
34111 }
34112
34113 return res;
34114};
34115
34116Red.prototype.convertTo = function convertTo(num) {
34117 var r = num.mod(this.m);
34118 if (r === num)
34119 return r.clone();
34120 else
34121 return r;
34122};
34123
34124Red.prototype.convertFrom = function convertFrom(num) {
34125 var res = num.clone();
34126 res.red = null;
34127 return res;
34128};
34129
34130//
34131// Montgomery method engine
34132//
34133
34134BN.mont = function mont(num) {
34135 return new Mont(num);
34136};
34137
34138function Mont(m) {
34139 Red.call(this, m);
34140
34141 this.shift = this.m.bitLength();
34142 if (this.shift % 26 !== 0)
34143 this.shift += 26 - (this.shift % 26);
34144 this.r = new BN(1).ishln(this.shift);
34145 this.r2 = this.imod(this.r.sqr());
34146 this.rinv = this.r._invmp(this.m);
34147
34148 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
34149 this.minv.sign = true;
34150 this.minv = this.minv.mod(this.r);
34151}
34152inherits(Mont, Red);
34153
34154Mont.prototype.convertTo = function convertTo(num) {
34155 return this.imod(num.shln(this.shift));
34156};
34157
34158Mont.prototype.convertFrom = function convertFrom(num) {
34159 var r = this.imod(num.mul(this.rinv));
34160 r.red = null;
34161 return r;
34162};
34163
34164Mont.prototype.imul = function imul(a, b) {
34165 if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
34166 a.words[0] = 0;
34167 a.length = 1;
34168 return a;
34169 }
34170
34171 var t = a.imul(b);
34172 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
34173 var u = t.isub(c).ishrn(this.shift);
34174 var res = u;
34175 if (u.cmp(this.m) >= 0)
34176 res = u.isub(this.m);
34177 else if (u.cmpn(0) < 0)
34178 res = u.iadd(this.m);
34179
34180 return res._forceRed(this);
34181};
34182
34183Mont.prototype.mul = function mul(a, b) {
34184 if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
34185 return new BN(0)._forceRed(this);
34186
34187 var t = a.mul(b);
34188 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
34189 var u = t.isub(c).ishrn(this.shift);
34190 var res = u;
34191 if (u.cmp(this.m) >= 0)
34192 res = u.isub(this.m);
34193 else if (u.cmpn(0) < 0)
34194 res = u.iadd(this.m);
34195
34196 return res._forceRed(this);
34197};
34198
34199Mont.prototype.invm = function invm(a) {
34200 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
34201 var res = this.imod(a._invmp(this.m).mul(this.r2));
34202 return res._forceRed(this);
34203};
34204
34205})(typeof module === 'undefined' || module, this);
34206}, {}],205: [function (exports, require, module, global) {'use strict'
34207exports['1.3.132.0.10'] = 'secp256k1'
34208
34209exports['1.3.132.0.33'] = 'p224'
34210
34211exports['1.2.840.10045.3.1.1'] = 'p192'
34212
34213exports['1.2.840.10045.3.1.7'] = 'p256'
34214}, {}],206: [function (exports, require, module, global) {'use strict';
34215
34216var elliptic = exports;
34217
34218elliptic.version = require('../package.json').version;
34219elliptic.utils = require('./elliptic/utils');
34220elliptic.rand = require('brorand');
34221elliptic.hmacDRBG = require('./elliptic/hmac-drbg');
34222elliptic.curve = require('./elliptic/curve');
34223elliptic.curves = require('./elliptic/curves');
34224
34225// Protocols
34226elliptic.ec = require('./elliptic/ec');
34227}, {"../package.json":207,"./elliptic/utils":208,"brorand":209,"./elliptic/hmac-drbg":210,"./elliptic/curve":217,"./elliptic/curves":222,"./elliptic/ec":224}],207: [function (exports, require, module, global) {module.exports = {
34228 "name": "elliptic",
34229 "version": "3.1.0",
34230 "description": "EC cryptography",
34231 "main": "lib/elliptic.js",
34232 "scripts": {
34233 "test": "make lint && mocha --reporter=spec test/*-test.js"
34234 },
34235 "repository": {
34236 "type": "git",
34237 "url": "git+ssh://git@github.com/indutny/elliptic.git"
34238 },
34239 "keywords": [
34240 "EC",
34241 "Elliptic",
34242 "curve",
34243 "Cryptography"
34244 ],
34245 "author": {
34246 "name": "Fedor Indutny",
34247 "email": "fedor@indutny.com"
34248 },
34249 "license": "MIT",
34250 "bugs": {
34251 "url": "https://github.com/indutny/elliptic/issues"
34252 },
34253 "homepage": "https://github.com/indutny/elliptic",
34254 "devDependencies": {
34255 "browserify": "^3.44.2",
34256 "jscs": "^1.11.3",
34257 "jshint": "^2.6.0",
34258 "mocha": "^2.1.0",
34259 "uglify-js": "^2.4.13"
34260 },
34261 "dependencies": {
34262 "bn.js": "^2.0.3",
34263 "brorand": "^1.0.1",
34264 "hash.js": "^1.0.0",
34265 "inherits": "^2.0.1"
34266 },
34267 "gitHead": "d86cd2a8178f7e7cecbd6dd92eea084e2ab44c13",
34268 "_id": "elliptic@3.1.0",
34269 "_shasum": "c21682ef762769b56a74201609105da11d5f60cc",
34270 "_from": "elliptic@>=3.0.0 <4.0.0",
34271 "_npmVersion": "2.11.0",
34272 "_nodeVersion": "2.2.1",
34273 "_npmUser": {
34274 "name": "indutny",
34275 "email": "fedor@indutny.com"
34276 },
34277 "maintainers": [
34278 {
34279 "name": "indutny",
34280 "email": "fedor@indutny.com"
34281 }
34282 ],
34283 "dist": {
34284 "shasum": "c21682ef762769b56a74201609105da11d5f60cc",
34285 "tarball": "http://registry.npmjs.org/elliptic/-/elliptic-3.1.0.tgz"
34286 },
34287 "directories": {},
34288 "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-3.1.0.tgz",
34289 "readme": "ERROR: No README data found!"
34290}
34291}, {}],208: [function (exports, require, module, global) {'use strict';
34292
34293var utils = exports;
34294
34295utils.assert = function assert(val, msg) {
34296 if (!val)
34297 throw new Error(msg || 'Assertion failed');
34298};
34299
34300function toArray(msg, enc) {
34301 if (Array.isArray(msg))
34302 return msg.slice();
34303 if (!msg)
34304 return [];
34305 var res = [];
34306 if (typeof msg !== 'string') {
34307 for (var i = 0; i < msg.length; i++)
34308 res[i] = msg[i] | 0;
34309 return res;
34310 }
34311 if (!enc) {
34312 for (var i = 0; i < msg.length; i++) {
34313 var c = msg.charCodeAt(i);
34314 var hi = c >> 8;
34315 var lo = c & 0xff;
34316 if (hi)
34317 res.push(hi, lo);
34318 else
34319 res.push(lo);
34320 }
34321 } else if (enc === 'hex') {
34322 msg = msg.replace(/[^a-z0-9]+/ig, '');
34323 if (msg.length % 2 !== 0)
34324 msg = '0' + msg;
34325 for (var i = 0; i < msg.length; i += 2)
34326 res.push(parseInt(msg[i] + msg[i + 1], 16));
34327 }
34328 return res;
34329}
34330utils.toArray = toArray;
34331
34332function zero2(word) {
34333 if (word.length === 1)
34334 return '0' + word;
34335 else
34336 return word;
34337}
34338utils.zero2 = zero2;
34339
34340function toHex(msg) {
34341 var res = '';
34342 for (var i = 0; i < msg.length; i++)
34343 res += zero2(msg[i].toString(16));
34344 return res;
34345}
34346utils.toHex = toHex;
34347
34348utils.encode = function encode(arr, enc) {
34349 if (enc === 'hex')
34350 return toHex(arr);
34351 else
34352 return arr;
34353};
34354
34355// Represent num in a w-NAF form
34356function getNAF(num, w) {
34357 var naf = [];
34358 var ws = 1 << (w + 1);
34359 var k = num.clone();
34360 while (k.cmpn(1) >= 0) {
34361 var z;
34362 if (k.isOdd()) {
34363 var mod = k.andln(ws - 1);
34364 if (mod > (ws >> 1) - 1)
34365 z = (ws >> 1) - mod;
34366 else
34367 z = mod;
34368 k.isubn(z);
34369 } else {
34370 z = 0;
34371 }
34372 naf.push(z);
34373
34374 // Optimization, shift by word if possible
34375 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
34376 for (var i = 1; i < shift; i++)
34377 naf.push(0);
34378 k.ishrn(shift);
34379 }
34380
34381 return naf;
34382}
34383utils.getNAF = getNAF;
34384
34385// Represent k1, k2 in a Joint Sparse Form
34386function getJSF(k1, k2) {
34387 var jsf = [
34388 [],
34389 []
34390 ];
34391
34392 k1 = k1.clone();
34393 k2 = k2.clone();
34394 var d1 = 0;
34395 var d2 = 0;
34396 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
34397
34398 // First phase
34399 var m14 = (k1.andln(3) + d1) & 3;
34400 var m24 = (k2.andln(3) + d2) & 3;
34401 if (m14 === 3)
34402 m14 = -1;
34403 if (m24 === 3)
34404 m24 = -1;
34405 var u1;
34406 if ((m14 & 1) === 0) {
34407 u1 = 0;
34408 } else {
34409 var m8 = (k1.andln(7) + d1) & 7;
34410 if ((m8 === 3 || m8 === 5) && m24 === 2)
34411 u1 = -m14;
34412 else
34413 u1 = m14;
34414 }
34415 jsf[0].push(u1);
34416
34417 var u2;
34418 if ((m24 & 1) === 0) {
34419 u2 = 0;
34420 } else {
34421 var m8 = (k2.andln(7) + d2) & 7;
34422 if ((m8 === 3 || m8 === 5) && m14 === 2)
34423 u2 = -m24;
34424 else
34425 u2 = m24;
34426 }
34427 jsf[1].push(u2);
34428
34429 // Second phase
34430 if (2 * d1 === u1 + 1)
34431 d1 = 1 - d1;
34432 if (2 * d2 === u2 + 1)
34433 d2 = 1 - d2;
34434 k1.ishrn(1);
34435 k2.ishrn(1);
34436 }
34437
34438 return jsf;
34439}
34440utils.getJSF = getJSF;
34441}, {}],209: [function (exports, require, module, global) {var r;
34442
34443module.exports = function rand(len) {
34444 if (!r)
34445 r = new Rand(null);
34446
34447 return r.generate(len);
34448};
34449
34450function Rand(rand) {
34451 this.rand = rand;
34452}
34453module.exports.Rand = Rand;
34454
34455Rand.prototype.generate = function generate(len) {
34456 return this._rand(len);
34457};
34458
34459if (typeof window === 'object') {
34460 if (window.crypto && window.crypto.getRandomValues) {
34461 // Modern browsers
34462 Rand.prototype._rand = function _rand(n) {
34463 var arr = new Uint8Array(n);
34464 window.crypto.getRandomValues(arr);
34465 return arr;
34466 };
34467 } else if (window.msCrypto && window.msCrypto.getRandomValues) {
34468 // IE
34469 Rand.prototype._rand = function _rand(n) {
34470 var arr = new Uint8Array(n);
34471 window.msCrypto.getRandomValues(arr);
34472 return arr;
34473 };
34474 } else {
34475 // Old junk
34476 Rand.prototype._rand = function() {
34477 throw new Error('Not implemented yet');
34478 };
34479 }
34480} else {
34481 // Node.js or Web worker
34482 try {
34483 var crypto = require('cry' + 'pto');
34484
34485 Rand.prototype._rand = function _rand(n) {
34486 return crypto.randomBytes(n);
34487 };
34488 } catch (e) {
34489 // Emulate crypto API using randy
34490 Rand.prototype._rand = function _rand(n) {
34491 var res = new Uint8Array(n);
34492 for (var i = 0; i < res.length; i++)
34493 res[i] = this.rand.getByte();
34494 return res;
34495 };
34496 }
34497}
34498}, {}],210: [function (exports, require, module, global) {'use strict';
34499
34500var hash = require('hash.js');
34501var elliptic = require('../elliptic');
34502var utils = elliptic.utils;
34503var assert = utils.assert;
34504
34505function HmacDRBG(options) {
34506 if (!(this instanceof HmacDRBG))
34507 return new HmacDRBG(options);
34508 this.hash = options.hash;
34509 this.predResist = !!options.predResist;
34510
34511 this.outLen = this.hash.outSize;
34512 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
34513
34514 this.reseed = null;
34515 this.reseedInterval = null;
34516 this.K = null;
34517 this.V = null;
34518
34519 var entropy = utils.toArray(options.entropy, options.entropyEnc);
34520 var nonce = utils.toArray(options.nonce, options.nonceEnc);
34521 var pers = utils.toArray(options.pers, options.persEnc);
34522 assert(entropy.length >= (this.minEntropy / 8),
34523 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
34524 this._init(entropy, nonce, pers);
34525}
34526module.exports = HmacDRBG;
34527
34528HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
34529 var seed = entropy.concat(nonce).concat(pers);
34530
34531 this.K = new Array(this.outLen / 8);
34532 this.V = new Array(this.outLen / 8);
34533 for (var i = 0; i < this.V.length; i++) {
34534 this.K[i] = 0x00;
34535 this.V[i] = 0x01;
34536 }
34537
34538 this._update(seed);
34539 this.reseed = 1;
34540 this.reseedInterval = 0x1000000000000; // 2^48
34541};
34542
34543HmacDRBG.prototype._hmac = function hmac() {
34544 return new hash.hmac(this.hash, this.K);
34545};
34546
34547HmacDRBG.prototype._update = function update(seed) {
34548 var kmac = this._hmac()
34549 .update(this.V)
34550 .update([ 0x00 ]);
34551 if (seed)
34552 kmac = kmac.update(seed);
34553 this.K = kmac.digest();
34554 this.V = this._hmac().update(this.V).digest();
34555 if (!seed)
34556 return;
34557
34558 this.K = this._hmac()
34559 .update(this.V)
34560 .update([ 0x01 ])
34561 .update(seed)
34562 .digest();
34563 this.V = this._hmac().update(this.V).digest();
34564};
34565
34566HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
34567 // Optional entropy enc
34568 if (typeof entropyEnc !== 'string') {
34569 addEnc = add;
34570 add = entropyEnc;
34571 entropyEnc = null;
34572 }
34573
34574 entropy = utils.toBuffer(entropy, entropyEnc);
34575 add = utils.toBuffer(add, addEnc);
34576
34577 assert(entropy.length >= (this.minEntropy / 8),
34578 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
34579
34580 this._update(entropy.concat(add || []));
34581 this.reseed = 1;
34582};
34583
34584HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
34585 if (this.reseed > this.reseedInterval)
34586 throw new Error('Reseed is required');
34587
34588 // Optional encoding
34589 if (typeof enc !== 'string') {
34590 addEnc = add;
34591 add = enc;
34592 enc = null;
34593 }
34594
34595 // Optional additional data
34596 if (add) {
34597 add = utils.toArray(add, addEnc);
34598 this._update(add);
34599 }
34600
34601 var temp = [];
34602 while (temp.length < len) {
34603 this.V = this._hmac().update(this.V).digest();
34604 temp = temp.concat(this.V);
34605 }
34606
34607 var res = temp.slice(0, len);
34608 this._update(add);
34609 this.reseed++;
34610 return utils.encode(res, enc);
34611};
34612}, {"hash.js":211,"../elliptic":206}],211: [function (exports, require, module, global) {var hash = exports;
34613
34614hash.utils = require('./hash/utils');
34615hash.common = require('./hash/common');
34616hash.sha = require('./hash/sha');
34617hash.ripemd = require('./hash/ripemd');
34618hash.hmac = require('./hash/hmac');
34619
34620// Proxy hash functions to the main object
34621hash.sha1 = hash.sha.sha1;
34622hash.sha256 = hash.sha.sha256;
34623hash.sha224 = hash.sha.sha224;
34624hash.sha384 = hash.sha.sha384;
34625hash.sha512 = hash.sha.sha512;
34626hash.ripemd160 = hash.ripemd.ripemd160;
34627}, {"./hash/utils":212,"./hash/common":213,"./hash/sha":214,"./hash/ripemd":215,"./hash/hmac":216}],212: [function (exports, require, module, global) {var utils = exports;
34628var inherits = require('inherits');
34629
34630function toArray(msg, enc) {
34631 if (Array.isArray(msg))
34632 return msg.slice();
34633 if (!msg)
34634 return [];
34635 var res = [];
34636 if (typeof msg === 'string') {
34637 if (!enc) {
34638 for (var i = 0; i < msg.length; i++) {
34639 var c = msg.charCodeAt(i);
34640 var hi = c >> 8;
34641 var lo = c & 0xff;
34642 if (hi)
34643 res.push(hi, lo);
34644 else
34645 res.push(lo);
34646 }
34647 } else if (enc === 'hex') {
34648 msg = msg.replace(/[^a-z0-9]+/ig, '');
34649 if (msg.length % 2 !== 0)
34650 msg = '0' + msg;
34651 for (var i = 0; i < msg.length; i += 2)
34652 res.push(parseInt(msg[i] + msg[i + 1], 16));
34653 }
34654 } else {
34655 for (var i = 0; i < msg.length; i++)
34656 res[i] = msg[i] | 0;
34657 }
34658 return res;
34659}
34660utils.toArray = toArray;
34661
34662function toHex(msg) {
34663 var res = '';
34664 for (var i = 0; i < msg.length; i++)
34665 res += zero2(msg[i].toString(16));
34666 return res;
34667}
34668utils.toHex = toHex;
34669
34670function htonl(w) {
34671 var res = (w >>> 24) |
34672 ((w >>> 8) & 0xff00) |
34673 ((w << 8) & 0xff0000) |
34674 ((w & 0xff) << 24);
34675 return res >>> 0;
34676}
34677utils.htonl = htonl;
34678
34679function toHex32(msg, endian) {
34680 var res = '';
34681 for (var i = 0; i < msg.length; i++) {
34682 var w = msg[i];
34683 if (endian === 'little')
34684 w = htonl(w);
34685 res += zero8(w.toString(16));
34686 }
34687 return res;
34688}
34689utils.toHex32 = toHex32;
34690
34691function zero2(word) {
34692 if (word.length === 1)
34693 return '0' + word;
34694 else
34695 return word;
34696}
34697utils.zero2 = zero2;
34698
34699function zero8(word) {
34700 if (word.length === 7)
34701 return '0' + word;
34702 else if (word.length === 6)
34703 return '00' + word;
34704 else if (word.length === 5)
34705 return '000' + word;
34706 else if (word.length === 4)
34707 return '0000' + word;
34708 else if (word.length === 3)
34709 return '00000' + word;
34710 else if (word.length === 2)
34711 return '000000' + word;
34712 else if (word.length === 1)
34713 return '0000000' + word;
34714 else
34715 return word;
34716}
34717utils.zero8 = zero8;
34718
34719function join32(msg, start, end, endian) {
34720 var len = end - start;
34721 assert(len % 4 === 0);
34722 var res = new Array(len / 4);
34723 for (var i = 0, k = start; i < res.length; i++, k += 4) {
34724 var w;
34725 if (endian === 'big')
34726 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
34727 else
34728 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
34729 res[i] = w >>> 0;
34730 }
34731 return res;
34732}
34733utils.join32 = join32;
34734
34735function split32(msg, endian) {
34736 var res = new Array(msg.length * 4);
34737 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
34738 var m = msg[i];
34739 if (endian === 'big') {
34740 res[k] = m >>> 24;
34741 res[k + 1] = (m >>> 16) & 0xff;
34742 res[k + 2] = (m >>> 8) & 0xff;
34743 res[k + 3] = m & 0xff;
34744 } else {
34745 res[k + 3] = m >>> 24;
34746 res[k + 2] = (m >>> 16) & 0xff;
34747 res[k + 1] = (m >>> 8) & 0xff;
34748 res[k] = m & 0xff;
34749 }
34750 }
34751 return res;
34752}
34753utils.split32 = split32;
34754
34755function rotr32(w, b) {
34756 return (w >>> b) | (w << (32 - b));
34757}
34758utils.rotr32 = rotr32;
34759
34760function rotl32(w, b) {
34761 return (w << b) | (w >>> (32 - b));
34762}
34763utils.rotl32 = rotl32;
34764
34765function sum32(a, b) {
34766 return (a + b) >>> 0;
34767}
34768utils.sum32 = sum32;
34769
34770function sum32_3(a, b, c) {
34771 return (a + b + c) >>> 0;
34772}
34773utils.sum32_3 = sum32_3;
34774
34775function sum32_4(a, b, c, d) {
34776 return (a + b + c + d) >>> 0;
34777}
34778utils.sum32_4 = sum32_4;
34779
34780function sum32_5(a, b, c, d, e) {
34781 return (a + b + c + d + e) >>> 0;
34782}
34783utils.sum32_5 = sum32_5;
34784
34785function assert(cond, msg) {
34786 if (!cond)
34787 throw new Error(msg || 'Assertion failed');
34788}
34789utils.assert = assert;
34790
34791utils.inherits = inherits;
34792
34793function sum64(buf, pos, ah, al) {
34794 var bh = buf[pos];
34795 var bl = buf[pos + 1];
34796
34797 var lo = (al + bl) >>> 0;
34798 var hi = (lo < al ? 1 : 0) + ah + bh;
34799 buf[pos] = hi >>> 0;
34800 buf[pos + 1] = lo;
34801}
34802exports.sum64 = sum64;
34803
34804function sum64_hi(ah, al, bh, bl) {
34805 var lo = (al + bl) >>> 0;
34806 var hi = (lo < al ? 1 : 0) + ah + bh;
34807 return hi >>> 0;
34808};
34809exports.sum64_hi = sum64_hi;
34810
34811function sum64_lo(ah, al, bh, bl) {
34812 var lo = al + bl;
34813 return lo >>> 0;
34814};
34815exports.sum64_lo = sum64_lo;
34816
34817function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
34818 var carry = 0;
34819 var lo = al;
34820 lo = (lo + bl) >>> 0;
34821 carry += lo < al ? 1 : 0;
34822 lo = (lo + cl) >>> 0;
34823 carry += lo < cl ? 1 : 0;
34824 lo = (lo + dl) >>> 0;
34825 carry += lo < dl ? 1 : 0;
34826
34827 var hi = ah + bh + ch + dh + carry;
34828 return hi >>> 0;
34829};
34830exports.sum64_4_hi = sum64_4_hi;
34831
34832function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
34833 var lo = al + bl + cl + dl;
34834 return lo >>> 0;
34835};
34836exports.sum64_4_lo = sum64_4_lo;
34837
34838function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
34839 var carry = 0;
34840 var lo = al;
34841 lo = (lo + bl) >>> 0;
34842 carry += lo < al ? 1 : 0;
34843 lo = (lo + cl) >>> 0;
34844 carry += lo < cl ? 1 : 0;
34845 lo = (lo + dl) >>> 0;
34846 carry += lo < dl ? 1 : 0;
34847 lo = (lo + el) >>> 0;
34848 carry += lo < el ? 1 : 0;
34849
34850 var hi = ah + bh + ch + dh + eh + carry;
34851 return hi >>> 0;
34852};
34853exports.sum64_5_hi = sum64_5_hi;
34854
34855function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
34856 var lo = al + bl + cl + dl + el;
34857
34858 return lo >>> 0;
34859};
34860exports.sum64_5_lo = sum64_5_lo;
34861
34862function rotr64_hi(ah, al, num) {
34863 var r = (al << (32 - num)) | (ah >>> num);
34864 return r >>> 0;
34865};
34866exports.rotr64_hi = rotr64_hi;
34867
34868function rotr64_lo(ah, al, num) {
34869 var r = (ah << (32 - num)) | (al >>> num);
34870 return r >>> 0;
34871};
34872exports.rotr64_lo = rotr64_lo;
34873
34874function shr64_hi(ah, al, num) {
34875 return ah >>> num;
34876};
34877exports.shr64_hi = shr64_hi;
34878
34879function shr64_lo(ah, al, num) {
34880 var r = (ah << (32 - num)) | (al >>> num);
34881 return r >>> 0;
34882};
34883exports.shr64_lo = shr64_lo;
34884}, {"inherits":149}],213: [function (exports, require, module, global) {var hash = require('../hash');
34885var utils = hash.utils;
34886var assert = utils.assert;
34887
34888function BlockHash() {
34889 this.pending = null;
34890 this.pendingTotal = 0;
34891 this.blockSize = this.constructor.blockSize;
34892 this.outSize = this.constructor.outSize;
34893 this.hmacStrength = this.constructor.hmacStrength;
34894 this.padLength = this.constructor.padLength / 8;
34895 this.endian = 'big';
34896
34897 this._delta8 = this.blockSize / 8;
34898 this._delta32 = this.blockSize / 32;
34899}
34900exports.BlockHash = BlockHash;
34901
34902BlockHash.prototype.update = function update(msg, enc) {
34903 // Convert message to array, pad it, and join into 32bit blocks
34904 msg = utils.toArray(msg, enc);
34905 if (!this.pending)
34906 this.pending = msg;
34907 else
34908 this.pending = this.pending.concat(msg);
34909 this.pendingTotal += msg.length;
34910
34911 // Enough data, try updating
34912 if (this.pending.length >= this._delta8) {
34913 msg = this.pending;
34914
34915 // Process pending data in blocks
34916 var r = msg.length % this._delta8;
34917 this.pending = msg.slice(msg.length - r, msg.length);
34918 if (this.pending.length === 0)
34919 this.pending = null;
34920
34921 msg = utils.join32(msg, 0, msg.length - r, this.endian);
34922 for (var i = 0; i < msg.length; i += this._delta32)
34923 this._update(msg, i, i + this._delta32);
34924 }
34925
34926 return this;
34927};
34928
34929BlockHash.prototype.digest = function digest(enc) {
34930 this.update(this._pad());
34931 assert(this.pending === null);
34932
34933 return this._digest(enc);
34934};
34935
34936BlockHash.prototype._pad = function pad() {
34937 var len = this.pendingTotal;
34938 var bytes = this._delta8;
34939 var k = bytes - ((len + this.padLength) % bytes);
34940 var res = new Array(k + this.padLength);
34941 res[0] = 0x80;
34942 for (var i = 1; i < k; i++)
34943 res[i] = 0;
34944
34945 // Append length
34946 len <<= 3;
34947 if (this.endian === 'big') {
34948 for (var t = 8; t < this.padLength; t++)
34949 res[i++] = 0;
34950
34951 res[i++] = 0;
34952 res[i++] = 0;
34953 res[i++] = 0;
34954 res[i++] = 0;
34955 res[i++] = (len >>> 24) & 0xff;
34956 res[i++] = (len >>> 16) & 0xff;
34957 res[i++] = (len >>> 8) & 0xff;
34958 res[i++] = len & 0xff;
34959 } else {
34960 res[i++] = len & 0xff;
34961 res[i++] = (len >>> 8) & 0xff;
34962 res[i++] = (len >>> 16) & 0xff;
34963 res[i++] = (len >>> 24) & 0xff;
34964 res[i++] = 0;
34965 res[i++] = 0;
34966 res[i++] = 0;
34967 res[i++] = 0;
34968
34969 for (var t = 8; t < this.padLength; t++)
34970 res[i++] = 0;
34971 }
34972
34973 return res;
34974};
34975}, {"../hash":211}],214: [function (exports, require, module, global) {var hash = require('../hash');
34976var utils = hash.utils;
34977var assert = utils.assert;
34978
34979var rotr32 = utils.rotr32;
34980var rotl32 = utils.rotl32;
34981var sum32 = utils.sum32;
34982var sum32_4 = utils.sum32_4;
34983var sum32_5 = utils.sum32_5;
34984var rotr64_hi = utils.rotr64_hi;
34985var rotr64_lo = utils.rotr64_lo;
34986var shr64_hi = utils.shr64_hi;
34987var shr64_lo = utils.shr64_lo;
34988var sum64 = utils.sum64;
34989var sum64_hi = utils.sum64_hi;
34990var sum64_lo = utils.sum64_lo;
34991var sum64_4_hi = utils.sum64_4_hi;
34992var sum64_4_lo = utils.sum64_4_lo;
34993var sum64_5_hi = utils.sum64_5_hi;
34994var sum64_5_lo = utils.sum64_5_lo;
34995var BlockHash = hash.common.BlockHash;
34996
34997var sha256_K = [
34998 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
34999 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
35000 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
35001 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
35002 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
35003 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
35004 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
35005 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
35006 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
35007 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
35008 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
35009 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
35010 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
35011 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
35012 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
35013 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
35014];
35015
35016var sha512_K = [
35017 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
35018 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
35019 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
35020 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
35021 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
35022 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
35023 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
35024 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
35025 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
35026 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
35027 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
35028 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
35029 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
35030 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
35031 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
35032 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
35033 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
35034 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
35035 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
35036 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
35037 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
35038 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
35039 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
35040 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
35041 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
35042 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
35043 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
35044 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
35045 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
35046 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
35047 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
35048 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
35049 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
35050 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
35051 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
35052 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
35053 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
35054 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
35055 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
35056 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
35057];
35058
35059var sha1_K = [
35060 0x5A827999, 0x6ED9EBA1,
35061 0x8F1BBCDC, 0xCA62C1D6
35062];
35063
35064function SHA256() {
35065 if (!(this instanceof SHA256))
35066 return new SHA256();
35067
35068 BlockHash.call(this);
35069 this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
35070 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ];
35071 this.k = sha256_K;
35072 this.W = new Array(64);
35073}
35074utils.inherits(SHA256, BlockHash);
35075exports.sha256 = SHA256;
35076
35077SHA256.blockSize = 512;
35078SHA256.outSize = 256;
35079SHA256.hmacStrength = 192;
35080SHA256.padLength = 64;
35081
35082SHA256.prototype._update = function _update(msg, start) {
35083 var W = this.W;
35084
35085 for (var i = 0; i < 16; i++)
35086 W[i] = msg[start + i];
35087 for (; i < W.length; i++)
35088 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
35089
35090 var a = this.h[0];
35091 var b = this.h[1];
35092 var c = this.h[2];
35093 var d = this.h[3];
35094 var e = this.h[4];
35095 var f = this.h[5];
35096 var g = this.h[6];
35097 var h = this.h[7];
35098
35099 assert(this.k.length === W.length);
35100 for (var i = 0; i < W.length; i++) {
35101 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
35102 var T2 = sum32(s0_256(a), maj32(a, b, c));
35103 h = g;
35104 g = f;
35105 f = e;
35106 e = sum32(d, T1);
35107 d = c;
35108 c = b;
35109 b = a;
35110 a = sum32(T1, T2);
35111 }
35112
35113 this.h[0] = sum32(this.h[0], a);
35114 this.h[1] = sum32(this.h[1], b);
35115 this.h[2] = sum32(this.h[2], c);
35116 this.h[3] = sum32(this.h[3], d);
35117 this.h[4] = sum32(this.h[4], e);
35118 this.h[5] = sum32(this.h[5], f);
35119 this.h[6] = sum32(this.h[6], g);
35120 this.h[7] = sum32(this.h[7], h);
35121};
35122
35123SHA256.prototype._digest = function digest(enc) {
35124 if (enc === 'hex')
35125 return utils.toHex32(this.h, 'big');
35126 else
35127 return utils.split32(this.h, 'big');
35128};
35129
35130function SHA224() {
35131 if (!(this instanceof SHA224))
35132 return new SHA224();
35133
35134 SHA256.call(this);
35135 this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
35136 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
35137}
35138utils.inherits(SHA224, SHA256);
35139exports.sha224 = SHA224;
35140
35141SHA224.blockSize = 512;
35142SHA224.outSize = 224;
35143SHA224.hmacStrength = 192;
35144SHA224.padLength = 64;
35145
35146SHA224.prototype._digest = function digest(enc) {
35147 // Just truncate output
35148 if (enc === 'hex')
35149 return utils.toHex32(this.h.slice(0, 7), 'big');
35150 else
35151 return utils.split32(this.h.slice(0, 7), 'big');
35152};
35153
35154function SHA512() {
35155 if (!(this instanceof SHA512))
35156 return new SHA512();
35157
35158 BlockHash.call(this);
35159 this.h = [ 0x6a09e667, 0xf3bcc908,
35160 0xbb67ae85, 0x84caa73b,
35161 0x3c6ef372, 0xfe94f82b,
35162 0xa54ff53a, 0x5f1d36f1,
35163 0x510e527f, 0xade682d1,
35164 0x9b05688c, 0x2b3e6c1f,
35165 0x1f83d9ab, 0xfb41bd6b,
35166 0x5be0cd19, 0x137e2179 ];
35167 this.k = sha512_K;
35168 this.W = new Array(160);
35169}
35170utils.inherits(SHA512, BlockHash);
35171exports.sha512 = SHA512;
35172
35173SHA512.blockSize = 1024;
35174SHA512.outSize = 512;
35175SHA512.hmacStrength = 192;
35176SHA512.padLength = 128;
35177
35178SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
35179 var W = this.W;
35180
35181 // 32 x 32bit words
35182 for (var i = 0; i < 32; i++)
35183 W[i] = msg[start + i];
35184 for (; i < W.length; i += 2) {
35185 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
35186 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
35187 var c1_hi = W[i - 14]; // i - 7
35188 var c1_lo = W[i - 13];
35189 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
35190 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
35191 var c3_hi = W[i - 32]; // i - 16
35192 var c3_lo = W[i - 31];
35193
35194 W[i] = sum64_4_hi(c0_hi, c0_lo,
35195 c1_hi, c1_lo,
35196 c2_hi, c2_lo,
35197 c3_hi, c3_lo);
35198 W[i + 1] = sum64_4_lo(c0_hi, c0_lo,
35199 c1_hi, c1_lo,
35200 c2_hi, c2_lo,
35201 c3_hi, c3_lo);
35202 }
35203};
35204
35205SHA512.prototype._update = function _update(msg, start) {
35206 this._prepareBlock(msg, start);
35207
35208 var W = this.W;
35209
35210 var ah = this.h[0];
35211 var al = this.h[1];
35212 var bh = this.h[2];
35213 var bl = this.h[3];
35214 var ch = this.h[4];
35215 var cl = this.h[5];
35216 var dh = this.h[6];
35217 var dl = this.h[7];
35218 var eh = this.h[8];
35219 var el = this.h[9];
35220 var fh = this.h[10];
35221 var fl = this.h[11];
35222 var gh = this.h[12];
35223 var gl = this.h[13];
35224 var hh = this.h[14];
35225 var hl = this.h[15];
35226
35227 assert(this.k.length === W.length);
35228 for (var i = 0; i < W.length; i += 2) {
35229 var c0_hi = hh;
35230 var c0_lo = hl;
35231 var c1_hi = s1_512_hi(eh, el);
35232 var c1_lo = s1_512_lo(eh, el);
35233 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
35234 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
35235 var c3_hi = this.k[i];
35236 var c3_lo = this.k[i + 1];
35237 var c4_hi = W[i];
35238 var c4_lo = W[i + 1];
35239
35240 var T1_hi = sum64_5_hi(c0_hi, c0_lo,
35241 c1_hi, c1_lo,
35242 c2_hi, c2_lo,
35243 c3_hi, c3_lo,
35244 c4_hi, c4_lo);
35245 var T1_lo = sum64_5_lo(c0_hi, c0_lo,
35246 c1_hi, c1_lo,
35247 c2_hi, c2_lo,
35248 c3_hi, c3_lo,
35249 c4_hi, c4_lo);
35250
35251 var c0_hi = s0_512_hi(ah, al);
35252 var c0_lo = s0_512_lo(ah, al);
35253 var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
35254 var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
35255
35256 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
35257 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
35258
35259 hh = gh;
35260 hl = gl;
35261
35262 gh = fh;
35263 gl = fl;
35264
35265 fh = eh;
35266 fl = el;
35267
35268 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
35269 el = sum64_lo(dl, dl, T1_hi, T1_lo);
35270
35271 dh = ch;
35272 dl = cl;
35273
35274 ch = bh;
35275 cl = bl;
35276
35277 bh = ah;
35278 bl = al;
35279
35280 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
35281 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
35282 }
35283
35284 sum64(this.h, 0, ah, al);
35285 sum64(this.h, 2, bh, bl);
35286 sum64(this.h, 4, ch, cl);
35287 sum64(this.h, 6, dh, dl);
35288 sum64(this.h, 8, eh, el);
35289 sum64(this.h, 10, fh, fl);
35290 sum64(this.h, 12, gh, gl);
35291 sum64(this.h, 14, hh, hl);
35292};
35293
35294SHA512.prototype._digest = function digest(enc) {
35295 if (enc === 'hex')
35296 return utils.toHex32(this.h, 'big');
35297 else
35298 return utils.split32(this.h, 'big');
35299};
35300
35301function SHA384() {
35302 if (!(this instanceof SHA384))
35303 return new SHA384();
35304
35305 SHA512.call(this);
35306 this.h = [ 0xcbbb9d5d, 0xc1059ed8,
35307 0x629a292a, 0x367cd507,
35308 0x9159015a, 0x3070dd17,
35309 0x152fecd8, 0xf70e5939,
35310 0x67332667, 0xffc00b31,
35311 0x8eb44a87, 0x68581511,
35312 0xdb0c2e0d, 0x64f98fa7,
35313 0x47b5481d, 0xbefa4fa4 ];
35314}
35315utils.inherits(SHA384, SHA512);
35316exports.sha384 = SHA384;
35317
35318SHA384.blockSize = 1024;
35319SHA384.outSize = 384;
35320SHA384.hmacStrength = 192;
35321SHA384.padLength = 128;
35322
35323SHA384.prototype._digest = function digest(enc) {
35324 if (enc === 'hex')
35325 return utils.toHex32(this.h.slice(0, 12), 'big');
35326 else
35327 return utils.split32(this.h.slice(0, 12), 'big');
35328};
35329
35330function SHA1() {
35331 if (!(this instanceof SHA1))
35332 return new SHA1();
35333
35334 BlockHash.call(this);
35335 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe,
35336 0x10325476, 0xc3d2e1f0 ];
35337 this.W = new Array(80);
35338}
35339
35340utils.inherits(SHA1, BlockHash);
35341exports.sha1 = SHA1;
35342
35343SHA1.blockSize = 512;
35344SHA1.outSize = 160;
35345SHA1.hmacStrength = 80;
35346SHA1.padLength = 64;
35347
35348SHA1.prototype._update = function _update(msg, start) {
35349 var W = this.W;
35350
35351 for (var i = 0; i < 16; i++)
35352 W[i] = msg[start + i];
35353
35354 for(; i < W.length; i++)
35355 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
35356
35357 var a = this.h[0];
35358 var b = this.h[1];
35359 var c = this.h[2];
35360 var d = this.h[3];
35361 var e = this.h[4];
35362
35363 for (var i = 0; i < W.length; i++) {
35364 var s = ~~(i / 20);
35365 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
35366 e = d;
35367 d = c;
35368 c = rotl32(b, 30);
35369 b = a;
35370 a = t;
35371 }
35372
35373 this.h[0] = sum32(this.h[0], a);
35374 this.h[1] = sum32(this.h[1], b);
35375 this.h[2] = sum32(this.h[2], c);
35376 this.h[3] = sum32(this.h[3], d);
35377 this.h[4] = sum32(this.h[4], e);
35378};
35379
35380SHA1.prototype._digest = function digest(enc) {
35381 if (enc === 'hex')
35382 return utils.toHex32(this.h, 'big');
35383 else
35384 return utils.split32(this.h, 'big');
35385};
35386
35387function ch32(x, y, z) {
35388 return (x & y) ^ ((~x) & z);
35389}
35390
35391function maj32(x, y, z) {
35392 return (x & y) ^ (x & z) ^ (y & z);
35393}
35394
35395function p32(x, y, z) {
35396 return x ^ y ^ z;
35397}
35398
35399function s0_256(x) {
35400 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
35401}
35402
35403function s1_256(x) {
35404 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
35405}
35406
35407function g0_256(x) {
35408 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
35409}
35410
35411function g1_256(x) {
35412 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
35413}
35414
35415function ft_1(s, x, y, z) {
35416 if (s === 0)
35417 return ch32(x, y, z);
35418 if (s === 1 || s === 3)
35419 return p32(x, y, z);
35420 if (s === 2)
35421 return maj32(x, y, z);
35422}
35423
35424function ch64_hi(xh, xl, yh, yl, zh, zl) {
35425 var r = (xh & yh) ^ ((~xh) & zh);
35426 if (r < 0)
35427 r += 0x100000000;
35428 return r;
35429}
35430
35431function ch64_lo(xh, xl, yh, yl, zh, zl) {
35432 var r = (xl & yl) ^ ((~xl) & zl);
35433 if (r < 0)
35434 r += 0x100000000;
35435 return r;
35436}
35437
35438function maj64_hi(xh, xl, yh, yl, zh, zl) {
35439 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
35440 if (r < 0)
35441 r += 0x100000000;
35442 return r;
35443}
35444
35445function maj64_lo(xh, xl, yh, yl, zh, zl) {
35446 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
35447 if (r < 0)
35448 r += 0x100000000;
35449 return r;
35450}
35451
35452function s0_512_hi(xh, xl) {
35453 var c0_hi = rotr64_hi(xh, xl, 28);
35454 var c1_hi = rotr64_hi(xl, xh, 2); // 34
35455 var c2_hi = rotr64_hi(xl, xh, 7); // 39
35456
35457 var r = c0_hi ^ c1_hi ^ c2_hi;
35458 if (r < 0)
35459 r += 0x100000000;
35460 return r;
35461}
35462
35463function s0_512_lo(xh, xl) {
35464 var c0_lo = rotr64_lo(xh, xl, 28);
35465 var c1_lo = rotr64_lo(xl, xh, 2); // 34
35466 var c2_lo = rotr64_lo(xl, xh, 7); // 39
35467
35468 var r = c0_lo ^ c1_lo ^ c2_lo;
35469 if (r < 0)
35470 r += 0x100000000;
35471 return r;
35472}
35473
35474function s1_512_hi(xh, xl) {
35475 var c0_hi = rotr64_hi(xh, xl, 14);
35476 var c1_hi = rotr64_hi(xh, xl, 18);
35477 var c2_hi = rotr64_hi(xl, xh, 9); // 41
35478
35479 var r = c0_hi ^ c1_hi ^ c2_hi;
35480 if (r < 0)
35481 r += 0x100000000;
35482 return r;
35483}
35484
35485function s1_512_lo(xh, xl) {
35486 var c0_lo = rotr64_lo(xh, xl, 14);
35487 var c1_lo = rotr64_lo(xh, xl, 18);
35488 var c2_lo = rotr64_lo(xl, xh, 9); // 41
35489
35490 var r = c0_lo ^ c1_lo ^ c2_lo;
35491 if (r < 0)
35492 r += 0x100000000;
35493 return r;
35494}
35495
35496function g0_512_hi(xh, xl) {
35497 var c0_hi = rotr64_hi(xh, xl, 1);
35498 var c1_hi = rotr64_hi(xh, xl, 8);
35499 var c2_hi = shr64_hi(xh, xl, 7);
35500
35501 var r = c0_hi ^ c1_hi ^ c2_hi;
35502 if (r < 0)
35503 r += 0x100000000;
35504 return r;
35505}
35506
35507function g0_512_lo(xh, xl) {
35508 var c0_lo = rotr64_lo(xh, xl, 1);
35509 var c1_lo = rotr64_lo(xh, xl, 8);
35510 var c2_lo = shr64_lo(xh, xl, 7);
35511
35512 var r = c0_lo ^ c1_lo ^ c2_lo;
35513 if (r < 0)
35514 r += 0x100000000;
35515 return r;
35516}
35517
35518function g1_512_hi(xh, xl) {
35519 var c0_hi = rotr64_hi(xh, xl, 19);
35520 var c1_hi = rotr64_hi(xl, xh, 29); // 61
35521 var c2_hi = shr64_hi(xh, xl, 6);
35522
35523 var r = c0_hi ^ c1_hi ^ c2_hi;
35524 if (r < 0)
35525 r += 0x100000000;
35526 return r;
35527}
35528
35529function g1_512_lo(xh, xl) {
35530 var c0_lo = rotr64_lo(xh, xl, 19);
35531 var c1_lo = rotr64_lo(xl, xh, 29); // 61
35532 var c2_lo = shr64_lo(xh, xl, 6);
35533
35534 var r = c0_lo ^ c1_lo ^ c2_lo;
35535 if (r < 0)
35536 r += 0x100000000;
35537 return r;
35538}
35539}, {"../hash":211}],215: [function (exports, require, module, global) {var hash = require('../hash');
35540var utils = hash.utils;
35541
35542var rotl32 = utils.rotl32;
35543var sum32 = utils.sum32;
35544var sum32_3 = utils.sum32_3;
35545var sum32_4 = utils.sum32_4;
35546var BlockHash = hash.common.BlockHash;
35547
35548function RIPEMD160() {
35549 if (!(this instanceof RIPEMD160))
35550 return new RIPEMD160();
35551
35552 BlockHash.call(this);
35553
35554 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
35555 this.endian = 'little';
35556}
35557utils.inherits(RIPEMD160, BlockHash);
35558exports.ripemd160 = RIPEMD160;
35559
35560RIPEMD160.blockSize = 512;
35561RIPEMD160.outSize = 160;
35562RIPEMD160.hmacStrength = 192;
35563RIPEMD160.padLength = 64;
35564
35565RIPEMD160.prototype._update = function update(msg, start) {
35566 var A = this.h[0];
35567 var B = this.h[1];
35568 var C = this.h[2];
35569 var D = this.h[3];
35570 var E = this.h[4];
35571 var Ah = A;
35572 var Bh = B;
35573 var Ch = C;
35574 var Dh = D;
35575 var Eh = E;
35576 for (var j = 0; j < 80; j++) {
35577 var T = sum32(
35578 rotl32(
35579 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
35580 s[j]),
35581 E);
35582 A = E;
35583 E = D;
35584 D = rotl32(C, 10);
35585 C = B;
35586 B = T;
35587 T = sum32(
35588 rotl32(
35589 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
35590 sh[j]),
35591 Eh);
35592 Ah = Eh;
35593 Eh = Dh;
35594 Dh = rotl32(Ch, 10);
35595 Ch = Bh;
35596 Bh = T;
35597 }
35598 T = sum32_3(this.h[1], C, Dh);
35599 this.h[1] = sum32_3(this.h[2], D, Eh);
35600 this.h[2] = sum32_3(this.h[3], E, Ah);
35601 this.h[3] = sum32_3(this.h[4], A, Bh);
35602 this.h[4] = sum32_3(this.h[0], B, Ch);
35603 this.h[0] = T;
35604};
35605
35606RIPEMD160.prototype._digest = function digest(enc) {
35607 if (enc === 'hex')
35608 return utils.toHex32(this.h, 'little');
35609 else
35610 return utils.split32(this.h, 'little');
35611};
35612
35613function f(j, x, y, z) {
35614 if (j <= 15)
35615 return x ^ y ^ z;
35616 else if (j <= 31)
35617 return (x & y) | ((~x) & z);
35618 else if (j <= 47)
35619 return (x | (~y)) ^ z;
35620 else if (j <= 63)
35621 return (x & z) | (y & (~z));
35622 else
35623 return x ^ (y | (~z));
35624}
35625
35626function K(j) {
35627 if (j <= 15)
35628 return 0x00000000;
35629 else if (j <= 31)
35630 return 0x5a827999;
35631 else if (j <= 47)
35632 return 0x6ed9eba1;
35633 else if (j <= 63)
35634 return 0x8f1bbcdc;
35635 else
35636 return 0xa953fd4e;
35637}
35638
35639function Kh(j) {
35640 if (j <= 15)
35641 return 0x50a28be6;
35642 else if (j <= 31)
35643 return 0x5c4dd124;
35644 else if (j <= 47)
35645 return 0x6d703ef3;
35646 else if (j <= 63)
35647 return 0x7a6d76e9;
35648 else
35649 return 0x00000000;
35650}
35651
35652var r = [
35653 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
35654 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
35655 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
35656 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
35657 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
35658];
35659
35660var rh = [
35661 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
35662 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
35663 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
35664 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
35665 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
35666];
35667
35668var s = [
35669 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
35670 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
35671 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
35672 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
35673 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
35674];
35675
35676var sh = [
35677 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
35678 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
35679 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
35680 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
35681 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
35682];
35683}, {"../hash":211}],216: [function (exports, require, module, global) {var hmac = exports;
35684
35685var hash = require('../hash');
35686var utils = hash.utils;
35687var assert = utils.assert;
35688
35689function Hmac(hash, key, enc) {
35690 if (!(this instanceof Hmac))
35691 return new Hmac(hash, key, enc);
35692 this.Hash = hash;
35693 this.blockSize = hash.blockSize / 8;
35694 this.outSize = hash.outSize / 8;
35695 this.inner = null;
35696 this.outer = null;
35697
35698 this._init(utils.toArray(key, enc));
35699}
35700module.exports = Hmac;
35701
35702Hmac.prototype._init = function init(key) {
35703 // Shorten key, if needed
35704 if (key.length > this.blockSize)
35705 key = new this.Hash().update(key).digest();
35706 assert(key.length <= this.blockSize);
35707
35708 // Add padding to key
35709 for (var i = key.length; i < this.blockSize; i++)
35710 key.push(0);
35711
35712 for (var i = 0; i < key.length; i++)
35713 key[i] ^= 0x36;
35714 this.inner = new this.Hash().update(key);
35715
35716 // 0x36 ^ 0x5c = 0x6a
35717 for (var i = 0; i < key.length; i++)
35718 key[i] ^= 0x6a;
35719 this.outer = new this.Hash().update(key);
35720};
35721
35722Hmac.prototype.update = function update(msg, enc) {
35723 this.inner.update(msg, enc);
35724 return this;
35725};
35726
35727Hmac.prototype.digest = function digest(enc) {
35728 this.outer.update(this.inner.digest());
35729 return this.outer.digest(enc);
35730};
35731}, {"../hash":211}],217: [function (exports, require, module, global) {'use strict';
35732
35733var curve = exports;
35734
35735curve.base = require('./base');
35736curve.short = require('./short');
35737curve.mont = require('./mont');
35738curve.edwards = require('./edwards');
35739}, {"./base":218,"./short":219,"./mont":220,"./edwards":221}],218: [function (exports, require, module, global) {'use strict';
35740
35741var bn = require('bn.js');
35742var elliptic = require('../../elliptic');
35743
35744var getNAF = elliptic.utils.getNAF;
35745var getJSF = elliptic.utils.getJSF;
35746var assert = elliptic.utils.assert;
35747
35748function BaseCurve(type, conf) {
35749 this.type = type;
35750 this.p = new bn(conf.p, 16);
35751
35752 // Use Montgomery, when there is no fast reduction for the prime
35753 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
35754
35755 // Useful for many curves
35756 this.zero = new bn(0).toRed(this.red);
35757 this.one = new bn(1).toRed(this.red);
35758 this.two = new bn(2).toRed(this.red);
35759
35760 // Curve configuration, optional
35761 this.n = conf.n && new bn(conf.n, 16);
35762 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
35763
35764 // Temporary arrays
35765 this._wnafT1 = new Array(4);
35766 this._wnafT2 = new Array(4);
35767 this._wnafT3 = new Array(4);
35768 this._wnafT4 = new Array(4);
35769}
35770module.exports = BaseCurve;
35771
35772BaseCurve.prototype.point = function point() {
35773 throw new Error('Not implemented');
35774};
35775
35776BaseCurve.prototype.validate = function validate() {
35777 throw new Error('Not implemented');
35778};
35779
35780BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
35781 assert(p.precomputed);
35782 var doubles = p._getDoubles();
35783
35784 var naf = getNAF(k, 1);
35785 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
35786 I /= 3;
35787
35788 // Translate into more windowed form
35789 var repr = [];
35790 for (var j = 0; j < naf.length; j += doubles.step) {
35791 var nafW = 0;
35792 for (var k = j + doubles.step - 1; k >= j; k--)
35793 nafW = (nafW << 1) + naf[k];
35794 repr.push(nafW);
35795 }
35796
35797 var a = this.jpoint(null, null, null);
35798 var b = this.jpoint(null, null, null);
35799 for (var i = I; i > 0; i--) {
35800 for (var j = 0; j < repr.length; j++) {
35801 var nafW = repr[j];
35802 if (nafW === i)
35803 b = b.mixedAdd(doubles.points[j]);
35804 else if (nafW === -i)
35805 b = b.mixedAdd(doubles.points[j].neg());
35806 }
35807 a = a.add(b);
35808 }
35809 return a.toP();
35810};
35811
35812BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
35813 var w = 4;
35814
35815 // Precompute window
35816 var nafPoints = p._getNAFPoints(w);
35817 w = nafPoints.wnd;
35818 var wnd = nafPoints.points;
35819
35820 // Get NAF form
35821 var naf = getNAF(k, w);
35822
35823 // Add `this`*(N+1) for every w-NAF index
35824 var acc = this.jpoint(null, null, null);
35825 for (var i = naf.length - 1; i >= 0; i--) {
35826 // Count zeroes
35827 for (var k = 0; i >= 0 && naf[i] === 0; i--)
35828 k++;
35829 if (i >= 0)
35830 k++;
35831 acc = acc.dblp(k);
35832
35833 if (i < 0)
35834 break;
35835 var z = naf[i];
35836 assert(z !== 0);
35837 if (p.type === 'affine') {
35838 // J +- P
35839 if (z > 0)
35840 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
35841 else
35842 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
35843 } else {
35844 // J +- J
35845 if (z > 0)
35846 acc = acc.add(wnd[(z - 1) >> 1]);
35847 else
35848 acc = acc.add(wnd[(-z - 1) >> 1].neg());
35849 }
35850 }
35851 return p.type === 'affine' ? acc.toP() : acc;
35852};
35853
35854BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
35855 points,
35856 coeffs,
35857 len) {
35858 var wndWidth = this._wnafT1;
35859 var wnd = this._wnafT2;
35860 var naf = this._wnafT3;
35861
35862 // Fill all arrays
35863 var max = 0;
35864 for (var i = 0; i < len; i++) {
35865 var p = points[i];
35866 var nafPoints = p._getNAFPoints(defW);
35867 wndWidth[i] = nafPoints.wnd;
35868 wnd[i] = nafPoints.points;
35869 }
35870
35871 // Comb small window NAFs
35872 for (var i = len - 1; i >= 1; i -= 2) {
35873 var a = i - 1;
35874 var b = i;
35875 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
35876 naf[a] = getNAF(coeffs[a], wndWidth[a]);
35877 naf[b] = getNAF(coeffs[b], wndWidth[b]);
35878 max = Math.max(naf[a].length, max);
35879 max = Math.max(naf[b].length, max);
35880 continue;
35881 }
35882
35883 var comb = [
35884 points[a], /* 1 */
35885 null, /* 3 */
35886 null, /* 5 */
35887 points[b] /* 7 */
35888 ];
35889
35890 // Try to avoid Projective points, if possible
35891 if (points[a].y.cmp(points[b].y) === 0) {
35892 comb[1] = points[a].add(points[b]);
35893 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
35894 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
35895 comb[1] = points[a].toJ().mixedAdd(points[b]);
35896 comb[2] = points[a].add(points[b].neg());
35897 } else {
35898 comb[1] = points[a].toJ().mixedAdd(points[b]);
35899 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
35900 }
35901
35902 var index = [
35903 -3, /* -1 -1 */
35904 -1, /* -1 0 */
35905 -5, /* -1 1 */
35906 -7, /* 0 -1 */
35907 0, /* 0 0 */
35908 7, /* 0 1 */
35909 5, /* 1 -1 */
35910 1, /* 1 0 */
35911 3 /* 1 1 */
35912 ];
35913
35914 var jsf = getJSF(coeffs[a], coeffs[b]);
35915 max = Math.max(jsf[0].length, max);
35916 naf[a] = new Array(max);
35917 naf[b] = new Array(max);
35918 for (var j = 0; j < max; j++) {
35919 var ja = jsf[0][j] | 0;
35920 var jb = jsf[1][j] | 0;
35921
35922 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
35923 naf[b][j] = 0;
35924 wnd[a] = comb;
35925 }
35926 }
35927
35928 var acc = this.jpoint(null, null, null);
35929 var tmp = this._wnafT4;
35930 for (var i = max; i >= 0; i--) {
35931 var k = 0;
35932
35933 while (i >= 0) {
35934 var zero = true;
35935 for (var j = 0; j < len; j++) {
35936 tmp[j] = naf[j][i] | 0;
35937 if (tmp[j] !== 0)
35938 zero = false;
35939 }
35940 if (!zero)
35941 break;
35942 k++;
35943 i--;
35944 }
35945 if (i >= 0)
35946 k++;
35947 acc = acc.dblp(k);
35948 if (i < 0)
35949 break;
35950
35951 for (var j = 0; j < len; j++) {
35952 var z = tmp[j];
35953 var p;
35954 if (z === 0)
35955 continue;
35956 else if (z > 0)
35957 p = wnd[j][(z - 1) >> 1];
35958 else if (z < 0)
35959 p = wnd[j][(-z - 1) >> 1].neg();
35960
35961 if (p.type === 'affine')
35962 acc = acc.mixedAdd(p);
35963 else
35964 acc = acc.add(p);
35965 }
35966 }
35967 // Zeroify references
35968 for (var i = 0; i < len; i++)
35969 wnd[i] = null;
35970 return acc.toP();
35971};
35972
35973function BasePoint(curve, type) {
35974 this.curve = curve;
35975 this.type = type;
35976 this.precomputed = null;
35977}
35978BaseCurve.BasePoint = BasePoint;
35979
35980BasePoint.prototype.validate = function validate() {
35981 return this.curve.validate(this);
35982};
35983
35984BasePoint.prototype.precompute = function precompute(power) {
35985 if (this.precomputed)
35986 return this;
35987
35988 var precomputed = {
35989 doubles: null,
35990 naf: null,
35991 beta: null
35992 };
35993 precomputed.naf = this._getNAFPoints(8);
35994 precomputed.doubles = this._getDoubles(4, power);
35995 precomputed.beta = this._getBeta();
35996 this.precomputed = precomputed;
35997
35998 return this;
35999};
36000
36001BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
36002 if (!this.precomputed)
36003 return false;
36004
36005 var doubles = this.precomputed.doubles;
36006 if (!doubles)
36007 return false;
36008
36009 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
36010};
36011
36012BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
36013 if (this.precomputed && this.precomputed.doubles)
36014 return this.precomputed.doubles;
36015
36016 var doubles = [ this ];
36017 var acc = this;
36018 for (var i = 0; i < power; i += step) {
36019 for (var j = 0; j < step; j++)
36020 acc = acc.dbl();
36021 doubles.push(acc);
36022 }
36023 return {
36024 step: step,
36025 points: doubles
36026 };
36027};
36028
36029BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
36030 if (this.precomputed && this.precomputed.naf)
36031 return this.precomputed.naf;
36032
36033 var res = [ this ];
36034 var max = (1 << wnd) - 1;
36035 var dbl = max === 1 ? null : this.dbl();
36036 for (var i = 1; i < max; i++)
36037 res[i] = res[i - 1].add(dbl);
36038 return {
36039 wnd: wnd,
36040 points: res
36041 };
36042};
36043
36044BasePoint.prototype._getBeta = function _getBeta() {
36045 return null;
36046};
36047
36048BasePoint.prototype.dblp = function dblp(k) {
36049 var r = this;
36050 for (var i = 0; i < k; i++)
36051 r = r.dbl();
36052 return r;
36053};
36054}, {"bn.js":204,"../../elliptic":206}],219: [function (exports, require, module, global) {'use strict';
36055
36056var curve = require('../curve');
36057var elliptic = require('../../elliptic');
36058var bn = require('bn.js');
36059var inherits = require('inherits');
36060var Base = curve.base;
36061
36062var assert = elliptic.utils.assert;
36063
36064function ShortCurve(conf) {
36065 Base.call(this, 'short', conf);
36066
36067 this.a = new bn(conf.a, 16).toRed(this.red);
36068 this.b = new bn(conf.b, 16).toRed(this.red);
36069 this.tinv = this.two.redInvm();
36070
36071 this.zeroA = this.a.fromRed().cmpn(0) === 0;
36072 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
36073
36074 // If the curve is endomorphic, precalculate beta and lambda
36075 this.endo = this._getEndomorphism(conf);
36076 this._endoWnafT1 = new Array(4);
36077 this._endoWnafT2 = new Array(4);
36078}
36079inherits(ShortCurve, Base);
36080module.exports = ShortCurve;
36081
36082ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
36083 // No efficient endomorphism
36084 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
36085 return;
36086
36087 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
36088 var beta;
36089 var lambda;
36090 if (conf.beta) {
36091 beta = new bn(conf.beta, 16).toRed(this.red);
36092 } else {
36093 var betas = this._getEndoRoots(this.p);
36094 // Choose the smallest beta
36095 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
36096 beta = beta.toRed(this.red);
36097 }
36098 if (conf.lambda) {
36099 lambda = new bn(conf.lambda, 16);
36100 } else {
36101 // Choose the lambda that is matching selected beta
36102 var lambdas = this._getEndoRoots(this.n);
36103 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
36104 lambda = lambdas[0];
36105 } else {
36106 lambda = lambdas[1];
36107 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
36108 }
36109 }
36110
36111 // Get basis vectors, used for balanced length-two representation
36112 var basis;
36113 if (conf.basis) {
36114 basis = conf.basis.map(function(vec) {
36115 return {
36116 a: new bn(vec.a, 16),
36117 b: new bn(vec.b, 16)
36118 };
36119 });
36120 } else {
36121 basis = this._getEndoBasis(lambda);
36122 }
36123
36124 return {
36125 beta: beta,
36126 lambda: lambda,
36127 basis: basis
36128 };
36129};
36130
36131ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
36132 // Find roots of for x^2 + x + 1 in F
36133 // Root = (-1 +- Sqrt(-3)) / 2
36134 //
36135 var red = num === this.p ? this.red : bn.mont(num);
36136 var tinv = new bn(2).toRed(red).redInvm();
36137 var ntinv = tinv.redNeg();
36138
36139 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
36140
36141 var l1 = ntinv.redAdd(s).fromRed();
36142 var l2 = ntinv.redSub(s).fromRed();
36143 return [ l1, l2 ];
36144};
36145
36146ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
36147 // aprxSqrt >= sqrt(this.n)
36148 var aprxSqrt = this.n.shrn(Math.floor(this.n.bitLength() / 2));
36149
36150 // 3.74
36151 // Run EGCD, until r(L + 1) < aprxSqrt
36152 var u = lambda;
36153 var v = this.n.clone();
36154 var x1 = new bn(1);
36155 var y1 = new bn(0);
36156 var x2 = new bn(0);
36157 var y2 = new bn(1);
36158
36159 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
36160 var a0;
36161 var b0;
36162 // First vector
36163 var a1;
36164 var b1;
36165 // Second vector
36166 var a2;
36167 var b2;
36168
36169 var prevR;
36170 var i = 0;
36171 var r;
36172 var x;
36173 while (u.cmpn(0) !== 0) {
36174 var q = v.div(u);
36175 r = v.sub(q.mul(u));
36176 x = x2.sub(q.mul(x1));
36177 var y = y2.sub(q.mul(y1));
36178
36179 if (!a1 && r.cmp(aprxSqrt) < 0) {
36180 a0 = prevR.neg();
36181 b0 = x1;
36182 a1 = r.neg();
36183 b1 = x;
36184 } else if (a1 && ++i === 2) {
36185 break;
36186 }
36187 prevR = r;
36188
36189 v = u;
36190 u = r;
36191 x2 = x1;
36192 x1 = x;
36193 y2 = y1;
36194 y1 = y;
36195 }
36196 a2 = r.neg();
36197 b2 = x;
36198
36199 var len1 = a1.sqr().add(b1.sqr());
36200 var len2 = a2.sqr().add(b2.sqr());
36201 if (len2.cmp(len1) >= 0) {
36202 a2 = a0;
36203 b2 = b0;
36204 }
36205
36206 // Normalize signs
36207 if (a1.sign) {
36208 a1 = a1.neg();
36209 b1 = b1.neg();
36210 }
36211 if (a2.sign) {
36212 a2 = a2.neg();
36213 b2 = b2.neg();
36214 }
36215
36216 return [
36217 { a: a1, b: b1 },
36218 { a: a2, b: b2 }
36219 ];
36220};
36221
36222ShortCurve.prototype._endoSplit = function _endoSplit(k) {
36223 var basis = this.endo.basis;
36224 var v1 = basis[0];
36225 var v2 = basis[1];
36226
36227 var c1 = v2.b.mul(k).divRound(this.n);
36228 var c2 = v1.b.neg().mul(k).divRound(this.n);
36229
36230 var p1 = c1.mul(v1.a);
36231 var p2 = c2.mul(v2.a);
36232 var q1 = c1.mul(v1.b);
36233 var q2 = c2.mul(v2.b);
36234
36235 // Calculate answer
36236 var k1 = k.sub(p1).sub(p2);
36237 var k2 = q1.add(q2).neg();
36238 return { k1: k1, k2: k2 };
36239};
36240
36241ShortCurve.prototype.pointFromX = function pointFromX(odd, x) {
36242 x = new bn(x, 16);
36243 if (!x.red)
36244 x = x.toRed(this.red);
36245
36246 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
36247 var y = y2.redSqrt();
36248
36249 // XXX Is there any way to tell if the number is odd without converting it
36250 // to non-red form?
36251 var isOdd = y.fromRed().isOdd();
36252 if (odd && !isOdd || !odd && isOdd)
36253 y = y.redNeg();
36254
36255 return this.point(x, y);
36256};
36257
36258ShortCurve.prototype.validate = function validate(point) {
36259 if (point.inf)
36260 return true;
36261
36262 var x = point.x;
36263 var y = point.y;
36264
36265 var ax = this.a.redMul(x);
36266 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
36267 return y.redSqr().redISub(rhs).cmpn(0) === 0;
36268};
36269
36270ShortCurve.prototype._endoWnafMulAdd =
36271 function _endoWnafMulAdd(points, coeffs) {
36272 var npoints = this._endoWnafT1;
36273 var ncoeffs = this._endoWnafT2;
36274 for (var i = 0; i < points.length; i++) {
36275 var split = this._endoSplit(coeffs[i]);
36276 var p = points[i];
36277 var beta = p._getBeta();
36278
36279 if (split.k1.sign) {
36280 split.k1.sign = !split.k1.sign;
36281 p = p.neg(true);
36282 }
36283 if (split.k2.sign) {
36284 split.k2.sign = !split.k2.sign;
36285 beta = beta.neg(true);
36286 }
36287
36288 npoints[i * 2] = p;
36289 npoints[i * 2 + 1] = beta;
36290 ncoeffs[i * 2] = split.k1;
36291 ncoeffs[i * 2 + 1] = split.k2;
36292 }
36293 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2);
36294
36295 // Clean-up references to points and coefficients
36296 for (var j = 0; j < i * 2; j++) {
36297 npoints[j] = null;
36298 ncoeffs[j] = null;
36299 }
36300 return res;
36301};
36302
36303function Point(curve, x, y, isRed) {
36304 Base.BasePoint.call(this, curve, 'affine');
36305 if (x === null && y === null) {
36306 this.x = null;
36307 this.y = null;
36308 this.inf = true;
36309 } else {
36310 this.x = new bn(x, 16);
36311 this.y = new bn(y, 16);
36312 // Force redgomery representation when loading from JSON
36313 if (isRed) {
36314 this.x.forceRed(this.curve.red);
36315 this.y.forceRed(this.curve.red);
36316 }
36317 if (!this.x.red)
36318 this.x = this.x.toRed(this.curve.red);
36319 if (!this.y.red)
36320 this.y = this.y.toRed(this.curve.red);
36321 this.inf = false;
36322 }
36323}
36324inherits(Point, Base.BasePoint);
36325
36326ShortCurve.prototype.point = function point(x, y, isRed) {
36327 return new Point(this, x, y, isRed);
36328};
36329
36330ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
36331 return Point.fromJSON(this, obj, red);
36332};
36333
36334Point.prototype._getBeta = function _getBeta() {
36335 if (!this.curve.endo)
36336 return;
36337
36338 var pre = this.precomputed;
36339 if (pre && pre.beta)
36340 return pre.beta;
36341
36342 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
36343 if (pre) {
36344 var curve = this.curve;
36345 var endoMul = function(p) {
36346 return curve.point(p.x.redMul(curve.endo.beta), p.y);
36347 };
36348 pre.beta = beta;
36349 beta.precomputed = {
36350 beta: null,
36351 naf: pre.naf && {
36352 wnd: pre.naf.wnd,
36353 points: pre.naf.points.map(endoMul)
36354 },
36355 doubles: pre.doubles && {
36356 step: pre.doubles.step,
36357 points: pre.doubles.points.map(endoMul)
36358 }
36359 };
36360 }
36361 return beta;
36362};
36363
36364Point.prototype.toJSON = function toJSON() {
36365 if (!this.precomputed)
36366 return [ this.x, this.y ];
36367
36368 return [ this.x, this.y, this.precomputed && {
36369 doubles: this.precomputed.doubles && {
36370 step: this.precomputed.doubles.step,
36371 points: this.precomputed.doubles.points.slice(1)
36372 },
36373 naf: this.precomputed.naf && {
36374 wnd: this.precomputed.naf.wnd,
36375 points: this.precomputed.naf.points.slice(1)
36376 }
36377 } ];
36378};
36379
36380Point.fromJSON = function fromJSON(curve, obj, red) {
36381 if (typeof obj === 'string')
36382 obj = JSON.parse(obj);
36383 var res = curve.point(obj[0], obj[1], red);
36384 if (!obj[2])
36385 return res;
36386
36387 function obj2point(obj) {
36388 return curve.point(obj[0], obj[1], red);
36389 }
36390
36391 var pre = obj[2];
36392 res.precomputed = {
36393 beta: null,
36394 doubles: pre.doubles && {
36395 step: pre.doubles.step,
36396 points: [ res ].concat(pre.doubles.points.map(obj2point))
36397 },
36398 naf: pre.naf && {
36399 wnd: pre.naf.wnd,
36400 points: [ res ].concat(pre.naf.points.map(obj2point))
36401 }
36402 };
36403 return res;
36404};
36405
36406Point.prototype.inspect = function inspect() {
36407 if (this.isInfinity())
36408 return '<EC Point Infinity>';
36409 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
36410 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
36411};
36412
36413Point.prototype.isInfinity = function isInfinity() {
36414 return this.inf;
36415};
36416
36417Point.prototype.add = function add(p) {
36418 // O + P = P
36419 if (this.inf)
36420 return p;
36421
36422 // P + O = P
36423 if (p.inf)
36424 return this;
36425
36426 // P + P = 2P
36427 if (this.eq(p))
36428 return this.dbl();
36429
36430 // P + (-P) = O
36431 if (this.neg().eq(p))
36432 return this.curve.point(null, null);
36433
36434 // P + Q = O
36435 if (this.x.cmp(p.x) === 0)
36436 return this.curve.point(null, null);
36437
36438 var c = this.y.redSub(p.y);
36439 if (c.cmpn(0) !== 0)
36440 c = c.redMul(this.x.redSub(p.x).redInvm());
36441 var nx = c.redSqr().redISub(this.x).redISub(p.x);
36442 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
36443 return this.curve.point(nx, ny);
36444};
36445
36446Point.prototype.dbl = function dbl() {
36447 if (this.inf)
36448 return this;
36449
36450 // 2P = O
36451 var ys1 = this.y.redAdd(this.y);
36452 if (ys1.cmpn(0) === 0)
36453 return this.curve.point(null, null);
36454
36455 var a = this.curve.a;
36456
36457 var x2 = this.x.redSqr();
36458 var dyinv = ys1.redInvm();
36459 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
36460
36461 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
36462 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
36463 return this.curve.point(nx, ny);
36464};
36465
36466Point.prototype.getX = function getX() {
36467 return this.x.fromRed();
36468};
36469
36470Point.prototype.getY = function getY() {
36471 return this.y.fromRed();
36472};
36473
36474Point.prototype.mul = function mul(k) {
36475 k = new bn(k, 16);
36476
36477 if (this._hasDoubles(k))
36478 return this.curve._fixedNafMul(this, k);
36479 else if (this.curve.endo)
36480 return this.curve._endoWnafMulAdd([ this ], [ k ]);
36481 else
36482 return this.curve._wnafMul(this, k);
36483};
36484
36485Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
36486 var points = [ this, p2 ];
36487 var coeffs = [ k1, k2 ];
36488 if (this.curve.endo)
36489 return this.curve._endoWnafMulAdd(points, coeffs);
36490 else
36491 return this.curve._wnafMulAdd(1, points, coeffs, 2);
36492};
36493
36494Point.prototype.eq = function eq(p) {
36495 return this === p ||
36496 this.inf === p.inf &&
36497 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
36498};
36499
36500Point.prototype.neg = function neg(_precompute) {
36501 if (this.inf)
36502 return this;
36503
36504 var res = this.curve.point(this.x, this.y.redNeg());
36505 if (_precompute && this.precomputed) {
36506 var pre = this.precomputed;
36507 var negate = function(p) {
36508 return p.neg();
36509 };
36510 res.precomputed = {
36511 naf: pre.naf && {
36512 wnd: pre.naf.wnd,
36513 points: pre.naf.points.map(negate)
36514 },
36515 doubles: pre.doubles && {
36516 step: pre.doubles.step,
36517 points: pre.doubles.points.map(negate)
36518 }
36519 };
36520 }
36521 return res;
36522};
36523
36524Point.prototype.toJ = function toJ() {
36525 if (this.inf)
36526 return this.curve.jpoint(null, null, null);
36527
36528 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
36529 return res;
36530};
36531
36532function JPoint(curve, x, y, z) {
36533 Base.BasePoint.call(this, curve, 'jacobian');
36534 if (x === null && y === null && z === null) {
36535 this.x = this.curve.one;
36536 this.y = this.curve.one;
36537 this.z = new bn(0);
36538 } else {
36539 this.x = new bn(x, 16);
36540 this.y = new bn(y, 16);
36541 this.z = new bn(z, 16);
36542 }
36543 if (!this.x.red)
36544 this.x = this.x.toRed(this.curve.red);
36545 if (!this.y.red)
36546 this.y = this.y.toRed(this.curve.red);
36547 if (!this.z.red)
36548 this.z = this.z.toRed(this.curve.red);
36549
36550 this.zOne = this.z === this.curve.one;
36551}
36552inherits(JPoint, Base.BasePoint);
36553
36554ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
36555 return new JPoint(this, x, y, z);
36556};
36557
36558JPoint.prototype.toP = function toP() {
36559 if (this.isInfinity())
36560 return this.curve.point(null, null);
36561
36562 var zinv = this.z.redInvm();
36563 var zinv2 = zinv.redSqr();
36564 var ax = this.x.redMul(zinv2);
36565 var ay = this.y.redMul(zinv2).redMul(zinv);
36566
36567 return this.curve.point(ax, ay);
36568};
36569
36570JPoint.prototype.neg = function neg() {
36571 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
36572};
36573
36574JPoint.prototype.add = function add(p) {
36575 // O + P = P
36576 if (this.isInfinity())
36577 return p;
36578
36579 // P + O = P
36580 if (p.isInfinity())
36581 return this;
36582
36583 // 12M + 4S + 7A
36584 var pz2 = p.z.redSqr();
36585 var z2 = this.z.redSqr();
36586 var u1 = this.x.redMul(pz2);
36587 var u2 = p.x.redMul(z2);
36588 var s1 = this.y.redMul(pz2.redMul(p.z));
36589 var s2 = p.y.redMul(z2.redMul(this.z));
36590
36591 var h = u1.redSub(u2);
36592 var r = s1.redSub(s2);
36593 if (h.cmpn(0) === 0) {
36594 if (r.cmpn(0) !== 0)
36595 return this.curve.jpoint(null, null, null);
36596 else
36597 return this.dbl();
36598 }
36599
36600 var h2 = h.redSqr();
36601 var h3 = h2.redMul(h);
36602 var v = u1.redMul(h2);
36603
36604 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
36605 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
36606 var nz = this.z.redMul(p.z).redMul(h);
36607
36608 return this.curve.jpoint(nx, ny, nz);
36609};
36610
36611JPoint.prototype.mixedAdd = function mixedAdd(p) {
36612 // O + P = P
36613 if (this.isInfinity())
36614 return p.toJ();
36615
36616 // P + O = P
36617 if (p.isInfinity())
36618 return this;
36619
36620 // 8M + 3S + 7A
36621 var z2 = this.z.redSqr();
36622 var u1 = this.x;
36623 var u2 = p.x.redMul(z2);
36624 var s1 = this.y;
36625 var s2 = p.y.redMul(z2).redMul(this.z);
36626
36627 var h = u1.redSub(u2);
36628 var r = s1.redSub(s2);
36629 if (h.cmpn(0) === 0) {
36630 if (r.cmpn(0) !== 0)
36631 return this.curve.jpoint(null, null, null);
36632 else
36633 return this.dbl();
36634 }
36635
36636 var h2 = h.redSqr();
36637 var h3 = h2.redMul(h);
36638 var v = u1.redMul(h2);
36639
36640 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
36641 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
36642 var nz = this.z.redMul(h);
36643
36644 return this.curve.jpoint(nx, ny, nz);
36645};
36646
36647JPoint.prototype.dblp = function dblp(pow) {
36648 if (pow === 0)
36649 return this;
36650 if (this.isInfinity())
36651 return this;
36652 if (!pow)
36653 return this.dbl();
36654
36655 if (this.curve.zeroA || this.curve.threeA) {
36656 var r = this;
36657 for (var i = 0; i < pow; i++)
36658 r = r.dbl();
36659 return r;
36660 }
36661
36662 // 1M + 2S + 1A + N * (4S + 5M + 8A)
36663 // N = 1 => 6M + 6S + 9A
36664 var a = this.curve.a;
36665 var tinv = this.curve.tinv;
36666
36667 var jx = this.x;
36668 var jy = this.y;
36669 var jz = this.z;
36670 var jz4 = jz.redSqr().redSqr();
36671
36672 // Reuse results
36673 var jyd = jy.redAdd(jy);
36674 for (var i = 0; i < pow; i++) {
36675 var jx2 = jx.redSqr();
36676 var jyd2 = jyd.redSqr();
36677 var jyd4 = jyd2.redSqr();
36678 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
36679
36680 var t1 = jx.redMul(jyd2);
36681 var nx = c.redSqr().redISub(t1.redAdd(t1));
36682 var t2 = t1.redISub(nx);
36683 var dny = c.redMul(t2);
36684 dny = dny.redIAdd(dny).redISub(jyd4);
36685 var nz = jyd.redMul(jz);
36686 if (i + 1 < pow)
36687 jz4 = jz4.redMul(jyd4);
36688
36689 jx = nx;
36690 jz = nz;
36691 jyd = dny;
36692 }
36693
36694 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
36695};
36696
36697JPoint.prototype.dbl = function dbl() {
36698 if (this.isInfinity())
36699 return this;
36700
36701 if (this.curve.zeroA)
36702 return this._zeroDbl();
36703 else if (this.curve.threeA)
36704 return this._threeDbl();
36705 else
36706 return this._dbl();
36707};
36708
36709JPoint.prototype._zeroDbl = function _zeroDbl() {
36710 var nx;
36711 var ny;
36712 var nz;
36713 // Z = 1
36714 if (this.zOne) {
36715 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
36716 // #doubling-mdbl-2007-bl
36717 // 1M + 5S + 14A
36718
36719 // XX = X1^2
36720 var xx = this.x.redSqr();
36721 // YY = Y1^2
36722 var yy = this.y.redSqr();
36723 // YYYY = YY^2
36724 var yyyy = yy.redSqr();
36725 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
36726 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
36727 s = s.redIAdd(s);
36728 // M = 3 * XX + a; a = 0
36729 var m = xx.redAdd(xx).redIAdd(xx);
36730 // T = M ^ 2 - 2*S
36731 var t = m.redSqr().redISub(s).redISub(s);
36732
36733 // 8 * YYYY
36734 var yyyy8 = yyyy.redIAdd(yyyy);
36735 yyyy8 = yyyy8.redIAdd(yyyy8);
36736 yyyy8 = yyyy8.redIAdd(yyyy8);
36737
36738 // X3 = T
36739 nx = t;
36740 // Y3 = M * (S - T) - 8 * YYYY
36741 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
36742 // Z3 = 2*Y1
36743 nz = this.y.redAdd(this.y);
36744 } else {
36745 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
36746 // #doubling-dbl-2009-l
36747 // 2M + 5S + 13A
36748
36749 // A = X1^2
36750 var a = this.x.redSqr();
36751 // B = Y1^2
36752 var b = this.y.redSqr();
36753 // C = B^2
36754 var c = b.redSqr();
36755 // D = 2 * ((X1 + B)^2 - A - C)
36756 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
36757 d = d.redIAdd(d);
36758 // E = 3 * A
36759 var e = a.redAdd(a).redIAdd(a);
36760 // F = E^2
36761 var f = e.redSqr();
36762
36763 // 8 * C
36764 var c8 = c.redIAdd(c);
36765 c8 = c8.redIAdd(c8);
36766 c8 = c8.redIAdd(c8);
36767
36768 // X3 = F - 2 * D
36769 nx = f.redISub(d).redISub(d);
36770 // Y3 = E * (D - X3) - 8 * C
36771 ny = e.redMul(d.redISub(nx)).redISub(c8);
36772 // Z3 = 2 * Y1 * Z1
36773 nz = this.y.redMul(this.z);
36774 nz = nz.redIAdd(nz);
36775 }
36776
36777 return this.curve.jpoint(nx, ny, nz);
36778};
36779
36780JPoint.prototype._threeDbl = function _threeDbl() {
36781 var nx;
36782 var ny;
36783 var nz;
36784 // Z = 1
36785 if (this.zOne) {
36786 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
36787 // #doubling-mdbl-2007-bl
36788 // 1M + 5S + 15A
36789
36790 // XX = X1^2
36791 var xx = this.x.redSqr();
36792 // YY = Y1^2
36793 var yy = this.y.redSqr();
36794 // YYYY = YY^2
36795 var yyyy = yy.redSqr();
36796 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
36797 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
36798 s = s.redIAdd(s);
36799 // M = 3 * XX + a
36800 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
36801 // T = M^2 - 2 * S
36802 var t = m.redSqr().redISub(s).redISub(s);
36803 // X3 = T
36804 nx = t;
36805 // Y3 = M * (S - T) - 8 * YYYY
36806 var yyyy8 = yyyy.redIAdd(yyyy);
36807 yyyy8 = yyyy8.redIAdd(yyyy8);
36808 yyyy8 = yyyy8.redIAdd(yyyy8);
36809 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
36810 // Z3 = 2 * Y1
36811 nz = this.y.redAdd(this.y);
36812 } else {
36813 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
36814 // 3M + 5S
36815
36816 // delta = Z1^2
36817 var delta = this.z.redSqr();
36818 // gamma = Y1^2
36819 var gamma = this.y.redSqr();
36820 // beta = X1 * gamma
36821 var beta = this.x.redMul(gamma);
36822 // alpha = 3 * (X1 - delta) * (X1 + delta)
36823 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
36824 alpha = alpha.redAdd(alpha).redIAdd(alpha);
36825 // X3 = alpha^2 - 8 * beta
36826 var beta4 = beta.redIAdd(beta);
36827 beta4 = beta4.redIAdd(beta4);
36828 var beta8 = beta4.redAdd(beta4);
36829 nx = alpha.redSqr().redISub(beta8);
36830 // Z3 = (Y1 + Z1)^2 - gamma - delta
36831 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
36832 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
36833 var ggamma8 = gamma.redSqr();
36834 ggamma8 = ggamma8.redIAdd(ggamma8);
36835 ggamma8 = ggamma8.redIAdd(ggamma8);
36836 ggamma8 = ggamma8.redIAdd(ggamma8);
36837 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
36838 }
36839
36840 return this.curve.jpoint(nx, ny, nz);
36841};
36842
36843JPoint.prototype._dbl = function _dbl() {
36844 var a = this.curve.a;
36845
36846 // 4M + 6S + 10A
36847 var jx = this.x;
36848 var jy = this.y;
36849 var jz = this.z;
36850 var jz4 = jz.redSqr().redSqr();
36851
36852 var jx2 = jx.redSqr();
36853 var jy2 = jy.redSqr();
36854
36855 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
36856
36857 var jxd4 = jx.redAdd(jx);
36858 jxd4 = jxd4.redIAdd(jxd4);
36859 var t1 = jxd4.redMul(jy2);
36860 var nx = c.redSqr().redISub(t1.redAdd(t1));
36861 var t2 = t1.redISub(nx);
36862
36863 var jyd8 = jy2.redSqr();
36864 jyd8 = jyd8.redIAdd(jyd8);
36865 jyd8 = jyd8.redIAdd(jyd8);
36866 jyd8 = jyd8.redIAdd(jyd8);
36867 var ny = c.redMul(t2).redISub(jyd8);
36868 var nz = jy.redAdd(jy).redMul(jz);
36869
36870 return this.curve.jpoint(nx, ny, nz);
36871};
36872
36873JPoint.prototype.trpl = function trpl() {
36874 if (!this.curve.zeroA)
36875 return this.dbl().add(this);
36876
36877 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
36878 // 5M + 10S + ...
36879
36880 // XX = X1^2
36881 var xx = this.x.redSqr();
36882 // YY = Y1^2
36883 var yy = this.y.redSqr();
36884 // ZZ = Z1^2
36885 var zz = this.z.redSqr();
36886 // YYYY = YY^2
36887 var yyyy = yy.redSqr();
36888 // M = 3 * XX + a * ZZ2; a = 0
36889 var m = xx.redAdd(xx).redIAdd(xx);
36890 // MM = M^2
36891 var mm = m.redSqr();
36892 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
36893 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
36894 e = e.redIAdd(e);
36895 e = e.redAdd(e).redIAdd(e);
36896 e = e.redISub(mm);
36897 // EE = E^2
36898 var ee = e.redSqr();
36899 // T = 16*YYYY
36900 var t = yyyy.redIAdd(yyyy);
36901 t = t.redIAdd(t);
36902 t = t.redIAdd(t);
36903 t = t.redIAdd(t);
36904 // U = (M + E)^2 - MM - EE - T
36905 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
36906 // X3 = 4 * (X1 * EE - 4 * YY * U)
36907 var yyu4 = yy.redMul(u);
36908 yyu4 = yyu4.redIAdd(yyu4);
36909 yyu4 = yyu4.redIAdd(yyu4);
36910 var nx = this.x.redMul(ee).redISub(yyu4);
36911 nx = nx.redIAdd(nx);
36912 nx = nx.redIAdd(nx);
36913 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
36914 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
36915 ny = ny.redIAdd(ny);
36916 ny = ny.redIAdd(ny);
36917 ny = ny.redIAdd(ny);
36918 // Z3 = (Z1 + E)^2 - ZZ - EE
36919 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
36920
36921 return this.curve.jpoint(nx, ny, nz);
36922};
36923
36924JPoint.prototype.mul = function mul(k, kbase) {
36925 k = new bn(k, kbase);
36926
36927 return this.curve._wnafMul(this, k);
36928};
36929
36930JPoint.prototype.eq = function eq(p) {
36931 if (p.type === 'affine')
36932 return this.eq(p.toJ());
36933
36934 if (this === p)
36935 return true;
36936
36937 // x1 * z2^2 == x2 * z1^2
36938 var z2 = this.z.redSqr();
36939 var pz2 = p.z.redSqr();
36940 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
36941 return false;
36942
36943 // y1 * z2^3 == y2 * z1^3
36944 var z3 = z2.redMul(this.z);
36945 var pz3 = pz2.redMul(p.z);
36946 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
36947};
36948
36949JPoint.prototype.inspect = function inspect() {
36950 if (this.isInfinity())
36951 return '<EC JPoint Infinity>';
36952 return '<EC JPoint x: ' + this.x.toString(16, 2) +
36953 ' y: ' + this.y.toString(16, 2) +
36954 ' z: ' + this.z.toString(16, 2) + '>';
36955};
36956
36957JPoint.prototype.isInfinity = function isInfinity() {
36958 // XXX This code assumes that zero is always zero in red
36959 return this.z.cmpn(0) === 0;
36960};
36961}, {"../curve":217,"../../elliptic":206,"bn.js":204,"inherits":149}],220: [function (exports, require, module, global) {'use strict';
36962
36963var curve = require('../curve');
36964var bn = require('bn.js');
36965var inherits = require('inherits');
36966var Base = curve.base;
36967
36968function MontCurve(conf) {
36969 Base.call(this, 'mont', conf);
36970
36971 this.a = new bn(conf.a, 16).toRed(this.red);
36972 this.b = new bn(conf.b, 16).toRed(this.red);
36973 this.i4 = new bn(4).toRed(this.red).redInvm();
36974 this.two = new bn(2).toRed(this.red);
36975 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
36976}
36977inherits(MontCurve, Base);
36978module.exports = MontCurve;
36979
36980MontCurve.prototype.validate = function validate(point) {
36981 var x = point.normalize().x;
36982 var x2 = x.redSqr();
36983 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
36984 var y = rhs.redSqrt();
36985
36986 return y.redSqr().cmp(rhs) === 0;
36987};
36988
36989function Point(curve, x, z) {
36990 Base.BasePoint.call(this, curve, 'projective');
36991 if (x === null && z === null) {
36992 this.x = this.curve.one;
36993 this.z = this.curve.zero;
36994 } else {
36995 this.x = new bn(x, 16);
36996 this.z = new bn(z, 16);
36997 if (!this.x.red)
36998 this.x = this.x.toRed(this.curve.red);
36999 if (!this.z.red)
37000 this.z = this.z.toRed(this.curve.red);
37001 }
37002}
37003inherits(Point, Base.BasePoint);
37004
37005MontCurve.prototype.point = function point(x, z) {
37006 return new Point(this, x, z);
37007};
37008
37009MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
37010 return Point.fromJSON(this, obj);
37011};
37012
37013Point.prototype.precompute = function precompute() {
37014 // No-op
37015};
37016
37017Point.fromJSON = function fromJSON(curve, obj) {
37018 return new Point(curve, obj[0], obj[1] || curve.one);
37019};
37020
37021Point.prototype.inspect = function inspect() {
37022 if (this.isInfinity())
37023 return '<EC Point Infinity>';
37024 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
37025 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
37026};
37027
37028Point.prototype.isInfinity = function isInfinity() {
37029 // XXX This code assumes that zero is always zero in red
37030 return this.z.cmpn(0) === 0;
37031};
37032
37033Point.prototype.dbl = function dbl() {
37034 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
37035 // 2M + 2S + 4A
37036
37037 // A = X1 + Z1
37038 var a = this.x.redAdd(this.z);
37039 // AA = A^2
37040 var aa = a.redSqr();
37041 // B = X1 - Z1
37042 var b = this.x.redSub(this.z);
37043 // BB = B^2
37044 var bb = b.redSqr();
37045 // C = AA - BB
37046 var c = aa.redSub(bb);
37047 // X3 = AA * BB
37048 var nx = aa.redMul(bb);
37049 // Z3 = C * (BB + A24 * C)
37050 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
37051 return this.curve.point(nx, nz);
37052};
37053
37054Point.prototype.add = function add() {
37055 throw new Error('Not supported on Montgomery curve');
37056};
37057
37058Point.prototype.diffAdd = function diffAdd(p, diff) {
37059 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
37060 // 4M + 2S + 6A
37061
37062 // A = X2 + Z2
37063 var a = this.x.redAdd(this.z);
37064 // B = X2 - Z2
37065 var b = this.x.redSub(this.z);
37066 // C = X3 + Z3
37067 var c = p.x.redAdd(p.z);
37068 // D = X3 - Z3
37069 var d = p.x.redSub(p.z);
37070 // DA = D * A
37071 var da = d.redMul(a);
37072 // CB = C * B
37073 var cb = c.redMul(b);
37074 // X5 = Z1 * (DA + CB)^2
37075 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
37076 // Z5 = X1 * (DA - CB)^2
37077 var nz = diff.x.redMul(da.redISub(cb).redSqr());
37078 return this.curve.point(nx, nz);
37079};
37080
37081Point.prototype.mul = function mul(k) {
37082 var t = k.clone();
37083 var a = this; // (N / 2) * Q + Q
37084 var b = this.curve.point(null, null); // (N / 2) * Q
37085 var c = this; // Q
37086
37087 for (var bits = []; t.cmpn(0) !== 0; t.ishrn(1))
37088 bits.push(t.andln(1));
37089
37090 for (var i = bits.length - 1; i >= 0; i--) {
37091 if (bits[i] === 0) {
37092 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
37093 a = a.diffAdd(b, c);
37094 // N * Q = 2 * ((N / 2) * Q + Q))
37095 b = b.dbl();
37096 } else {
37097 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
37098 b = a.diffAdd(b, c);
37099 // N * Q + Q = 2 * ((N / 2) * Q + Q)
37100 a = a.dbl();
37101 }
37102 }
37103 return b;
37104};
37105
37106Point.prototype.mulAdd = function mulAdd() {
37107 throw new Error('Not supported on Montgomery curve');
37108};
37109
37110Point.prototype.normalize = function normalize() {
37111 this.x = this.x.redMul(this.z.redInvm());
37112 this.z = this.curve.one;
37113 return this;
37114};
37115
37116Point.prototype.getX = function getX() {
37117 // Normalize coordinates
37118 this.normalize();
37119
37120 return this.x.fromRed();
37121};
37122}, {"../curve":217,"bn.js":204,"inherits":149}],221: [function (exports, require, module, global) {'use strict';
37123
37124var curve = require('../curve');
37125var elliptic = require('../../elliptic');
37126var bn = require('bn.js');
37127var inherits = require('inherits');
37128var Base = curve.base;
37129
37130var assert = elliptic.utils.assert;
37131
37132function EdwardsCurve(conf) {
37133 // NOTE: Important as we are creating point in Base.call()
37134 this.twisted = (conf.a | 0) !== 1;
37135 this.mOneA = this.twisted && (conf.a | 0) === -1;
37136 this.extended = this.mOneA;
37137
37138 Base.call(this, 'edwards', conf);
37139
37140 this.a = new bn(conf.a, 16).mod(this.red.m).toRed(this.red);
37141 this.c = new bn(conf.c, 16).toRed(this.red);
37142 this.c2 = this.c.redSqr();
37143 this.d = new bn(conf.d, 16).toRed(this.red);
37144 this.dd = this.d.redAdd(this.d);
37145
37146 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
37147 this.oneC = (conf.c | 0) === 1;
37148}
37149inherits(EdwardsCurve, Base);
37150module.exports = EdwardsCurve;
37151
37152EdwardsCurve.prototype._mulA = function _mulA(num) {
37153 if (this.mOneA)
37154 return num.redNeg();
37155 else
37156 return this.a.redMul(num);
37157};
37158
37159EdwardsCurve.prototype._mulC = function _mulC(num) {
37160 if (this.oneC)
37161 return num;
37162 else
37163 return this.c.redMul(num);
37164};
37165
37166// Just for compatibility with Short curve
37167EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
37168 return this.point(x, y, z, t);
37169};
37170
37171EdwardsCurve.prototype.pointFromX = function pointFromX(odd, x) {
37172 x = new bn(x, 16);
37173 if (!x.red)
37174 x = x.toRed(this.red);
37175
37176 var x2 = x.redSqr();
37177 var rhs = this.c2.redSub(this.a.redMul(x2));
37178 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
37179
37180 var y = rhs.redMul(lhs.redInvm()).redSqrt();
37181 var isOdd = y.fromRed().isOdd();
37182 if (odd && !isOdd || !odd && isOdd)
37183 y = y.redNeg();
37184
37185 return this.point(x, y, curve.one);
37186};
37187
37188EdwardsCurve.prototype.validate = function validate(point) {
37189 if (point.isInfinity())
37190 return true;
37191
37192 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
37193 point.normalize();
37194
37195 var x2 = point.x.redSqr();
37196 var y2 = point.y.redSqr();
37197 var lhs = x2.redMul(this.a).redAdd(y2);
37198 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
37199
37200 return lhs.cmp(rhs) === 0;
37201};
37202
37203function Point(curve, x, y, z, t) {
37204 Base.BasePoint.call(this, curve, 'projective');
37205 if (x === null && y === null && z === null) {
37206 this.x = this.curve.zero;
37207 this.y = this.curve.one;
37208 this.z = this.curve.one;
37209 this.t = this.curve.zero;
37210 this.zOne = true;
37211 } else {
37212 this.x = new bn(x, 16);
37213 this.y = new bn(y, 16);
37214 this.z = z ? new bn(z, 16) : this.curve.one;
37215 this.t = t && new bn(t, 16);
37216 if (!this.x.red)
37217 this.x = this.x.toRed(this.curve.red);
37218 if (!this.y.red)
37219 this.y = this.y.toRed(this.curve.red);
37220 if (!this.z.red)
37221 this.z = this.z.toRed(this.curve.red);
37222 if (this.t && !this.t.red)
37223 this.t = this.t.toRed(this.curve.red);
37224 this.zOne = this.z === this.curve.one;
37225
37226 // Use extended coordinates
37227 if (this.curve.extended && !this.t) {
37228 this.t = this.x.redMul(this.y);
37229 if (!this.zOne)
37230 this.t = this.t.redMul(this.z.redInvm());
37231 }
37232 }
37233}
37234inherits(Point, Base.BasePoint);
37235
37236EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
37237 return Point.fromJSON(this, obj);
37238};
37239
37240EdwardsCurve.prototype.point = function point(x, y, z, t) {
37241 return new Point(this, x, y, z, t);
37242};
37243
37244Point.fromJSON = function fromJSON(curve, obj) {
37245 return new Point(curve, obj[0], obj[1], obj[2]);
37246};
37247
37248Point.prototype.inspect = function inspect() {
37249 if (this.isInfinity())
37250 return '<EC Point Infinity>';
37251 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
37252 ' y: ' + this.y.fromRed().toString(16, 2) +
37253 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
37254};
37255
37256Point.prototype.isInfinity = function isInfinity() {
37257 // XXX This code assumes that zero is always zero in red
37258 return this.x.cmpn(0) === 0 &&
37259 this.y.cmp(this.z) === 0;
37260};
37261
37262Point.prototype._extDbl = function _extDbl() {
37263 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
37264 // #doubling-dbl-2008-hwcd
37265 // 4M + 4S
37266
37267 // A = X1^2
37268 var a = this.x.redSqr();
37269 // B = Y1^2
37270 var b = this.y.redSqr();
37271 // C = 2 * Z1^2
37272 var c = this.z.redSqr();
37273 c = c.redIAdd(c);
37274 // D = a * A
37275 var d = this.curve._mulA(a);
37276 // E = (X1 + Y1)^2 - A - B
37277 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
37278 // G = D + B
37279 var g = d.redAdd(b);
37280 // F = G - C
37281 var f = g.redSub(c);
37282 // H = D - B
37283 var h = d.redSub(b);
37284 // X3 = E * F
37285 var nx = e.redMul(f);
37286 // Y3 = G * H
37287 var ny = g.redMul(h);
37288 // T3 = E * H
37289 var nt = e.redMul(h);
37290 // Z3 = F * G
37291 var nz = f.redMul(g);
37292 return this.curve.point(nx, ny, nz, nt);
37293};
37294
37295Point.prototype._projDbl = function _projDbl() {
37296 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
37297 // #doubling-dbl-2008-bbjlp
37298 // #doubling-dbl-2007-bl
37299 // and others
37300 // Generally 3M + 4S or 2M + 4S
37301
37302 // B = (X1 + Y1)^2
37303 var b = this.x.redAdd(this.y).redSqr();
37304 // C = X1^2
37305 var c = this.x.redSqr();
37306 // D = Y1^2
37307 var d = this.y.redSqr();
37308
37309 var nx;
37310 var ny;
37311 var nz;
37312 if (this.curve.twisted) {
37313 // E = a * C
37314 var e = this.curve._mulA(c);
37315 // F = E + D
37316 var f = e.redAdd(d);
37317 if (this.zOne) {
37318 // X3 = (B - C - D) * (F - 2)
37319 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
37320 // Y3 = F * (E - D)
37321 ny = f.redMul(e.redSub(d));
37322 // Z3 = F^2 - 2 * F
37323 nz = f.redSqr().redSub(f).redSub(f);
37324 } else {
37325 // H = Z1^2
37326 var h = this.z.redSqr();
37327 // J = F - 2 * H
37328 var j = f.redSub(h).redISub(h);
37329 // X3 = (B-C-D)*J
37330 nx = b.redSub(c).redISub(d).redMul(j);
37331 // Y3 = F * (E - D)
37332 ny = f.redMul(e.redSub(d));
37333 // Z3 = F * J
37334 nz = f.redMul(j);
37335 }
37336 } else {
37337 // E = C + D
37338 var e = c.redAdd(d);
37339 // H = (c * Z1)^2
37340 var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
37341 // J = E - 2 * H
37342 var j = e.redSub(h).redSub(h);
37343 // X3 = c * (B - E) * J
37344 nx = this.curve._mulC(b.redISub(e)).redMul(j);
37345 // Y3 = c * E * (C - D)
37346 ny = this.curve._mulC(e).redMul(c.redISub(d));
37347 // Z3 = E * J
37348 nz = e.redMul(j);
37349 }
37350 return this.curve.point(nx, ny, nz);
37351};
37352
37353Point.prototype.dbl = function dbl() {
37354 if (this.isInfinity())
37355 return this;
37356
37357 // Double in extended coordinates
37358 if (this.curve.extended)
37359 return this._extDbl();
37360 else
37361 return this._projDbl();
37362};
37363
37364Point.prototype._extAdd = function _extAdd(p) {
37365 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
37366 // #addition-add-2008-hwcd-3
37367 // 8M
37368
37369 // A = (Y1 - X1) * (Y2 - X2)
37370 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
37371 // B = (Y1 + X1) * (Y2 + X2)
37372 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
37373 // C = T1 * k * T2
37374 var c = this.t.redMul(this.curve.dd).redMul(p.t);
37375 // D = Z1 * 2 * Z2
37376 var d = this.z.redMul(p.z.redAdd(p.z));
37377 // E = B - A
37378 var e = b.redSub(a);
37379 // F = D - C
37380 var f = d.redSub(c);
37381 // G = D + C
37382 var g = d.redAdd(c);
37383 // H = B + A
37384 var h = b.redAdd(a);
37385 // X3 = E * F
37386 var nx = e.redMul(f);
37387 // Y3 = G * H
37388 var ny = g.redMul(h);
37389 // T3 = E * H
37390 var nt = e.redMul(h);
37391 // Z3 = F * G
37392 var nz = f.redMul(g);
37393 return this.curve.point(nx, ny, nz, nt);
37394};
37395
37396Point.prototype._projAdd = function _projAdd(p) {
37397 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
37398 // #addition-add-2008-bbjlp
37399 // #addition-add-2007-bl
37400 // 10M + 1S
37401
37402 // A = Z1 * Z2
37403 var a = this.z.redMul(p.z);
37404 // B = A^2
37405 var b = a.redSqr();
37406 // C = X1 * X2
37407 var c = this.x.redMul(p.x);
37408 // D = Y1 * Y2
37409 var d = this.y.redMul(p.y);
37410 // E = d * C * D
37411 var e = this.curve.d.redMul(c).redMul(d);
37412 // F = B - E
37413 var f = b.redSub(e);
37414 // G = B + E
37415 var g = b.redAdd(e);
37416 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
37417 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
37418 var nx = a.redMul(f).redMul(tmp);
37419 var ny;
37420 var nz;
37421 if (this.curve.twisted) {
37422 // Y3 = A * G * (D - a * C)
37423 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
37424 // Z3 = F * G
37425 nz = f.redMul(g);
37426 } else {
37427 // Y3 = A * G * (D - C)
37428 ny = a.redMul(g).redMul(d.redSub(c));
37429 // Z3 = c * F * G
37430 nz = this.curve._mulC(f).redMul(g);
37431 }
37432 return this.curve.point(nx, ny, nz);
37433};
37434
37435Point.prototype.add = function add(p) {
37436 if (this.isInfinity())
37437 return p;
37438 if (p.isInfinity())
37439 return this;
37440
37441 if (this.curve.extended)
37442 return this._extAdd(p);
37443 else
37444 return this._projAdd(p);
37445};
37446
37447Point.prototype.mul = function mul(k) {
37448 if (this._hasDoubles(k))
37449 return this.curve._fixedNafMul(this, k);
37450 else
37451 return this.curve._wnafMul(this, k);
37452};
37453
37454Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
37455 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2);
37456};
37457
37458Point.prototype.normalize = function normalize() {
37459 if (this.zOne)
37460 return this;
37461
37462 // Normalize coordinates
37463 var zi = this.z.redInvm();
37464 this.x = this.x.redMul(zi);
37465 this.y = this.y.redMul(zi);
37466 if (this.t)
37467 this.t = this.t.redMul(zi);
37468 this.z = this.curve.one;
37469 this.zOne = true;
37470 return this;
37471};
37472
37473Point.prototype.neg = function neg() {
37474 return this.curve.point(this.x.redNeg(),
37475 this.y,
37476 this.z,
37477 this.t && this.t.redNeg());
37478};
37479
37480Point.prototype.getX = function getX() {
37481 this.normalize();
37482 return this.x.fromRed();
37483};
37484
37485Point.prototype.getY = function getY() {
37486 this.normalize();
37487 return this.y.fromRed();
37488};
37489
37490// Compatibility with BaseCurve
37491Point.prototype.toP = Point.prototype.normalize;
37492Point.prototype.mixedAdd = Point.prototype.add;
37493}, {"../curve":217,"../../elliptic":206,"bn.js":204,"inherits":149}],222: [function (exports, require, module, global) {'use strict';
37494
37495var curves = exports;
37496
37497var hash = require('hash.js');
37498var elliptic = require('../elliptic');
37499
37500var assert = elliptic.utils.assert;
37501
37502function PresetCurve(options) {
37503 if (options.type === 'short')
37504 this.curve = new elliptic.curve.short(options);
37505 else if (options.type === 'edwards')
37506 this.curve = new elliptic.curve.edwards(options);
37507 else
37508 this.curve = new elliptic.curve.mont(options);
37509 this.g = this.curve.g;
37510 this.n = this.curve.n;
37511 this.hash = options.hash;
37512
37513 assert(this.g.validate(), 'Invalid curve');
37514 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
37515}
37516curves.PresetCurve = PresetCurve;
37517
37518function defineCurve(name, options) {
37519 Object.defineProperty(curves, name, {
37520 configurable: true,
37521 enumerable: true,
37522 get: function() {
37523 var curve = new PresetCurve(options);
37524 Object.defineProperty(curves, name, {
37525 configurable: true,
37526 enumerable: true,
37527 value: curve
37528 });
37529 return curve;
37530 }
37531 });
37532}
37533
37534defineCurve('p192', {
37535 type: 'short',
37536 prime: 'p192',
37537 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
37538 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
37539 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
37540 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
37541 hash: hash.sha256,
37542 gRed: false,
37543 g: [
37544 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
37545 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
37546 ]
37547});
37548
37549defineCurve('p224', {
37550 type: 'short',
37551 prime: 'p224',
37552 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
37553 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
37554 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
37555 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
37556 hash: hash.sha256,
37557 gRed: false,
37558 g: [
37559 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
37560 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
37561 ]
37562});
37563
37564defineCurve('p256', {
37565 type: 'short',
37566 prime: null,
37567 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
37568 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
37569 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
37570 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
37571 hash: hash.sha256,
37572 gRed: false,
37573 g: [
37574 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
37575 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
37576 ]
37577});
37578
37579defineCurve('curve25519', {
37580 type: 'mont',
37581 prime: 'p25519',
37582 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
37583 a: '76d06',
37584 b: '0',
37585 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
37586 hash: hash.sha256,
37587 gRed: false,
37588 g: [
37589 '9'
37590 ]
37591});
37592
37593defineCurve('ed25519', {
37594 type: 'edwards',
37595 prime: 'p25519',
37596 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
37597 a: '-1',
37598 c: '1',
37599 // -121665 * (121666^(-1)) (mod P)
37600 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
37601 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
37602 hash: hash.sha256,
37603 gRed: false,
37604 g: [
37605 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
37606
37607 // 4/5
37608 '6666666666666666666666666666666666666666666666666666666666666658'
37609 ]
37610});
37611
37612var pre;
37613try {
37614 pre = require('./precomputed/secp256k1');
37615} catch (e) {
37616 pre = undefined;
37617}
37618
37619defineCurve('secp256k1', {
37620 type: 'short',
37621 prime: 'k256',
37622 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
37623 a: '0',
37624 b: '7',
37625 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
37626 h: '1',
37627 hash: hash.sha256,
37628
37629 // Precomputed endomorphism
37630 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
37631 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
37632 basis: [
37633 {
37634 a: '3086d221a7d46bcde86c90e49284eb15',
37635 b: '-e4437ed6010e88286f547fa90abfe4c3'
37636 },
37637 {
37638 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
37639 b: '3086d221a7d46bcde86c90e49284eb15'
37640 }
37641 ],
37642
37643 gRed: false,
37644 g: [
37645 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
37646 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
37647 pre
37648 ]
37649});
37650}, {"hash.js":211,"../elliptic":206,"./precomputed/secp256k1":223}],223: [function (exports, require, module, global) {module.exports = {
37651 doubles: {
37652 step: 4,
37653 points: [
37654 [
37655 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
37656 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
37657 ],
37658 [
37659 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
37660 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
37661 ],
37662 [
37663 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
37664 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
37665 ],
37666 [
37667 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
37668 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
37669 ],
37670 [
37671 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
37672 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
37673 ],
37674 [
37675 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
37676 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
37677 ],
37678 [
37679 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
37680 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
37681 ],
37682 [
37683 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
37684 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
37685 ],
37686 [
37687 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
37688 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
37689 ],
37690 [
37691 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
37692 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
37693 ],
37694 [
37695 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
37696 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
37697 ],
37698 [
37699 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
37700 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
37701 ],
37702 [
37703 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
37704 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
37705 ],
37706 [
37707 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
37708 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
37709 ],
37710 [
37711 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
37712 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
37713 ],
37714 [
37715 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
37716 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
37717 ],
37718 [
37719 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
37720 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
37721 ],
37722 [
37723 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
37724 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
37725 ],
37726 [
37727 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
37728 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
37729 ],
37730 [
37731 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
37732 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
37733 ],
37734 [
37735 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
37736 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
37737 ],
37738 [
37739 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
37740 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
37741 ],
37742 [
37743 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
37744 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
37745 ],
37746 [
37747 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
37748 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
37749 ],
37750 [
37751 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
37752 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
37753 ],
37754 [
37755 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
37756 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
37757 ],
37758 [
37759 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
37760 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
37761 ],
37762 [
37763 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
37764 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
37765 ],
37766 [
37767 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
37768 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
37769 ],
37770 [
37771 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
37772 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
37773 ],
37774 [
37775 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
37776 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
37777 ],
37778 [
37779 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
37780 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
37781 ],
37782 [
37783 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
37784 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
37785 ],
37786 [
37787 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
37788 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
37789 ],
37790 [
37791 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
37792 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
37793 ],
37794 [
37795 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
37796 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
37797 ],
37798 [
37799 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
37800 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
37801 ],
37802 [
37803 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
37804 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
37805 ],
37806 [
37807 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
37808 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
37809 ],
37810 [
37811 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
37812 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
37813 ],
37814 [
37815 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
37816 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
37817 ],
37818 [
37819 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
37820 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
37821 ],
37822 [
37823 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
37824 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
37825 ],
37826 [
37827 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
37828 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
37829 ],
37830 [
37831 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
37832 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
37833 ],
37834 [
37835 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
37836 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
37837 ],
37838 [
37839 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
37840 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
37841 ],
37842 [
37843 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
37844 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
37845 ],
37846 [
37847 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
37848 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
37849 ],
37850 [
37851 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
37852 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
37853 ],
37854 [
37855 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
37856 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
37857 ],
37858 [
37859 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
37860 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
37861 ],
37862 [
37863 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
37864 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
37865 ],
37866 [
37867 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
37868 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
37869 ],
37870 [
37871 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
37872 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
37873 ],
37874 [
37875 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
37876 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
37877 ],
37878 [
37879 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
37880 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
37881 ],
37882 [
37883 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
37884 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
37885 ],
37886 [
37887 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
37888 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
37889 ],
37890 [
37891 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
37892 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
37893 ],
37894 [
37895 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
37896 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
37897 ],
37898 [
37899 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
37900 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
37901 ],
37902 [
37903 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
37904 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
37905 ],
37906 [
37907 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
37908 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
37909 ],
37910 [
37911 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
37912 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
37913 ]
37914 ]
37915 },
37916 naf: {
37917 wnd: 7,
37918 points: [
37919 [
37920 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
37921 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
37922 ],
37923 [
37924 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
37925 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
37926 ],
37927 [
37928 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
37929 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
37930 ],
37931 [
37932 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
37933 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
37934 ],
37935 [
37936 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
37937 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
37938 ],
37939 [
37940 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
37941 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
37942 ],
37943 [
37944 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
37945 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
37946 ],
37947 [
37948 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
37949 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
37950 ],
37951 [
37952 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
37953 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
37954 ],
37955 [
37956 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
37957 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
37958 ],
37959 [
37960 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
37961 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
37962 ],
37963 [
37964 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
37965 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
37966 ],
37967 [
37968 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
37969 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
37970 ],
37971 [
37972 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
37973 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
37974 ],
37975 [
37976 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
37977 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
37978 ],
37979 [
37980 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
37981 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
37982 ],
37983 [
37984 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
37985 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
37986 ],
37987 [
37988 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
37989 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
37990 ],
37991 [
37992 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
37993 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
37994 ],
37995 [
37996 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
37997 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
37998 ],
37999 [
38000 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
38001 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
38002 ],
38003 [
38004 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
38005 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
38006 ],
38007 [
38008 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
38009 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
38010 ],
38011 [
38012 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
38013 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
38014 ],
38015 [
38016 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
38017 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
38018 ],
38019 [
38020 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
38021 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
38022 ],
38023 [
38024 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
38025 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
38026 ],
38027 [
38028 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
38029 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
38030 ],
38031 [
38032 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
38033 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
38034 ],
38035 [
38036 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
38037 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
38038 ],
38039 [
38040 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
38041 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
38042 ],
38043 [
38044 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
38045 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
38046 ],
38047 [
38048 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
38049 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
38050 ],
38051 [
38052 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
38053 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
38054 ],
38055 [
38056 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
38057 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
38058 ],
38059 [
38060 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
38061 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
38062 ],
38063 [
38064 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
38065 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
38066 ],
38067 [
38068 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
38069 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
38070 ],
38071 [
38072 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
38073 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
38074 ],
38075 [
38076 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
38077 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
38078 ],
38079 [
38080 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
38081 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
38082 ],
38083 [
38084 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
38085 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
38086 ],
38087 [
38088 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
38089 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
38090 ],
38091 [
38092 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
38093 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
38094 ],
38095 [
38096 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
38097 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
38098 ],
38099 [
38100 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
38101 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
38102 ],
38103 [
38104 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
38105 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
38106 ],
38107 [
38108 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
38109 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
38110 ],
38111 [
38112 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
38113 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
38114 ],
38115 [
38116 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
38117 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
38118 ],
38119 [
38120 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
38121 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
38122 ],
38123 [
38124 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
38125 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
38126 ],
38127 [
38128 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
38129 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
38130 ],
38131 [
38132 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
38133 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
38134 ],
38135 [
38136 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
38137 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
38138 ],
38139 [
38140 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
38141 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
38142 ],
38143 [
38144 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
38145 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
38146 ],
38147 [
38148 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
38149 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
38150 ],
38151 [
38152 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
38153 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
38154 ],
38155 [
38156 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
38157 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
38158 ],
38159 [
38160 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
38161 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
38162 ],
38163 [
38164 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
38165 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
38166 ],
38167 [
38168 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
38169 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
38170 ],
38171 [
38172 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
38173 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
38174 ],
38175 [
38176 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
38177 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
38178 ],
38179 [
38180 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
38181 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
38182 ],
38183 [
38184 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
38185 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
38186 ],
38187 [
38188 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
38189 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
38190 ],
38191 [
38192 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
38193 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
38194 ],
38195 [
38196 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
38197 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
38198 ],
38199 [
38200 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
38201 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
38202 ],
38203 [
38204 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
38205 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
38206 ],
38207 [
38208 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
38209 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
38210 ],
38211 [
38212 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
38213 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
38214 ],
38215 [
38216 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
38217 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
38218 ],
38219 [
38220 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
38221 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
38222 ],
38223 [
38224 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
38225 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
38226 ],
38227 [
38228 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
38229 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
38230 ],
38231 [
38232 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
38233 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
38234 ],
38235 [
38236 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
38237 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
38238 ],
38239 [
38240 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
38241 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
38242 ],
38243 [
38244 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
38245 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
38246 ],
38247 [
38248 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
38249 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
38250 ],
38251 [
38252 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
38253 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
38254 ],
38255 [
38256 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
38257 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
38258 ],
38259 [
38260 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
38261 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
38262 ],
38263 [
38264 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
38265 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
38266 ],
38267 [
38268 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
38269 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
38270 ],
38271 [
38272 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
38273 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
38274 ],
38275 [
38276 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
38277 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
38278 ],
38279 [
38280 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
38281 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
38282 ],
38283 [
38284 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
38285 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
38286 ],
38287 [
38288 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
38289 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
38290 ],
38291 [
38292 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
38293 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
38294 ],
38295 [
38296 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
38297 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
38298 ],
38299 [
38300 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
38301 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
38302 ],
38303 [
38304 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
38305 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
38306 ],
38307 [
38308 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
38309 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
38310 ],
38311 [
38312 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
38313 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
38314 ],
38315 [
38316 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
38317 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
38318 ],
38319 [
38320 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
38321 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
38322 ],
38323 [
38324 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
38325 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
38326 ],
38327 [
38328 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
38329 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
38330 ],
38331 [
38332 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
38333 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
38334 ],
38335 [
38336 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
38337 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
38338 ],
38339 [
38340 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
38341 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
38342 ],
38343 [
38344 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
38345 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
38346 ],
38347 [
38348 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
38349 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
38350 ],
38351 [
38352 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
38353 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
38354 ],
38355 [
38356 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
38357 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
38358 ],
38359 [
38360 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
38361 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
38362 ],
38363 [
38364 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
38365 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
38366 ],
38367 [
38368 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
38369 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
38370 ],
38371 [
38372 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
38373 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
38374 ],
38375 [
38376 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
38377 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
38378 ],
38379 [
38380 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
38381 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
38382 ],
38383 [
38384 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
38385 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
38386 ],
38387 [
38388 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
38389 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
38390 ],
38391 [
38392 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
38393 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
38394 ],
38395 [
38396 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
38397 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
38398 ],
38399 [
38400 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
38401 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
38402 ],
38403 [
38404 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
38405 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
38406 ],
38407 [
38408 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
38409 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
38410 ],
38411 [
38412 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
38413 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
38414 ],
38415 [
38416 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
38417 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
38418 ],
38419 [
38420 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
38421 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
38422 ],
38423 [
38424 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
38425 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
38426 ]
38427 ]
38428 }
38429};
38430}, {}],224: [function (exports, require, module, global) {'use strict';
38431
38432var bn = require('bn.js');
38433var elliptic = require('../../elliptic');
38434var utils = elliptic.utils;
38435var assert = utils.assert;
38436
38437var KeyPair = require('./key');
38438var Signature = require('./signature');
38439
38440function EC(options) {
38441 if (!(this instanceof EC))
38442 return new EC(options);
38443
38444 // Shortcut `elliptic.ec(curve-name)`
38445 if (typeof options === 'string') {
38446 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
38447
38448 options = elliptic.curves[options];
38449 }
38450
38451 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
38452 if (options instanceof elliptic.curves.PresetCurve)
38453 options = { curve: options };
38454
38455 this.curve = options.curve.curve;
38456 this.n = this.curve.n;
38457 this.nh = this.n.shrn(1);
38458 this.g = this.curve.g;
38459
38460 // Point on curve
38461 this.g = options.curve.g;
38462 this.g.precompute(options.curve.n.bitLength() + 1);
38463
38464 // Hash for function for DRBG
38465 this.hash = options.hash || options.curve.hash;
38466}
38467module.exports = EC;
38468
38469EC.prototype.keyPair = function keyPair(options) {
38470 return new KeyPair(this, options);
38471};
38472
38473EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
38474 return KeyPair.fromPrivate(this, priv, enc);
38475};
38476
38477EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
38478 return KeyPair.fromPublic(this, pub, enc);
38479};
38480
38481EC.prototype.genKeyPair = function genKeyPair(options) {
38482 if (!options)
38483 options = {};
38484
38485 // Instantiate Hmac_DRBG
38486 var drbg = new elliptic.hmacDRBG({
38487 hash: this.hash,
38488 pers: options.pers,
38489 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
38490 nonce: this.n.toArray()
38491 });
38492
38493 var bytes = this.n.byteLength();
38494 var ns2 = this.n.sub(new bn(2));
38495 do {
38496 var priv = new bn(drbg.generate(bytes));
38497 if (priv.cmp(ns2) > 0)
38498 continue;
38499
38500 priv.iaddn(1);
38501 return this.keyFromPrivate(priv);
38502 } while (true);
38503};
38504
38505EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
38506 var delta = msg.byteLength() * 8 - this.n.bitLength();
38507 if (delta > 0)
38508 msg = msg.shrn(delta);
38509 if (!truncOnly && msg.cmp(this.n) >= 0)
38510 return msg.sub(this.n);
38511 else
38512 return msg;
38513};
38514
38515EC.prototype.sign = function sign(msg, key, enc, options) {
38516 if (typeof enc === 'object') {
38517 options = enc;
38518 enc = null;
38519 }
38520 if (!options)
38521 options = {};
38522
38523 key = this.keyFromPrivate(key, enc);
38524 msg = this._truncateToN(new bn(msg, 16));
38525
38526 // Zero-extend key to provide enough entropy
38527 var bytes = this.n.byteLength();
38528 var bkey = key.getPrivate().toArray();
38529 for (var i = bkey.length; i < 21; i++)
38530 bkey.unshift(0);
38531
38532 // Zero-extend nonce to have the same byte size as N
38533 var nonce = msg.toArray();
38534 for (var i = nonce.length; i < bytes; i++)
38535 nonce.unshift(0);
38536
38537 // Instantiate Hmac_DRBG
38538 var drbg = new elliptic.hmacDRBG({
38539 hash: this.hash,
38540 entropy: bkey,
38541 nonce: nonce
38542 });
38543
38544 // Number of bytes to generate
38545 var ns1 = this.n.sub(new bn(1));
38546 do {
38547 var k = new bn(drbg.generate(this.n.byteLength()));
38548 k = this._truncateToN(k, true);
38549 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
38550 continue;
38551
38552 var kp = this.g.mul(k);
38553 if (kp.isInfinity())
38554 continue;
38555
38556 var kpX = kp.getX();
38557 var r = kpX.mod(this.n);
38558 if (r.cmpn(0) === 0)
38559 continue;
38560
38561 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)).mod(this.n);
38562 if (s.cmpn(0) === 0)
38563 continue;
38564
38565 // Use complement of `s`, if it is > `n / 2`
38566 if (options.canonical && s.cmp(this.nh) > 0)
38567 s = this.n.sub(s);
38568
38569 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
38570 (kpX.cmp(r) !== 0 ? 2 : 0);
38571
38572 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
38573 } while (true);
38574};
38575
38576EC.prototype.verify = function verify(msg, signature, key, enc) {
38577 msg = this._truncateToN(new bn(msg, 16));
38578 key = this.keyFromPublic(key, enc);
38579 signature = new Signature(signature, 'hex');
38580
38581 // Perform primitive values validation
38582 var r = signature.r;
38583 var s = signature.s;
38584 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
38585 return false;
38586 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
38587 return false;
38588
38589 // Validate signature
38590 var sinv = s.invm(this.n);
38591 var u1 = sinv.mul(msg).mod(this.n);
38592 var u2 = sinv.mul(r).mod(this.n);
38593
38594 var p = this.g.mulAdd(u1, key.getPublic(), u2);
38595 if (p.isInfinity())
38596 return false;
38597
38598 return p.getX().mod(this.n).cmp(r) === 0;
38599};
38600
38601EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
38602 assert((3 & j) === j, 'The recovery param is more than two bits');
38603 signature = new Signature(signature, enc);
38604
38605 var n = this.n;
38606 var e = new bn(msg);
38607 var r = signature.r;
38608 var s = signature.s;
38609
38610 // A set LSB signifies that the y-coordinate is odd
38611 var isYOdd = j & 1;
38612 var isSecondKey = j >> 1;
38613 if (r.cmp(this.curve.p.mod(this.curve.n)) >= 0 && isSecondKey)
38614 throw new Error('Unable to find sencond key candinate');
38615
38616 // 1.1. Let x = r + jn.
38617 r = this.curve.pointFromX(isYOdd, r);
38618 var eNeg = e.neg().mod(n);
38619
38620 // 1.6.1 Compute Q = r^-1 (sR - eG)
38621 // Q = r^-1 (sR + -eG)
38622 var rInv = signature.r.invm(n);
38623 return r.mul(s).add(this.g.mul(eNeg)).mul(rInv);
38624};
38625
38626EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
38627 signature = new Signature(signature, enc);
38628 if (signature.recoveryParam !== null)
38629 return signature.recoveryParam;
38630
38631 for (var i = 0; i < 4; i++) {
38632 var Qprime = this.recoverPubKey(e, signature, i);
38633
38634 if (Qprime.eq(Q))
38635 return i;
38636 }
38637 throw new Error('Unable to find valid recovery factor');
38638};
38639}, {"bn.js":204,"../../elliptic":206,"./key":225,"./signature":226}],225: [function (exports, require, module, global) {'use strict';
38640
38641var bn = require('bn.js');
38642
38643var elliptic = require('../../elliptic');
38644var utils = elliptic.utils;
38645
38646function KeyPair(ec, options) {
38647 this.ec = ec;
38648 this.priv = null;
38649 this.pub = null;
38650
38651 // KeyPair(ec, { priv: ..., pub: ... })
38652 if (options.priv)
38653 this._importPrivate(options.priv, options.privEnc);
38654 if (options.pub)
38655 this._importPublic(options.pub, options.pubEnc);
38656}
38657module.exports = KeyPair;
38658
38659KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
38660 if (pub instanceof KeyPair)
38661 return pub;
38662
38663 return new KeyPair(ec, {
38664 pub: pub,
38665 pubEnc: enc
38666 });
38667};
38668
38669KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
38670 if (priv instanceof KeyPair)
38671 return priv;
38672
38673 return new KeyPair(ec, {
38674 priv: priv,
38675 privEnc: enc
38676 });
38677};
38678
38679KeyPair.prototype.validate = function validate() {
38680 var pub = this.getPublic();
38681
38682 if (pub.isInfinity())
38683 return { result: false, reason: 'Invalid public key' };
38684 if (!pub.validate())
38685 return { result: false, reason: 'Public key is not a point' };
38686 if (!pub.mul(this.ec.curve.n).isInfinity())
38687 return { result: false, reason: 'Public key * N != O' };
38688
38689 return { result: true, reason: null };
38690};
38691
38692KeyPair.prototype.getPublic = function getPublic(compact, enc) {
38693 if (!this.pub)
38694 this.pub = this.ec.g.mul(this.priv);
38695
38696 // compact is optional argument
38697 if (typeof compact === 'string') {
38698 enc = compact;
38699 compact = null;
38700 }
38701
38702 if (!enc)
38703 return this.pub;
38704
38705 var len = this.ec.curve.p.byteLength();
38706 var x = this.pub.getX().toArray();
38707
38708 for (var i = x.length; i < len; i++)
38709 x.unshift(0);
38710
38711 var res;
38712 if (this.ec.curve.type !== 'mont') {
38713 if (compact) {
38714 res = [ this.pub.getY().isEven() ? 0x02 : 0x03 ].concat(x);
38715 } else {
38716 var y = this.pub.getY().toArray();
38717 for (var i = y.length; i < len; i++)
38718 y.unshift(0);
38719 var res = [ 0x04 ].concat(x, y);
38720 }
38721 } else {
38722 res = x;
38723 }
38724
38725 return utils.encode(res, enc);
38726};
38727
38728KeyPair.prototype.getPrivate = function getPrivate(enc) {
38729 if (enc === 'hex')
38730 return this.priv.toString(16, 2);
38731 else
38732 return this.priv;
38733};
38734
38735KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
38736 this.priv = new bn(key, enc || 16);
38737
38738 // Ensure that the priv won't be bigger than n, otherwise we may fail
38739 // in fixed multiplication method
38740 this.priv = this.priv.mod(this.ec.curve.n);
38741};
38742
38743KeyPair.prototype._importPublic = function _importPublic(key, enc) {
38744 if (key.x || key.y) {
38745 this.pub = this.ec.curve.point(key.x, key.y);
38746 return;
38747 }
38748
38749 key = utils.toArray(key, enc);
38750 if (this.ec.curve.type !== 'mont')
38751 return this._importPublicShort(key);
38752 else
38753 return this._importPublicMont(key);
38754};
38755
38756KeyPair.prototype._importPublicShort = function _importPublicShort(key) {
38757 var len = this.ec.curve.p.byteLength();
38758 if (key[0] === 0x04 && key.length - 1 === 2 * len) {
38759 this.pub = this.ec.curve.point(
38760 key.slice(1, 1 + len),
38761 key.slice(1 + len, 1 + 2 * len));
38762 } else if ((key[0] === 0x02 || key[0] === 0x03) && key.length - 1 === len) {
38763 this.pub = this.ec.curve.pointFromX(key[0] === 0x03, key.slice(1, 1 + len));
38764 }
38765};
38766
38767KeyPair.prototype._importPublicMont = function _importPublicMont(key) {
38768 this.pub = this.ec.curve.point(key, 1);
38769};
38770
38771// ECDH
38772KeyPair.prototype.derive = function derive(pub) {
38773 return pub.mul(this.priv).getX();
38774};
38775
38776// ECDSA
38777KeyPair.prototype.sign = function sign(msg) {
38778 return this.ec.sign(msg, this);
38779};
38780
38781KeyPair.prototype.verify = function verify(msg, signature) {
38782 return this.ec.verify(msg, signature, this);
38783};
38784
38785KeyPair.prototype.inspect = function inspect() {
38786 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
38787 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
38788};
38789}, {"bn.js":204,"../../elliptic":206}],226: [function (exports, require, module, global) {'use strict';
38790
38791var bn = require('bn.js');
38792
38793var elliptic = require('../../elliptic');
38794var utils = elliptic.utils;
38795var assert = utils.assert;
38796
38797function Signature(options, enc) {
38798 if (options instanceof Signature)
38799 return options;
38800
38801 if (this._importDER(options, enc))
38802 return;
38803
38804 assert(options.r && options.s, 'Signature without r or s');
38805 this.r = new bn(options.r, 16);
38806 this.s = new bn(options.s, 16);
38807 if (options.recoveryParam !== null)
38808 this.recoveryParam = options.recoveryParam;
38809 else
38810 this.recoveryParam = null;
38811}
38812module.exports = Signature;
38813
38814Signature.prototype._importDER = function _importDER(data, enc) {
38815 data = utils.toArray(data, enc);
38816 if (data.length < 6 || data[0] !== 0x30 || data[2] !== 0x02)
38817 return false;
38818 var total = data[1];
38819 if (1 + total > data.length)
38820 return false;
38821 var rlen = data[3];
38822 // Short length notation
38823 if (rlen >= 0x80)
38824 return false;
38825 if (4 + rlen + 2 >= data.length)
38826 return false;
38827 if (data[4 + rlen] !== 0x02)
38828 return false;
38829 var slen = data[5 + rlen];
38830 // Short length notation
38831 if (slen >= 0x80)
38832 return false;
38833 if (4 + rlen + 2 + slen > data.length)
38834 return false;
38835
38836 this.r = new bn(data.slice(4, 4 + rlen));
38837 this.s = new bn(data.slice(4 + rlen + 2, 4 + rlen + 2 + slen));
38838 this.recoveryParam = null;
38839
38840 return true;
38841};
38842
38843Signature.prototype.toDER = function toDER(enc) {
38844 var r = this.r.toArray();
38845 var s = this.s.toArray();
38846
38847 // Pad values
38848 if (r[0] & 0x80)
38849 r = [ 0 ].concat(r);
38850 // Pad values
38851 if (s[0] & 0x80)
38852 s = [ 0 ].concat(s);
38853
38854 var total = r.length + s.length + 4;
38855 var res = [ 0x30, total, 0x02, r.length ];
38856 res = res.concat(r, [ 0x02, s.length ], s);
38857 return utils.encode(res, enc);
38858};
38859}, {"bn.js":204,"../../elliptic":206}],227: [function (exports, require, module, global) {var asn1 = require('./asn1')
38860var aesid = require('./aesid.json')
38861var fixProc = require('./fixProc')
38862var ciphers = require('browserify-aes')
38863var compat = require('pbkdf2')
38864module.exports = parseKeys
38865
38866function parseKeys (buffer) {
38867 var password
38868 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
38869 password = buffer.passphrase
38870 buffer = buffer.key
38871 }
38872 if (typeof buffer === 'string') {
38873 buffer = new Buffer(buffer)
38874 }
38875
38876 var stripped = fixProc(buffer, password)
38877
38878 var type = stripped.tag
38879 var data = stripped.data
38880 var subtype, ndata
38881 switch (type) {
38882 case 'PUBLIC KEY':
38883 ndata = asn1.PublicKey.decode(data, 'der')
38884 subtype = ndata.algorithm.algorithm.join('.')
38885 switch (subtype) {
38886 case '1.2.840.113549.1.1.1':
38887 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
38888 case '1.2.840.10045.2.1':
38889 ndata.subjectPrivateKey = ndata.subjectPublicKey
38890 return {
38891 type: 'ec',
38892 data: ndata
38893 }
38894 case '1.2.840.10040.4.1':
38895 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
38896 return {
38897 type: 'dsa',
38898 data: ndata.algorithm.params
38899 }
38900 default: throw new Error('unknown key id ' + subtype)
38901 }
38902 throw new Error('unknown key type ' + type)
38903 case 'ENCRYPTED PRIVATE KEY':
38904 data = asn1.EncryptedPrivateKey.decode(data, 'der')
38905 data = decrypt(data, password)
38906 // falls through
38907 case 'PRIVATE KEY':
38908 ndata = asn1.PrivateKey.decode(data, 'der')
38909 subtype = ndata.algorithm.algorithm.join('.')
38910 switch (subtype) {
38911 case '1.2.840.113549.1.1.1':
38912 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
38913 case '1.2.840.10045.2.1':
38914 return {
38915 curve: ndata.algorithm.curve,
38916 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
38917 }
38918 case '1.2.840.10040.4.1':
38919 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
38920 return {
38921 type: 'dsa',
38922 params: ndata.algorithm.params
38923 }
38924 default: throw new Error('unknown key id ' + subtype)
38925 }
38926 throw new Error('unknown key type ' + type)
38927 case 'RSA PUBLIC KEY':
38928 return asn1.RSAPublicKey.decode(data, 'der')
38929 case 'RSA PRIVATE KEY':
38930 return asn1.RSAPrivateKey.decode(data, 'der')
38931 case 'DSA PRIVATE KEY':
38932 return {
38933 type: 'dsa',
38934 params: asn1.DSAPrivateKey.decode(data, 'der')
38935 }
38936 case 'EC PRIVATE KEY':
38937 data = asn1.ECPrivateKey.decode(data, 'der')
38938 return {
38939 curve: data.parameters.value,
38940 privateKey: data.privateKey
38941 }
38942 default: throw new Error('unknown key type ' + type)
38943 }
38944}
38945parseKeys.signature = asn1.signature
38946function decrypt (data, password) {
38947 var salt = data.algorithm.decrypt.kde.kdeparams.salt
38948 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
38949 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
38950 var iv = data.algorithm.decrypt.cipher.iv
38951 var cipherText = data.subjectPrivateKey
38952 var keylen = parseInt(algo.split('-')[1], 10) / 8
38953 var key = compat.pbkdf2Sync(password, salt, iters, keylen)
38954 var cipher = ciphers.createDecipheriv(algo, key, iv)
38955 var out = []
38956 out.push(cipher.update(cipherText))
38957 out.push(cipher.final())
38958 return Buffer.concat(out)
38959}
38960}, {"./asn1":228,"./aesid.json":246,"./fixProc":247,"browserify-aes":249,"pbkdf2":164}],228: [function (exports, require, module, global) {// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
38961// Fedor, you are amazing.
38962
38963var asn1 = require('asn1.js')
38964
38965var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
38966 this.seq().obj(
38967 this.key('version').int(),
38968 this.key('modulus').int(),
38969 this.key('publicExponent').int(),
38970 this.key('privateExponent').int(),
38971 this.key('prime1').int(),
38972 this.key('prime2').int(),
38973 this.key('exponent1').int(),
38974 this.key('exponent2').int(),
38975 this.key('coefficient').int()
38976 )
38977})
38978exports.RSAPrivateKey = RSAPrivateKey
38979
38980var RSAPublicKey = asn1.define('RSAPublicKey', function () {
38981 this.seq().obj(
38982 this.key('modulus').int(),
38983 this.key('publicExponent').int()
38984 )
38985})
38986exports.RSAPublicKey = RSAPublicKey
38987
38988var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
38989 this.seq().obj(
38990 this.key('algorithm').use(AlgorithmIdentifier),
38991 this.key('subjectPublicKey').bitstr()
38992 )
38993})
38994exports.PublicKey = PublicKey
38995
38996var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
38997 this.seq().obj(
38998 this.key('algorithm').objid(),
38999 this.key('none').null_().optional(),
39000 this.key('curve').objid().optional(),
39001 this.key('params').seq().obj(
39002 this.key('p').int(),
39003 this.key('q').int(),
39004 this.key('g').int()
39005 ).optional()
39006 )
39007})
39008
39009var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
39010 this.seq().obj(
39011 this.key('version').int(),
39012 this.key('algorithm').use(AlgorithmIdentifier),
39013 this.key('subjectPrivateKey').octstr()
39014 )
39015})
39016exports.PrivateKey = PrivateKeyInfo
39017var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
39018 this.seq().obj(
39019 this.key('algorithm').seq().obj(
39020 this.key('id').objid(),
39021 this.key('decrypt').seq().obj(
39022 this.key('kde').seq().obj(
39023 this.key('id').objid(),
39024 this.key('kdeparams').seq().obj(
39025 this.key('salt').octstr(),
39026 this.key('iters').int()
39027 )
39028 ),
39029 this.key('cipher').seq().obj(
39030 this.key('algo').objid(),
39031 this.key('iv').octstr()
39032 )
39033 )
39034 ),
39035 this.key('subjectPrivateKey').octstr()
39036 )
39037})
39038
39039exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
39040
39041var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
39042 this.seq().obj(
39043 this.key('version').int(),
39044 this.key('p').int(),
39045 this.key('q').int(),
39046 this.key('g').int(),
39047 this.key('pub_key').int(),
39048 this.key('priv_key').int()
39049 )
39050})
39051exports.DSAPrivateKey = DSAPrivateKey
39052
39053exports.DSAparam = asn1.define('DSAparam', function () {
39054 this.int()
39055})
39056var ECPrivateKey = asn1.define('ECPrivateKey', function () {
39057 this.seq().obj(
39058 this.key('version').int(),
39059 this.key('privateKey').octstr(),
39060 this.key('parameters').optional().explicit(0).use(ECParameters),
39061 this.key('publicKey').optional().explicit(1).bitstr()
39062 )
39063})
39064exports.ECPrivateKey = ECPrivateKey
39065var ECParameters = asn1.define('ECParameters', function () {
39066 this.choice({
39067 namedCurve: this.objid()
39068 })
39069})
39070
39071exports.signature = asn1.define('signature', function () {
39072 this.seq().obj(
39073 this.key('r').int(),
39074 this.key('s').int()
39075 )
39076})
39077}, {"asn1.js":229}],229: [function (exports, require, module, global) {var asn1 = exports;
39078
39079asn1.bignum = require('bn.js');
39080
39081asn1.define = require('./asn1/api').define;
39082asn1.base = require('./asn1/base');
39083asn1.constants = require('./asn1/constants');
39084asn1.decoders = require('./asn1/decoders');
39085asn1.encoders = require('./asn1/encoders');
39086}, {"bn.js":204,"./asn1/api":230,"./asn1/base":233,"./asn1/constants":238,"./asn1/decoders":240,"./asn1/encoders":243}],230: [function (exports, require, module, global) {var asn1 = require('../asn1');
39087var inherits = require('inherits');
39088
39089var api = exports;
39090
39091api.define = function define(name, body) {
39092 return new Entity(name, body);
39093};
39094
39095function Entity(name, body) {
39096 this.name = name;
39097 this.body = body;
39098
39099 this.decoders = {};
39100 this.encoders = {};
39101};
39102
39103Entity.prototype._createNamed = function createNamed(base) {
39104 var named;
39105 try {
39106 named = require('vm').runInThisContext(
39107 '(function ' + this.name + '(entity) {\n' +
39108 ' this._initNamed(entity);\n' +
39109 '})'
39110 );
39111 } catch (e) {
39112 named = function (entity) {
39113 this._initNamed(entity);
39114 };
39115 }
39116 inherits(named, base);
39117 named.prototype._initNamed = function initnamed(entity) {
39118 base.call(this, entity);
39119 };
39120
39121 return new named(this);
39122};
39123
39124Entity.prototype._getDecoder = function _getDecoder(enc) {
39125 // Lazily create decoder
39126 if (!this.decoders.hasOwnProperty(enc))
39127 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
39128 return this.decoders[enc];
39129};
39130
39131Entity.prototype.decode = function decode(data, enc, options) {
39132 return this._getDecoder(enc).decode(data, options);
39133};
39134
39135Entity.prototype._getEncoder = function _getEncoder(enc) {
39136 // Lazily create encoder
39137 if (!this.encoders.hasOwnProperty(enc))
39138 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
39139 return this.encoders[enc];
39140};
39141
39142Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
39143 return this._getEncoder(enc).encode(data, reporter);
39144};
39145}, {"../asn1":229,"inherits":149,"vm":231}],231: [function (exports, require, module, global) {var indexOf = require('indexof');
39146
39147var Object_keys = function (obj) {
39148 if (Object.keys) return Object.keys(obj)
39149 else {
39150 var res = [];
39151 for (var key in obj) res.push(key)
39152 return res;
39153 }
39154};
39155
39156var forEach = function (xs, fn) {
39157 if (xs.forEach) return xs.forEach(fn)
39158 else for (var i = 0; i < xs.length; i++) {
39159 fn(xs[i], i, xs);
39160 }
39161};
39162
39163var defineProp = (function() {
39164 try {
39165 Object.defineProperty({}, '_', {});
39166 return function(obj, name, value) {
39167 Object.defineProperty(obj, name, {
39168 writable: true,
39169 enumerable: false,
39170 configurable: true,
39171 value: value
39172 })
39173 };
39174 } catch(e) {
39175 return function(obj, name, value) {
39176 obj[name] = value;
39177 };
39178 }
39179}());
39180
39181var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
39182'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
39183'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
39184'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
39185'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
39186
39187function Context() {}
39188Context.prototype = {};
39189
39190var Script = exports.Script = function NodeScript (code) {
39191 if (!(this instanceof Script)) return new Script(code);
39192 this.code = code;
39193};
39194
39195Script.prototype.runInContext = function (context) {
39196 if (!(context instanceof Context)) {
39197 throw new TypeError("needs a 'context' argument.");
39198 }
39199
39200 var iframe = document.createElement('iframe');
39201 if (!iframe.style) iframe.style = {};
39202 iframe.style.display = 'none';
39203
39204 document.body.appendChild(iframe);
39205
39206 var win = iframe.contentWindow;
39207 var wEval = win.eval, wExecScript = win.execScript;
39208
39209 if (!wEval && wExecScript) {
39210 // win.eval() magically appears when this is called in IE:
39211 wExecScript.call(win, 'null');
39212 wEval = win.eval;
39213 }
39214
39215 forEach(Object_keys(context), function (key) {
39216 win[key] = context[key];
39217 });
39218 forEach(globals, function (key) {
39219 if (context[key]) {
39220 win[key] = context[key];
39221 }
39222 });
39223
39224 var winKeys = Object_keys(win);
39225
39226 var res = wEval.call(win, this.code);
39227
39228 forEach(Object_keys(win), function (key) {
39229 // Avoid copying circular objects like `top` and `window` by only
39230 // updating existing context properties or new properties in the `win`
39231 // that was only introduced after the eval.
39232 if (key in context || indexOf(winKeys, key) === -1) {
39233 context[key] = win[key];
39234 }
39235 });
39236
39237 forEach(globals, function (key) {
39238 if (!(key in context)) {
39239 defineProp(context, key, win[key]);
39240 }
39241 });
39242
39243 document.body.removeChild(iframe);
39244
39245 return res;
39246};
39247
39248Script.prototype.runInThisContext = function () {
39249 return eval(this.code); // maybe...
39250};
39251
39252Script.prototype.runInNewContext = function (context) {
39253 var ctx = Script.createContext(context);
39254 var res = this.runInContext(ctx);
39255
39256 forEach(Object_keys(ctx), function (key) {
39257 context[key] = ctx[key];
39258 });
39259
39260 return res;
39261};
39262
39263forEach(Object_keys(Script.prototype), function (name) {
39264 exports[name] = Script[name] = function (code) {
39265 var s = Script(code);
39266 return s[name].apply(s, [].slice.call(arguments, 1));
39267 };
39268});
39269
39270exports.createScript = function (code) {
39271 return exports.Script(code);
39272};
39273
39274exports.createContext = Script.createContext = function (context) {
39275 var copy = new Context();
39276 if(typeof context === 'object') {
39277 forEach(Object_keys(context), function (key) {
39278 copy[key] = context[key];
39279 });
39280 }
39281 return copy;
39282};
39283}, {"indexof":232}],232: [function (exports, require, module, global) {
39284var indexOf = [].indexOf;
39285
39286module.exports = function(arr, obj){
39287 if (indexOf) return arr.indexOf(obj);
39288 for (var i = 0; i < arr.length; ++i) {
39289 if (arr[i] === obj) return i;
39290 }
39291 return -1;
39292};}, {}],233: [function (exports, require, module, global) {var base = exports;
39293
39294base.Reporter = require('./reporter').Reporter;
39295base.DecoderBuffer = require('./buffer').DecoderBuffer;
39296base.EncoderBuffer = require('./buffer').EncoderBuffer;
39297base.Node = require('./node');
39298}, {"./reporter":234,"./buffer":235,"./node":236}],234: [function (exports, require, module, global) {var inherits = require('inherits');
39299
39300function Reporter(options) {
39301 this._reporterState = {
39302 obj: null,
39303 path: [],
39304 options: options || {},
39305 errors: []
39306 };
39307}
39308exports.Reporter = Reporter;
39309
39310Reporter.prototype.isError = function isError(obj) {
39311 return obj instanceof ReporterError;
39312};
39313
39314Reporter.prototype.save = function save() {
39315 var state = this._reporterState;
39316
39317 return { obj: state.obj, pathLen: state.path.length };
39318};
39319
39320Reporter.prototype.restore = function restore(data) {
39321 var state = this._reporterState;
39322
39323 state.obj = data.obj;
39324 state.path = state.path.slice(0, data.pathLen);
39325};
39326
39327Reporter.prototype.enterKey = function enterKey(key) {
39328 return this._reporterState.path.push(key);
39329};
39330
39331Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
39332 var state = this._reporterState;
39333
39334 state.path = state.path.slice(0, index - 1);
39335 if (state.obj !== null)
39336 state.obj[key] = value;
39337};
39338
39339Reporter.prototype.enterObject = function enterObject() {
39340 var state = this._reporterState;
39341
39342 var prev = state.obj;
39343 state.obj = {};
39344 return prev;
39345};
39346
39347Reporter.prototype.leaveObject = function leaveObject(prev) {
39348 var state = this._reporterState;
39349
39350 var now = state.obj;
39351 state.obj = prev;
39352 return now;
39353};
39354
39355Reporter.prototype.error = function error(msg) {
39356 var err;
39357 var state = this._reporterState;
39358
39359 var inherited = msg instanceof ReporterError;
39360 if (inherited) {
39361 err = msg;
39362 } else {
39363 err = new ReporterError(state.path.map(function(elem) {
39364 return '[' + JSON.stringify(elem) + ']';
39365 }).join(''), msg.message || msg, msg.stack);
39366 }
39367
39368 if (!state.options.partial)
39369 throw err;
39370
39371 if (!inherited)
39372 state.errors.push(err);
39373
39374 return err;
39375};
39376
39377Reporter.prototype.wrapResult = function wrapResult(result) {
39378 var state = this._reporterState;
39379 if (!state.options.partial)
39380 return result;
39381
39382 return {
39383 result: this.isError(result) ? null : result,
39384 errors: state.errors
39385 };
39386};
39387
39388function ReporterError(path, msg) {
39389 this.path = path;
39390 this.rethrow(msg);
39391};
39392inherits(ReporterError, Error);
39393
39394ReporterError.prototype.rethrow = function rethrow(msg) {
39395 this.message = msg + ' at: ' + (this.path || '(shallow)');
39396 Error.captureStackTrace(this, ReporterError);
39397
39398 return this;
39399};
39400}, {"inherits":149}],235: [function (exports, require, module, global) {var inherits = require('inherits');
39401var Reporter = require('../base').Reporter;
39402var Buffer = require('buffer').Buffer;
39403
39404function DecoderBuffer(base, options) {
39405 Reporter.call(this, options);
39406 if (!Buffer.isBuffer(base)) {
39407 this.error('Input not Buffer');
39408 return;
39409 }
39410
39411 this.base = base;
39412 this.offset = 0;
39413 this.length = base.length;
39414}
39415inherits(DecoderBuffer, Reporter);
39416exports.DecoderBuffer = DecoderBuffer;
39417
39418DecoderBuffer.prototype.save = function save() {
39419 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
39420};
39421
39422DecoderBuffer.prototype.restore = function restore(save) {
39423 // Return skipped data
39424 var res = new DecoderBuffer(this.base);
39425 res.offset = save.offset;
39426 res.length = this.offset;
39427
39428 this.offset = save.offset;
39429 Reporter.prototype.restore.call(this, save.reporter);
39430
39431 return res;
39432};
39433
39434DecoderBuffer.prototype.isEmpty = function isEmpty() {
39435 return this.offset === this.length;
39436};
39437
39438DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
39439 if (this.offset + 1 <= this.length)
39440 return this.base.readUInt8(this.offset++, true);
39441 else
39442 return this.error(fail || 'DecoderBuffer overrun');
39443}
39444
39445DecoderBuffer.prototype.skip = function skip(bytes, fail) {
39446 if (!(this.offset + bytes <= this.length))
39447 return this.error(fail || 'DecoderBuffer overrun');
39448
39449 var res = new DecoderBuffer(this.base);
39450
39451 // Share reporter state
39452 res._reporterState = this._reporterState;
39453
39454 res.offset = this.offset;
39455 res.length = this.offset + bytes;
39456 this.offset += bytes;
39457 return res;
39458}
39459
39460DecoderBuffer.prototype.raw = function raw(save) {
39461 return this.base.slice(save ? save.offset : this.offset, this.length);
39462}
39463
39464function EncoderBuffer(value, reporter) {
39465 if (Array.isArray(value)) {
39466 this.length = 0;
39467 this.value = value.map(function(item) {
39468 if (!(item instanceof EncoderBuffer))
39469 item = new EncoderBuffer(item, reporter);
39470 this.length += item.length;
39471 return item;
39472 }, this);
39473 } else if (typeof value === 'number') {
39474 if (!(0 <= value && value <= 0xff))
39475 return reporter.error('non-byte EncoderBuffer value');
39476 this.value = value;
39477 this.length = 1;
39478 } else if (typeof value === 'string') {
39479 this.value = value;
39480 this.length = Buffer.byteLength(value);
39481 } else if (Buffer.isBuffer(value)) {
39482 this.value = value;
39483 this.length = value.length;
39484 } else {
39485 return reporter.error('Unsupported type: ' + typeof value);
39486 }
39487}
39488exports.EncoderBuffer = EncoderBuffer;
39489
39490EncoderBuffer.prototype.join = function join(out, offset) {
39491 if (!out)
39492 out = new Buffer(this.length);
39493 if (!offset)
39494 offset = 0;
39495
39496 if (this.length === 0)
39497 return out;
39498
39499 if (Array.isArray(this.value)) {
39500 this.value.forEach(function(item) {
39501 item.join(out, offset);
39502 offset += item.length;
39503 });
39504 } else {
39505 if (typeof this.value === 'number')
39506 out[offset] = this.value;
39507 else if (typeof this.value === 'string')
39508 out.write(this.value, offset);
39509 else if (Buffer.isBuffer(this.value))
39510 this.value.copy(out, offset);
39511 offset += this.length;
39512 }
39513
39514 return out;
39515};
39516}, {"inherits":149,"../base":233,"buffer":29}],236: [function (exports, require, module, global) {var Reporter = require('../base').Reporter;
39517var EncoderBuffer = require('../base').EncoderBuffer;
39518var assert = require('minimalistic-assert');
39519
39520// Supported tags
39521var tags = [
39522 'seq', 'seqof', 'set', 'setof', 'octstr', 'bitstr', 'objid', 'bool',
39523 'gentime', 'utctime', 'null_', 'enum', 'int', 'ia5str', 'utf8str'
39524];
39525
39526// Public methods list
39527var methods = [
39528 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
39529 'any'
39530].concat(tags);
39531
39532// Overrided methods list
39533var overrided = [
39534 '_peekTag', '_decodeTag', '_use',
39535 '_decodeStr', '_decodeObjid', '_decodeTime',
39536 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
39537
39538 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
39539 '_encodeNull', '_encodeInt', '_encodeBool'
39540];
39541
39542function Node(enc, parent) {
39543 var state = {};
39544 this._baseState = state;
39545
39546 state.enc = enc;
39547
39548 state.parent = parent || null;
39549 state.children = null;
39550
39551 // State
39552 state.tag = null;
39553 state.args = null;
39554 state.reverseArgs = null;
39555 state.choice = null;
39556 state.optional = false;
39557 state.any = false;
39558 state.obj = false;
39559 state.use = null;
39560 state.useDecoder = null;
39561 state.key = null;
39562 state['default'] = null;
39563 state.explicit = null;
39564 state.implicit = null;
39565
39566 // Should create new instance on each method
39567 if (!state.parent) {
39568 state.children = [];
39569 this._wrap();
39570 }
39571}
39572module.exports = Node;
39573
39574var stateProps = [
39575 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
39576 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
39577 'implicit'
39578];
39579
39580Node.prototype.clone = function clone() {
39581 var state = this._baseState;
39582 var cstate = {};
39583 stateProps.forEach(function(prop) {
39584 cstate[prop] = state[prop];
39585 });
39586 var res = new this.constructor(cstate.parent);
39587 res._baseState = cstate;
39588 return res;
39589};
39590
39591Node.prototype._wrap = function wrap() {
39592 var state = this._baseState;
39593 methods.forEach(function(method) {
39594 this[method] = function _wrappedMethod() {
39595 var clone = new this.constructor(this);
39596 state.children.push(clone);
39597 return clone[method].apply(clone, arguments);
39598 };
39599 }, this);
39600};
39601
39602Node.prototype._init = function init(body) {
39603 var state = this._baseState;
39604
39605 assert(state.parent === null);
39606 body.call(this);
39607
39608 // Filter children
39609 state.children = state.children.filter(function(child) {
39610 return child._baseState.parent === this;
39611 }, this);
39612 assert.equal(state.children.length, 1, 'Root node can have only one child');
39613};
39614
39615Node.prototype._useArgs = function useArgs(args) {
39616 var state = this._baseState;
39617
39618 // Filter children and args
39619 var children = args.filter(function(arg) {
39620 return arg instanceof this.constructor;
39621 }, this);
39622 args = args.filter(function(arg) {
39623 return !(arg instanceof this.constructor);
39624 }, this);
39625
39626 if (children.length !== 0) {
39627 assert(state.children === null);
39628 state.children = children;
39629
39630 // Replace parent to maintain backward link
39631 children.forEach(function(child) {
39632 child._baseState.parent = this;
39633 }, this);
39634 }
39635 if (args.length !== 0) {
39636 assert(state.args === null);
39637 state.args = args;
39638 state.reverseArgs = args.map(function(arg) {
39639 if (typeof arg !== 'object' || arg.constructor !== Object)
39640 return arg;
39641
39642 var res = {};
39643 Object.keys(arg).forEach(function(key) {
39644 if (key == (key | 0))
39645 key |= 0;
39646 var value = arg[key];
39647 res[value] = key;
39648 });
39649 return res;
39650 });
39651 }
39652};
39653
39654//
39655// Overrided methods
39656//
39657
39658overrided.forEach(function(method) {
39659 Node.prototype[method] = function _overrided() {
39660 var state = this._baseState;
39661 throw new Error(method + ' not implemented for encoding: ' + state.enc);
39662 };
39663});
39664
39665//
39666// Public methods
39667//
39668
39669tags.forEach(function(tag) {
39670 Node.prototype[tag] = function _tagMethod() {
39671 var state = this._baseState;
39672 var args = Array.prototype.slice.call(arguments);
39673
39674 assert(state.tag === null);
39675 state.tag = tag;
39676
39677 this._useArgs(args);
39678
39679 return this;
39680 };
39681});
39682
39683Node.prototype.use = function use(item) {
39684 var state = this._baseState;
39685
39686 assert(state.use === null);
39687 state.use = item;
39688
39689 return this;
39690};
39691
39692Node.prototype.optional = function optional() {
39693 var state = this._baseState;
39694
39695 state.optional = true;
39696
39697 return this;
39698};
39699
39700Node.prototype.def = function def(val) {
39701 var state = this._baseState;
39702
39703 assert(state['default'] === null);
39704 state['default'] = val;
39705 state.optional = true;
39706
39707 return this;
39708};
39709
39710Node.prototype.explicit = function explicit(num) {
39711 var state = this._baseState;
39712
39713 assert(state.explicit === null && state.implicit === null);
39714 state.explicit = num;
39715
39716 return this;
39717};
39718
39719Node.prototype.implicit = function implicit(num) {
39720 var state = this._baseState;
39721
39722 assert(state.explicit === null && state.implicit === null);
39723 state.implicit = num;
39724
39725 return this;
39726};
39727
39728Node.prototype.obj = function obj() {
39729 var state = this._baseState;
39730 var args = Array.prototype.slice.call(arguments);
39731
39732 state.obj = true;
39733
39734 if (args.length !== 0)
39735 this._useArgs(args);
39736
39737 return this;
39738};
39739
39740Node.prototype.key = function key(newKey) {
39741 var state = this._baseState;
39742
39743 assert(state.key === null);
39744 state.key = newKey;
39745
39746 return this;
39747};
39748
39749Node.prototype.any = function any() {
39750 var state = this._baseState;
39751
39752 state.any = true;
39753
39754 return this;
39755};
39756
39757Node.prototype.choice = function choice(obj) {
39758 var state = this._baseState;
39759
39760 assert(state.choice === null);
39761 state.choice = obj;
39762 this._useArgs(Object.keys(obj).map(function(key) {
39763 return obj[key];
39764 }));
39765
39766 return this;
39767};
39768
39769//
39770// Decoding
39771//
39772
39773Node.prototype._decode = function decode(input) {
39774 var state = this._baseState;
39775
39776 // Decode root node
39777 if (state.parent === null)
39778 return input.wrapResult(state.children[0]._decode(input));
39779
39780 var result = state['default'];
39781 var present = true;
39782
39783 var prevKey;
39784 if (state.key !== null)
39785 prevKey = input.enterKey(state.key);
39786
39787 // Check if tag is there
39788 if (state.optional) {
39789 var tag = null;
39790 if (state.explicit !== null)
39791 tag = state.explicit;
39792 else if (state.implicit !== null)
39793 tag = state.implicit;
39794 else if (state.tag !== null)
39795 tag = state.tag;
39796
39797 if (tag === null && !state.any) {
39798 // Trial and Error
39799 var save = input.save();
39800 try {
39801 if (state.choice === null)
39802 this._decodeGeneric(state.tag, input);
39803 else
39804 this._decodeChoice(input);
39805 present = true;
39806 } catch (e) {
39807 present = false;
39808 }
39809 input.restore(save);
39810 } else {
39811 present = this._peekTag(input, tag, state.any);
39812
39813 if (input.isError(present))
39814 return present;
39815 }
39816 }
39817
39818 // Push object on stack
39819 var prevObj;
39820 if (state.obj && present)
39821 prevObj = input.enterObject();
39822
39823 if (present) {
39824 // Unwrap explicit values
39825 if (state.explicit !== null) {
39826 var explicit = this._decodeTag(input, state.explicit);
39827 if (input.isError(explicit))
39828 return explicit;
39829 input = explicit;
39830 }
39831
39832 // Unwrap implicit and normal values
39833 if (state.use === null && state.choice === null) {
39834 if (state.any)
39835 var save = input.save();
39836 var body = this._decodeTag(
39837 input,
39838 state.implicit !== null ? state.implicit : state.tag,
39839 state.any
39840 );
39841 if (input.isError(body))
39842 return body;
39843
39844 if (state.any)
39845 result = input.raw(save);
39846 else
39847 input = body;
39848 }
39849
39850 // Select proper method for tag
39851 if (state.any)
39852 result = result;
39853 else if (state.choice === null)
39854 result = this._decodeGeneric(state.tag, input);
39855 else
39856 result = this._decodeChoice(input);
39857
39858 if (input.isError(result))
39859 return result;
39860
39861 // Decode children
39862 if (!state.any && state.choice === null && state.children !== null) {
39863 var fail = state.children.some(function decodeChildren(child) {
39864 // NOTE: We are ignoring errors here, to let parser continue with other
39865 // parts of encoded data
39866 child._decode(input);
39867 });
39868 if (fail)
39869 return err;
39870 }
39871 }
39872
39873 // Pop object
39874 if (state.obj && present)
39875 result = input.leaveObject(prevObj);
39876
39877 // Set key
39878 if (state.key !== null && (result !== null || present === true))
39879 input.leaveKey(prevKey, state.key, result);
39880
39881 return result;
39882};
39883
39884Node.prototype._decodeGeneric = function decodeGeneric(tag, input) {
39885 var state = this._baseState;
39886
39887 if (tag === 'seq' || tag === 'set')
39888 return null;
39889 if (tag === 'seqof' || tag === 'setof')
39890 return this._decodeList(input, tag, state.args[0]);
39891 else if (tag === 'octstr' || tag === 'bitstr')
39892 return this._decodeStr(input, tag);
39893 else if (tag === 'ia5str' || tag === 'utf8str')
39894 return this._decodeStr(input, tag);
39895 else if (tag === 'objid' && state.args)
39896 return this._decodeObjid(input, state.args[0], state.args[1]);
39897 else if (tag === 'objid')
39898 return this._decodeObjid(input, null, null);
39899 else if (tag === 'gentime' || tag === 'utctime')
39900 return this._decodeTime(input, tag);
39901 else if (tag === 'null_')
39902 return this._decodeNull(input);
39903 else if (tag === 'bool')
39904 return this._decodeBool(input);
39905 else if (tag === 'int' || tag === 'enum')
39906 return this._decodeInt(input, state.args && state.args[0]);
39907 else if (state.use !== null)
39908 return this._getUse(state.use, input._reporterState.obj)._decode(input);
39909 else
39910 return input.error('unknown tag: ' + tag);
39911
39912 return null;
39913};
39914
39915Node.prototype._getUse = function _getUse(entity, obj) {
39916
39917 var state = this._baseState;
39918 // Create altered use decoder if implicit is set
39919 state.useDecoder = this._use(entity, obj);
39920 assert(state.useDecoder._baseState.parent === null);
39921 state.useDecoder = state.useDecoder._baseState.children[0];
39922 if (state.implicit !== state.useDecoder._baseState.implicit) {
39923 state.useDecoder = state.useDecoder.clone();
39924 state.useDecoder._baseState.implicit = state.implicit;
39925 }
39926 return state.useDecoder;
39927};
39928
39929Node.prototype._decodeChoice = function decodeChoice(input) {
39930 var state = this._baseState;
39931 var result = null;
39932 var match = false;
39933
39934 Object.keys(state.choice).some(function(key) {
39935 var save = input.save();
39936 var node = state.choice[key];
39937 try {
39938 var value = node._decode(input);
39939 if (input.isError(value))
39940 return false;
39941
39942 result = { type: key, value: value };
39943 match = true;
39944 } catch (e) {
39945 input.restore(save);
39946 return false;
39947 }
39948 return true;
39949 }, this);
39950
39951 if (!match)
39952 return input.error('Choice not matched');
39953
39954 return result;
39955};
39956
39957//
39958// Encoding
39959//
39960
39961Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
39962 return new EncoderBuffer(data, this.reporter);
39963};
39964
39965Node.prototype._encode = function encode(data, reporter, parent) {
39966 var state = this._baseState;
39967 if (state['default'] !== null && state['default'] === data)
39968 return;
39969
39970 var result = this._encodeValue(data, reporter, parent);
39971 if (result === undefined)
39972 return;
39973
39974 if (this._skipDefault(result, reporter, parent))
39975 return;
39976
39977 return result;
39978};
39979
39980Node.prototype._encodeValue = function encode(data, reporter, parent) {
39981 var state = this._baseState;
39982
39983 // Decode root node
39984 if (state.parent === null)
39985 return state.children[0]._encode(data, reporter || new Reporter());
39986
39987 var result = null;
39988 var present = true;
39989
39990 // Set reporter to share it with a child class
39991 this.reporter = reporter;
39992
39993 // Check if data is there
39994 if (state.optional && data === undefined) {
39995 if (state['default'] !== null)
39996 data = state['default']
39997 else
39998 return;
39999 }
40000
40001 // For error reporting
40002 var prevKey;
40003
40004 // Encode children first
40005 var content = null;
40006 var primitive = false;
40007 if (state.any) {
40008 // Anything that was given is translated to buffer
40009 result = this._createEncoderBuffer(data);
40010 } else if (state.choice) {
40011 result = this._encodeChoice(data, reporter);
40012 } else if (state.children) {
40013 content = state.children.map(function(child) {
40014 if (child._baseState.tag === 'null_')
40015 return child._encode(null, reporter, data);
40016
40017 if (child._baseState.key === null)
40018 return reporter.error('Child should have a key');
40019 var prevKey = reporter.enterKey(child._baseState.key);
40020
40021 if (typeof data !== 'object')
40022 return reporter.error('Child expected, but input is not object');
40023
40024 var res = child._encode(data[child._baseState.key], reporter, data);
40025 reporter.leaveKey(prevKey);
40026
40027 return res;
40028 }, this).filter(function(child) {
40029 return child;
40030 });
40031
40032 content = this._createEncoderBuffer(content);
40033 } else {
40034 if (state.tag === 'seqof' || state.tag === 'setof') {
40035 // TODO(indutny): this should be thrown on DSL level
40036 if (!(state.args && state.args.length === 1))
40037 return reporter.error('Too many args for : ' + state.tag);
40038
40039 if (!Array.isArray(data))
40040 return reporter.error('seqof/setof, but data is not Array');
40041
40042 var child = this.clone();
40043 child._baseState.implicit = null;
40044 content = this._createEncoderBuffer(data.map(function(item) {
40045 var state = this._baseState;
40046
40047 return this._getUse(state.args[0], data)._encode(item, reporter);
40048 }, child));
40049 } else if (state.use !== null) {
40050 result = this._getUse(state.use, parent)._encode(data, reporter);
40051 } else {
40052 content = this._encodePrimitive(state.tag, data);
40053 primitive = true;
40054 }
40055 }
40056
40057 // Encode data itself
40058 var result;
40059 if (!state.any && state.choice === null) {
40060 var tag = state.implicit !== null ? state.implicit : state.tag;
40061 var cls = state.implicit === null ? 'universal' : 'context';
40062
40063 if (tag === null) {
40064 if (state.use === null)
40065 reporter.error('Tag could be ommited only for .use()');
40066 } else {
40067 if (state.use === null)
40068 result = this._encodeComposite(tag, primitive, cls, content);
40069 }
40070 }
40071
40072 // Wrap in explicit
40073 if (state.explicit !== null)
40074 result = this._encodeComposite(state.explicit, false, 'context', result);
40075
40076 return result;
40077};
40078
40079Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
40080 var state = this._baseState;
40081
40082 var node = state.choice[data.type];
40083 if (!node) {
40084 assert(
40085 false,
40086 data.type + ' not found in ' +
40087 JSON.stringify(Object.keys(state.choice)));
40088 }
40089 return node._encode(data.value, reporter);
40090};
40091
40092Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
40093 var state = this._baseState;
40094
40095 if (tag === 'octstr' || tag === 'bitstr' || tag === 'ia5str')
40096 return this._encodeStr(data, tag);
40097 else if (tag === 'utf8str')
40098 return this._encodeStr(data, tag);
40099 else if (tag === 'objid' && state.args)
40100 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
40101 else if (tag === 'objid')
40102 return this._encodeObjid(data, null, null);
40103 else if (tag === 'gentime' || tag === 'utctime')
40104 return this._encodeTime(data, tag);
40105 else if (tag === 'null_')
40106 return this._encodeNull();
40107 else if (tag === 'int' || tag === 'enum')
40108 return this._encodeInt(data, state.args && state.reverseArgs[0]);
40109 else if (tag === 'bool')
40110 return this._encodeBool(data);
40111 else
40112 throw new Error('Unsupported tag: ' + tag);
40113};
40114}, {"../base":233,"minimalistic-assert":237}],237: [function (exports, require, module, global) {module.exports = assert;
40115
40116function assert(val, msg) {
40117 if (!val)
40118 throw new Error(msg || 'Assertion failed');
40119}
40120
40121assert.equal = function assertEqual(l, r, msg) {
40122 if (l != r)
40123 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
40124};
40125}, {}],238: [function (exports, require, module, global) {var constants = exports;
40126
40127// Helper
40128constants._reverse = function reverse(map) {
40129 var res = {};
40130
40131 Object.keys(map).forEach(function(key) {
40132 // Convert key to integer if it is stringified
40133 if ((key | 0) == key)
40134 key = key | 0;
40135
40136 var value = map[key];
40137 res[value] = key;
40138 });
40139
40140 return res;
40141};
40142
40143constants.der = require('./der');
40144}, {"./der":239}],239: [function (exports, require, module, global) {var constants = require('../constants');
40145
40146exports.tagClass = {
40147 0: 'universal',
40148 1: 'application',
40149 2: 'context',
40150 3: 'private'
40151};
40152exports.tagClassByName = constants._reverse(exports.tagClass);
40153
40154exports.tag = {
40155 0x00: 'end',
40156 0x01: 'bool',
40157 0x02: 'int',
40158 0x03: 'bitstr',
40159 0x04: 'octstr',
40160 0x05: 'null_',
40161 0x06: 'objid',
40162 0x07: 'objDesc',
40163 0x08: 'external',
40164 0x09: 'real',
40165 0x0a: 'enum',
40166 0x0b: 'embed',
40167 0x0c: 'utf8str',
40168 0x0d: 'relativeOid',
40169 0x10: 'seq',
40170 0x11: 'set',
40171 0x12: 'numstr',
40172 0x13: 'printstr',
40173 0x14: 't61str',
40174 0x15: 'videostr',
40175 0x16: 'ia5str',
40176 0x17: 'utctime',
40177 0x18: 'gentime',
40178 0x19: 'graphstr',
40179 0x1a: 'iso646str',
40180 0x1b: 'genstr',
40181 0x1c: 'unistr',
40182 0x1d: 'charstr',
40183 0x1e: 'bmpstr'
40184};
40185exports.tagByName = constants._reverse(exports.tag);
40186}, {"../constants":238}],240: [function (exports, require, module, global) {var decoders = exports;
40187
40188decoders.der = require('./der');
40189decoders.pem = require('./pem');
40190}, {"./der":241,"./pem":242}],241: [function (exports, require, module, global) {var inherits = require('inherits');
40191
40192var asn1 = require('../../asn1');
40193var base = asn1.base;
40194var bignum = asn1.bignum;
40195
40196// Import DER constants
40197var der = asn1.constants.der;
40198
40199function DERDecoder(entity) {
40200 this.enc = 'der';
40201 this.name = entity.name;
40202 this.entity = entity;
40203
40204 // Construct base tree
40205 this.tree = new DERNode();
40206 this.tree._init(entity.body);
40207};
40208module.exports = DERDecoder;
40209
40210DERDecoder.prototype.decode = function decode(data, options) {
40211 if (!(data instanceof base.DecoderBuffer))
40212 data = new base.DecoderBuffer(data, options);
40213
40214 return this.tree._decode(data, options);
40215};
40216
40217// Tree methods
40218
40219function DERNode(parent) {
40220 base.Node.call(this, 'der', parent);
40221}
40222inherits(DERNode, base.Node);
40223
40224DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
40225 if (buffer.isEmpty())
40226 return false;
40227
40228 var state = buffer.save();
40229 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
40230 if (buffer.isError(decodedTag))
40231 return decodedTag;
40232
40233 buffer.restore(state);
40234
40235 return decodedTag.tag === tag || decodedTag.tagStr === tag || any;
40236};
40237
40238DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
40239 var decodedTag = derDecodeTag(buffer,
40240 'Failed to decode tag of "' + tag + '"');
40241 if (buffer.isError(decodedTag))
40242 return decodedTag;
40243
40244 var len = derDecodeLen(buffer,
40245 decodedTag.primitive,
40246 'Failed to get length of "' + tag + '"');
40247
40248 // Failure
40249 if (buffer.isError(len))
40250 return len;
40251
40252 if (!any &&
40253 decodedTag.tag !== tag &&
40254 decodedTag.tagStr !== tag &&
40255 decodedTag.tagStr + 'of' !== tag) {
40256 return buffer.error('Failed to match tag: "' + tag + '"');
40257 }
40258
40259 if (decodedTag.primitive || len !== null)
40260 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
40261
40262 // Indefinite length... find END tag
40263 var state = buffer.save();
40264 var res = this._skipUntilEnd(
40265 buffer,
40266 'Failed to skip indefinite length body: "' + this.tag + '"');
40267 if (buffer.isError(res))
40268 return res;
40269
40270 len = buffer.offset - state.offset;
40271 buffer.restore(state);
40272 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
40273};
40274
40275DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
40276 while (true) {
40277 var tag = derDecodeTag(buffer, fail);
40278 if (buffer.isError(tag))
40279 return tag;
40280 var len = derDecodeLen(buffer, tag.primitive, fail);
40281 if (buffer.isError(len))
40282 return len;
40283
40284 var res;
40285 if (tag.primitive || len !== null)
40286 res = buffer.skip(len)
40287 else
40288 res = this._skipUntilEnd(buffer, fail);
40289
40290 // Failure
40291 if (buffer.isError(res))
40292 return res;
40293
40294 if (tag.tagStr === 'end')
40295 break;
40296 }
40297};
40298
40299DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) {
40300 var result = [];
40301 while (!buffer.isEmpty()) {
40302 var possibleEnd = this._peekTag(buffer, 'end');
40303 if (buffer.isError(possibleEnd))
40304 return possibleEnd;
40305
40306 var res = decoder.decode(buffer, 'der');
40307 if (buffer.isError(res) && possibleEnd)
40308 break;
40309 result.push(res);
40310 }
40311 return result;
40312};
40313
40314DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
40315 if (tag === 'octstr') {
40316 return buffer.raw();
40317 } else if (tag === 'bitstr') {
40318 var unused = buffer.readUInt8();
40319 if (buffer.isError(unused))
40320 return unused;
40321
40322 return { unused: unused, data: buffer.raw() };
40323 } else if (tag === 'ia5str' || tag === 'utf8str') {
40324 return buffer.raw().toString();
40325 } else {
40326 return this.error('Decoding of string type: ' + tag + ' unsupported');
40327 }
40328};
40329
40330DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
40331 var identifiers = [];
40332 var ident = 0;
40333 while (!buffer.isEmpty()) {
40334 var subident = buffer.readUInt8();
40335 ident <<= 7;
40336 ident |= subident & 0x7f;
40337 if ((subident & 0x80) === 0) {
40338 identifiers.push(ident);
40339 ident = 0;
40340 }
40341 }
40342 if (subident & 0x80)
40343 identifiers.push(ident);
40344
40345 var first = (identifiers[0] / 40) | 0;
40346 var second = identifiers[0] % 40;
40347
40348 if (relative)
40349 result = identifiers;
40350 else
40351 result = [first, second].concat(identifiers.slice(1));
40352
40353 if (values)
40354 result = values[result.join(' ')];
40355
40356 return result;
40357};
40358
40359DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
40360 var str = buffer.raw().toString();
40361 if (tag === 'gentime') {
40362 var year = str.slice(0, 4) | 0;
40363 var mon = str.slice(4, 6) | 0;
40364 var day = str.slice(6, 8) | 0;
40365 var hour = str.slice(8, 10) | 0;
40366 var min = str.slice(10, 12) | 0;
40367 var sec = str.slice(12, 14) | 0;
40368 } else if (tag === 'utctime') {
40369 var year = str.slice(0, 2) | 0;
40370 var mon = str.slice(2, 4) | 0;
40371 var day = str.slice(4, 6) | 0;
40372 var hour = str.slice(6, 8) | 0;
40373 var min = str.slice(8, 10) | 0;
40374 var sec = str.slice(10, 12) | 0;
40375 if (year < 70)
40376 year = 2000 + year;
40377 else
40378 year = 1900 + year;
40379 } else {
40380 return this.error('Decoding ' + tag + ' time is not supported yet');
40381 }
40382
40383 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
40384};
40385
40386DERNode.prototype._decodeNull = function decodeNull(buffer) {
40387 return null;
40388};
40389
40390DERNode.prototype._decodeBool = function decodeBool(buffer) {
40391 var res = buffer.readUInt8();
40392 if (buffer.isError(res))
40393 return res;
40394 else
40395 return res !== 0;
40396};
40397
40398DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
40399 // Bigint, return as it is (assume big endian)
40400 var raw = buffer.raw();
40401 var res = new bignum(raw);
40402
40403 if (values)
40404 res = values[res.toString(10)] || res;
40405
40406 return res;
40407};
40408
40409DERNode.prototype._use = function use(entity, obj) {
40410 if (typeof entity === 'function')
40411 entity = entity(obj);
40412 return entity._getDecoder('der').tree;
40413};
40414
40415// Utility methods
40416
40417function derDecodeTag(buf, fail) {
40418 var tag = buf.readUInt8(fail);
40419 if (buf.isError(tag))
40420 return tag;
40421
40422 var cls = der.tagClass[tag >> 6];
40423 var primitive = (tag & 0x20) === 0;
40424
40425 // Multi-octet tag - load
40426 if ((tag & 0x1f) === 0x1f) {
40427 var oct = tag;
40428 tag = 0;
40429 while ((oct & 0x80) === 0x80) {
40430 oct = buf.readUInt8(fail);
40431 if (buf.isError(oct))
40432 return oct;
40433
40434 tag <<= 7;
40435 tag |= oct & 0x7f;
40436 }
40437 } else {
40438 tag &= 0x1f;
40439 }
40440 var tagStr = der.tag[tag];
40441
40442 return {
40443 cls: cls,
40444 primitive: primitive,
40445 tag: tag,
40446 tagStr: tagStr
40447 };
40448}
40449
40450function derDecodeLen(buf, primitive, fail) {
40451 var len = buf.readUInt8(fail);
40452 if (buf.isError(len))
40453 return len;
40454
40455 // Indefinite form
40456 if (!primitive && len === 0x80)
40457 return null;
40458
40459 // Definite form
40460 if ((len & 0x80) === 0) {
40461 // Short form
40462 return len;
40463 }
40464
40465 // Long form
40466 var num = len & 0x7f;
40467 if (num >= 4)
40468 return buf.error('length octect is too long');
40469
40470 len = 0;
40471 for (var i = 0; i < num; i++) {
40472 len <<= 8;
40473 var j = buf.readUInt8(fail);
40474 if (buf.isError(j))
40475 return j;
40476 len |= j;
40477 }
40478
40479 return len;
40480}
40481}, {"inherits":149,"../../asn1":229}],242: [function (exports, require, module, global) {var inherits = require('inherits');
40482var Buffer = require('buffer').Buffer;
40483
40484var asn1 = require('../../asn1');
40485var DERDecoder = require('./der');
40486
40487function PEMDecoder(entity) {
40488 DERDecoder.call(this, entity);
40489 this.enc = 'pem';
40490};
40491inherits(PEMDecoder, DERDecoder);
40492module.exports = PEMDecoder;
40493
40494PEMDecoder.prototype.decode = function decode(data, options) {
40495 var lines = data.toString().split(/[\r\n]+/g);
40496
40497 var label = options.label.toUpperCase();
40498
40499 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
40500 var start = -1;
40501 var end = -1;
40502 for (var i = 0; i < lines.length; i++) {
40503 var match = lines[i].match(re);
40504 if (match === null)
40505 continue;
40506
40507 if (match[2] !== label)
40508 continue;
40509
40510 if (start === -1) {
40511 if (match[1] !== 'BEGIN')
40512 break;
40513 start = i;
40514 } else {
40515 if (match[1] !== 'END')
40516 break;
40517 end = i;
40518 break;
40519 }
40520 }
40521 if (start === -1 || end === -1)
40522 throw new Error('PEM section not found for: ' + label);
40523
40524 var base64 = lines.slice(start + 1, end).join('');
40525 // Remove excessive symbols
40526 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
40527
40528 var input = new Buffer(base64, 'base64');
40529 return DERDecoder.prototype.decode.call(this, input, options);
40530};
40531}, {"inherits":149,"buffer":29,"../../asn1":229,"./der":241}],243: [function (exports, require, module, global) {var encoders = exports;
40532
40533encoders.der = require('./der');
40534encoders.pem = require('./pem');
40535}, {"./der":244,"./pem":245}],244: [function (exports, require, module, global) {var inherits = require('inherits');
40536var Buffer = require('buffer').Buffer;
40537
40538var asn1 = require('../../asn1');
40539var base = asn1.base;
40540var bignum = asn1.bignum;
40541
40542// Import DER constants
40543var der = asn1.constants.der;
40544
40545function DEREncoder(entity) {
40546 this.enc = 'der';
40547 this.name = entity.name;
40548 this.entity = entity;
40549
40550 // Construct base tree
40551 this.tree = new DERNode();
40552 this.tree._init(entity.body);
40553};
40554module.exports = DEREncoder;
40555
40556DEREncoder.prototype.encode = function encode(data, reporter) {
40557 return this.tree._encode(data, reporter).join();
40558};
40559
40560// Tree methods
40561
40562function DERNode(parent) {
40563 base.Node.call(this, 'der', parent);
40564}
40565inherits(DERNode, base.Node);
40566
40567DERNode.prototype._encodeComposite = function encodeComposite(tag,
40568 primitive,
40569 cls,
40570 content) {
40571 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
40572
40573 // Short form
40574 if (content.length < 0x80) {
40575 var header = new Buffer(2);
40576 header[0] = encodedTag;
40577 header[1] = content.length;
40578 return this._createEncoderBuffer([ header, content ]);
40579 }
40580
40581 // Long form
40582 // Count octets required to store length
40583 var lenOctets = 1;
40584 for (var i = content.length; i >= 0x100; i >>= 8)
40585 lenOctets++;
40586
40587 var header = new Buffer(1 + 1 + lenOctets);
40588 header[0] = encodedTag;
40589 header[1] = 0x80 | lenOctets;
40590
40591 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
40592 header[i] = j & 0xff;
40593
40594 return this._createEncoderBuffer([ header, content ]);
40595};
40596
40597DERNode.prototype._encodeStr = function encodeStr(str, tag) {
40598 if (tag === 'octstr')
40599 return this._createEncoderBuffer(str);
40600 else if (tag === 'bitstr')
40601 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
40602 else if (tag === 'ia5str' || tag === 'utf8str')
40603 return this._createEncoderBuffer(str);
40604 return this.reporter.error('Encoding of string type: ' + tag +
40605 ' unsupported');
40606};
40607
40608DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
40609 if (typeof id === 'string') {
40610 if (!values)
40611 return this.reporter.error('string objid given, but no values map found');
40612 if (!values.hasOwnProperty(id))
40613 return this.reporter.error('objid not found in values map');
40614 id = values[id].split(/[\s\.]+/g);
40615 for (var i = 0; i < id.length; i++)
40616 id[i] |= 0;
40617 } else if (Array.isArray(id)) {
40618 id = id.slice();
40619 for (var i = 0; i < id.length; i++)
40620 id[i] |= 0;
40621 }
40622
40623 if (!Array.isArray(id)) {
40624 return this.reporter.error('objid() should be either array or string, ' +
40625 'got: ' + JSON.stringify(id));
40626 }
40627
40628 if (!relative) {
40629 if (id[1] >= 40)
40630 return this.reporter.error('Second objid identifier OOB');
40631 id.splice(0, 2, id[0] * 40 + id[1]);
40632 }
40633
40634 // Count number of octets
40635 var size = 0;
40636 for (var i = 0; i < id.length; i++) {
40637 var ident = id[i];
40638 for (size++; ident >= 0x80; ident >>= 7)
40639 size++;
40640 }
40641
40642 var objid = new Buffer(size);
40643 var offset = objid.length - 1;
40644 for (var i = id.length - 1; i >= 0; i--) {
40645 var ident = id[i];
40646 objid[offset--] = ident & 0x7f;
40647 while ((ident >>= 7) > 0)
40648 objid[offset--] = 0x80 | (ident & 0x7f);
40649 }
40650
40651 return this._createEncoderBuffer(objid);
40652};
40653
40654function two(num) {
40655 if (num < 10)
40656 return '0' + num;
40657 else
40658 return num;
40659}
40660
40661DERNode.prototype._encodeTime = function encodeTime(time, tag) {
40662 var str;
40663 var date = new Date(time);
40664
40665 if (tag === 'gentime') {
40666 str = [
40667 two(date.getFullYear()),
40668 two(date.getUTCMonth() + 1),
40669 two(date.getUTCDate()),
40670 two(date.getUTCHours()),
40671 two(date.getUTCMinutes()),
40672 two(date.getUTCSeconds()),
40673 'Z'
40674 ].join('');
40675 } else if (tag === 'utctime') {
40676 str = [
40677 two(date.getFullYear() % 100),
40678 two(date.getUTCMonth() + 1),
40679 two(date.getUTCDate()),
40680 two(date.getUTCHours()),
40681 two(date.getUTCMinutes()),
40682 two(date.getUTCSeconds()),
40683 'Z'
40684 ].join('');
40685 } else {
40686 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
40687 }
40688
40689 return this._encodeStr(str, 'octstr');
40690};
40691
40692DERNode.prototype._encodeNull = function encodeNull() {
40693 return this._createEncoderBuffer('');
40694};
40695
40696DERNode.prototype._encodeInt = function encodeInt(num, values) {
40697 if (typeof num === 'string') {
40698 if (!values)
40699 return this.reporter.error('String int or enum given, but no values map');
40700 if (!values.hasOwnProperty(num)) {
40701 return this.reporter.error('Values map doesn\'t contain: ' +
40702 JSON.stringify(num));
40703 }
40704 num = values[num];
40705 }
40706
40707 // Bignum, assume big endian
40708 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
40709 var numArray = num.toArray();
40710 if (num.sign === false && numArray[0] & 0x80) {
40711 numArray.unshift(0);
40712 }
40713 num = new Buffer(numArray);
40714 }
40715
40716 if (Buffer.isBuffer(num)) {
40717 var size = num.length;
40718 if (num.length === 0)
40719 size++;
40720
40721 var out = new Buffer(size);
40722 num.copy(out);
40723 if (num.length === 0)
40724 out[0] = 0
40725 return this._createEncoderBuffer(out);
40726 }
40727
40728 if (num < 0x80)
40729 return this._createEncoderBuffer(num);
40730
40731 if (num < 0x100)
40732 return this._createEncoderBuffer([0, num]);
40733
40734 var size = 1;
40735 for (var i = num; i >= 0x100; i >>= 8)
40736 size++;
40737
40738 var out = new Array(size);
40739 for (var i = out.length - 1; i >= 0; i--) {
40740 out[i] = num & 0xff;
40741 num >>= 8;
40742 }
40743 if(out[0] & 0x80) {
40744 out.unshift(0);
40745 }
40746
40747 return this._createEncoderBuffer(new Buffer(out));
40748};
40749
40750DERNode.prototype._encodeBool = function encodeBool(value) {
40751 return this._createEncoderBuffer(value ? 0xff : 0);
40752};
40753
40754DERNode.prototype._use = function use(entity, obj) {
40755 if (typeof entity === 'function')
40756 entity = entity(obj);
40757 return entity._getEncoder('der').tree;
40758};
40759
40760DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
40761 var state = this._baseState;
40762 var i;
40763 if (state['default'] === null)
40764 return false;
40765
40766 var data = dataBuffer.join();
40767 if (state.defaultBuffer === undefined)
40768 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
40769
40770 if (data.length !== state.defaultBuffer.length)
40771 return false;
40772
40773 for (i=0; i < data.length; i++)
40774 if (data[i] !== state.defaultBuffer[i])
40775 return false;
40776
40777 return true;
40778};
40779
40780// Utility methods
40781
40782function encodeTag(tag, primitive, cls, reporter) {
40783 var res;
40784
40785 if (tag === 'seqof')
40786 tag = 'seq';
40787 else if (tag === 'setof')
40788 tag = 'set';
40789
40790 if (der.tagByName.hasOwnProperty(tag))
40791 res = der.tagByName[tag];
40792 else if (typeof tag === 'number' && (tag | 0) === tag)
40793 res = tag;
40794 else
40795 return reporter.error('Unknown tag: ' + tag);
40796
40797 if (res >= 0x1f)
40798 return reporter.error('Multi-octet tag encoding unsupported');
40799
40800 if (!primitive)
40801 res |= 0x20;
40802
40803 res |= (der.tagClassByName[cls || 'universal'] << 6);
40804
40805 return res;
40806}
40807}, {"inherits":149,"buffer":29,"../../asn1":229}],245: [function (exports, require, module, global) {var inherits = require('inherits');
40808var Buffer = require('buffer').Buffer;
40809
40810var asn1 = require('../../asn1');
40811var DEREncoder = require('./der');
40812
40813function PEMEncoder(entity) {
40814 DEREncoder.call(this, entity);
40815 this.enc = 'pem';
40816};
40817inherits(PEMEncoder, DEREncoder);
40818module.exports = PEMEncoder;
40819
40820PEMEncoder.prototype.encode = function encode(data, options) {
40821 var buf = DEREncoder.prototype.encode.call(this, data);
40822
40823 var p = buf.toString('base64');
40824 var out = [ '-----BEGIN ' + options.label + '-----' ];
40825 for (var i = 0; i < p.length; i += 64)
40826 out.push(p.slice(i, i + 64));
40827 out.push('-----END ' + options.label + '-----');
40828 return out.join('\n');
40829};
40830}, {"inherits":149,"buffer":29,"../../asn1":229,"./der":244}],246: [function (exports, require, module, global) {module.exports = {"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
40831"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
40832"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
40833"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
40834"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
40835"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
40836"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
40837"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
40838"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
40839"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
40840"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
40841"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
40842}}, {}],247: [function (exports, require, module, global) {// adapted from https://github.com/apatil/pemstrip
40843var findProc = /Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m
40844var startRegex = /^-----BEGIN (.*) KEY-----\r?\n/m
40845var fullRegex = /^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m
40846var evp = require('evp_bytestokey')
40847var ciphers = require('browserify-aes')
40848module.exports = function (okey, password) {
40849 var key = okey.toString()
40850 var match = key.match(findProc)
40851 var decrypted
40852 if (!match) {
40853 var match2 = key.match(fullRegex)
40854 decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64')
40855 } else {
40856 var suite = 'aes' + match[1]
40857 var iv = new Buffer(match[2], 'hex')
40858 var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64')
40859 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
40860 var out = []
40861 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
40862 out.push(cipher.update(cipherText))
40863 out.push(cipher.final())
40864 decrypted = Buffer.concat(out)
40865 }
40866 var tag = key.match(startRegex)[1] + ' KEY'
40867 return {
40868 tag: tag,
40869 data: decrypted
40870 }
40871}
40872}, {"evp_bytestokey":248,"browserify-aes":249}],248: [function (exports, require, module, global) {var md5 = require('create-hash/md5')
40873module.exports = EVP_BytesToKey
40874function EVP_BytesToKey (password, salt, keyLen, ivLen) {
40875 if (!Buffer.isBuffer(password)) {
40876 password = new Buffer(password, 'binary')
40877 }
40878 if (salt && !Buffer.isBuffer(salt)) {
40879 salt = new Buffer(salt, 'binary')
40880 }
40881 keyLen = keyLen / 8
40882 ivLen = ivLen || 0
40883 var ki = 0
40884 var ii = 0
40885 var key = new Buffer(keyLen)
40886 var iv = new Buffer(ivLen)
40887 var addmd = 0
40888 var md_buf
40889 var i
40890 var bufs = []
40891 while (true) {
40892 if (addmd++ > 0) {
40893 bufs.push(md_buf)
40894 }
40895 bufs.push(password)
40896 if (salt) {
40897 bufs.push(salt)
40898 }
40899 md_buf = md5(Buffer.concat(bufs))
40900 bufs = []
40901 i = 0
40902 if (keyLen > 0) {
40903 while (true) {
40904 if (keyLen === 0) {
40905 break
40906 }
40907 if (i === md_buf.length) {
40908 break
40909 }
40910 key[ki++] = md_buf[i]
40911 keyLen--
40912 i++
40913 }
40914 }
40915 if (ivLen > 0 && i !== md_buf.length) {
40916 while (true) {
40917 if (ivLen === 0) {
40918 break
40919 }
40920 if (i === md_buf.length) {
40921 break
40922 }
40923 iv[ii++] = md_buf[i]
40924 ivLen--
40925 i++
40926 }
40927 }
40928 if (keyLen === 0 && ivLen === 0) {
40929 break
40930 }
40931 }
40932 for (i = 0; i < md_buf.length; i++) {
40933 md_buf[i] = 0
40934 }
40935 return {
40936 key: key,
40937 iv: iv
40938 }
40939}
40940}, {"create-hash/md5":150}],249: [function (exports, require, module, global) {var ciphers = require('./encrypter')
40941exports.createCipher = exports.Cipher = ciphers.createCipher
40942exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
40943var deciphers = require('./decrypter')
40944exports.createDecipher = exports.Decipher = deciphers.createDecipher
40945exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
40946var modes = require('./modes')
40947function getCiphers () {
40948 return Object.keys(modes)
40949}
40950exports.listCiphers = exports.getCiphers = getCiphers
40951}, {"./encrypter":250,"./decrypter":265,"./modes":253}],250: [function (exports, require, module, global) {var aes = require('./aes')
40952var Transform = require('cipher-base')
40953var inherits = require('inherits')
40954var modes = require('./modes')
40955var ebtk = require('evp_bytestokey')
40956var StreamCipher = require('./streamCipher')
40957var AuthCipher = require('./authCipher')
40958inherits(Cipher, Transform)
40959function Cipher (mode, key, iv) {
40960 if (!(this instanceof Cipher)) {
40961 return new Cipher(mode, key, iv)
40962 }
40963 Transform.call(this)
40964 this._cache = new Splitter()
40965 this._cipher = new aes.AES(key)
40966 this._prev = new Buffer(iv.length)
40967 iv.copy(this._prev)
40968 this._mode = mode
40969 this._autopadding = true
40970}
40971Cipher.prototype._update = function (data) {
40972 this._cache.add(data)
40973 var chunk
40974 var thing
40975 var out = []
40976 while ((chunk = this._cache.get())) {
40977 thing = this._mode.encrypt(this, chunk)
40978 out.push(thing)
40979 }
40980 return Buffer.concat(out)
40981}
40982Cipher.prototype._final = function () {
40983 var chunk = this._cache.flush()
40984 if (this._autopadding) {
40985 chunk = this._mode.encrypt(this, chunk)
40986 this._cipher.scrub()
40987 return chunk
40988 } else if (chunk.toString('hex') !== '10101010101010101010101010101010') {
40989 this._cipher.scrub()
40990 throw new Error('data not multiple of block length')
40991 }
40992}
40993Cipher.prototype.setAutoPadding = function (setTo) {
40994 this._autopadding = !!setTo
40995}
40996
40997function Splitter () {
40998 if (!(this instanceof Splitter)) {
40999 return new Splitter()
41000 }
41001 this.cache = new Buffer('')
41002}
41003Splitter.prototype.add = function (data) {
41004 this.cache = Buffer.concat([this.cache, data])
41005}
41006
41007Splitter.prototype.get = function () {
41008 if (this.cache.length > 15) {
41009 var out = this.cache.slice(0, 16)
41010 this.cache = this.cache.slice(16)
41011 return out
41012 }
41013 return null
41014}
41015Splitter.prototype.flush = function () {
41016 var len = 16 - this.cache.length
41017 var padBuff = new Buffer(len)
41018
41019 var i = -1
41020 while (++i < len) {
41021 padBuff.writeUInt8(len, i)
41022 }
41023 var out = Buffer.concat([this.cache, padBuff])
41024 return out
41025}
41026var modelist = {
41027 ECB: require('./modes/ecb'),
41028 CBC: require('./modes/cbc'),
41029 CFB: require('./modes/cfb'),
41030 CFB8: require('./modes/cfb8'),
41031 CFB1: require('./modes/cfb1'),
41032 OFB: require('./modes/ofb'),
41033 CTR: require('./modes/ctr'),
41034 GCM: require('./modes/ctr')
41035}
41036
41037function createCipheriv (suite, password, iv) {
41038 var config = modes[suite.toLowerCase()]
41039 if (!config) {
41040 throw new TypeError('invalid suite type')
41041 }
41042 if (typeof iv === 'string') {
41043 iv = new Buffer(iv)
41044 }
41045 if (typeof password === 'string') {
41046 password = new Buffer(password)
41047 }
41048 if (password.length !== config.key / 8) {
41049 throw new TypeError('invalid key length ' + password.length)
41050 }
41051 if (iv.length !== config.iv) {
41052 throw new TypeError('invalid iv length ' + iv.length)
41053 }
41054 if (config.type === 'stream') {
41055 return new StreamCipher(modelist[config.mode], password, iv)
41056 } else if (config.type === 'auth') {
41057 return new AuthCipher(modelist[config.mode], password, iv)
41058 }
41059 return new Cipher(modelist[config.mode], password, iv)
41060}
41061function createCipher (suite, password) {
41062 var config = modes[suite.toLowerCase()]
41063 if (!config) {
41064 throw new TypeError('invalid suite type')
41065 }
41066 var keys = ebtk(password, false, config.key, config.iv)
41067 return createCipheriv(suite, keys.key, keys.iv)
41068}
41069
41070exports.createCipheriv = createCipheriv
41071exports.createCipher = createCipher
41072}, {"./aes":251,"cipher-base":252,"inherits":149,"./modes":253,"evp_bytestokey":248,"./streamCipher":254,"./authCipher":255,"./modes/ecb":258,"./modes/cbc":259,"./modes/cfb":260,"./modes/cfb8":261,"./modes/cfb1":262,"./modes/ofb":263,"./modes/ctr":264}],251: [function (exports, require, module, global) {// based on the aes implimentation in triple sec
41073// https://github.com/keybase/triplesec
41074
41075// which is in turn based on the one from crypto-js
41076// https://code.google.com/p/crypto-js/
41077
41078var uint_max = Math.pow(2, 32)
41079function fixup_uint32 (x) {
41080 var ret, x_pos
41081 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
41082 return ret
41083}
41084function scrub_vec (v) {
41085 for (var i = 0; i < v.length; v++) {
41086 v[i] = 0
41087 }
41088 return false
41089}
41090
41091function Global () {
41092 this.SBOX = []
41093 this.INV_SBOX = []
41094 this.SUB_MIX = [[], [], [], []]
41095 this.INV_SUB_MIX = [[], [], [], []]
41096 this.init()
41097 this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
41098}
41099
41100Global.prototype.init = function () {
41101 var d, i, sx, t, x, x2, x4, x8, xi, _i
41102 d = (function () {
41103 var _i, _results
41104 _results = []
41105 for (i = _i = 0; _i < 256; i = ++_i) {
41106 if (i < 128) {
41107 _results.push(i << 1)
41108 } else {
41109 _results.push((i << 1) ^ 0x11b)
41110 }
41111 }
41112 return _results
41113 })()
41114 x = 0
41115 xi = 0
41116 for (i = _i = 0; _i < 256; i = ++_i) {
41117 sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
41118 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
41119 this.SBOX[x] = sx
41120 this.INV_SBOX[sx] = x
41121 x2 = d[x]
41122 x4 = d[x2]
41123 x8 = d[x4]
41124 t = (d[sx] * 0x101) ^ (sx * 0x1010100)
41125 this.SUB_MIX[0][x] = (t << 24) | (t >>> 8)
41126 this.SUB_MIX[1][x] = (t << 16) | (t >>> 16)
41127 this.SUB_MIX[2][x] = (t << 8) | (t >>> 24)
41128 this.SUB_MIX[3][x] = t
41129 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
41130 this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
41131 this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
41132 this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
41133 this.INV_SUB_MIX[3][sx] = t
41134 if (x === 0) {
41135 x = xi = 1
41136 } else {
41137 x = x2 ^ d[d[d[x8 ^ x2]]]
41138 xi ^= d[d[xi]]
41139 }
41140 }
41141 return true
41142}
41143
41144var G = new Global()
41145
41146AES.blockSize = 4 * 4
41147
41148AES.prototype.blockSize = AES.blockSize
41149
41150AES.keySize = 256 / 8
41151
41152AES.prototype.keySize = AES.keySize
41153
41154function bufferToArray (buf) {
41155 var len = buf.length / 4
41156 var out = new Array(len)
41157 var i = -1
41158 while (++i < len) {
41159 out[i] = buf.readUInt32BE(i * 4)
41160 }
41161 return out
41162}
41163function AES (key) {
41164 this._key = bufferToArray(key)
41165 this._doReset()
41166}
41167
41168AES.prototype._doReset = function () {
41169 var invKsRow, keySize, keyWords, ksRow, ksRows, t
41170 keyWords = this._key
41171 keySize = keyWords.length
41172 this._nRounds = keySize + 6
41173 ksRows = (this._nRounds + 1) * 4
41174 this._keySchedule = []
41175 for (ksRow = 0; ksRow < ksRows; ksRow++) {
41176 this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t)
41177 }
41178 this._invKeySchedule = []
41179 for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
41180 ksRow = ksRows - invKsRow
41181 t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)]
41182 this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]]
41183 }
41184 return true
41185}
41186
41187AES.prototype.encryptBlock = function (M) {
41188 M = bufferToArray(new Buffer(M))
41189 var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX)
41190 var buf = new Buffer(16)
41191 buf.writeUInt32BE(out[0], 0)
41192 buf.writeUInt32BE(out[1], 4)
41193 buf.writeUInt32BE(out[2], 8)
41194 buf.writeUInt32BE(out[3], 12)
41195 return buf
41196}
41197
41198AES.prototype.decryptBlock = function (M) {
41199 M = bufferToArray(new Buffer(M))
41200 var temp = [M[3], M[1]]
41201 M[1] = temp[0]
41202 M[3] = temp[1]
41203 var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX)
41204 var buf = new Buffer(16)
41205 buf.writeUInt32BE(out[0], 0)
41206 buf.writeUInt32BE(out[3], 4)
41207 buf.writeUInt32BE(out[2], 8)
41208 buf.writeUInt32BE(out[1], 12)
41209 return buf
41210}
41211
41212AES.prototype.scrub = function () {
41213 scrub_vec(this._keySchedule)
41214 scrub_vec(this._invKeySchedule)
41215 scrub_vec(this._key)
41216}
41217
41218AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) {
41219 var ksRow, s0, s1, s2, s3, t0, t1, t2, t3
41220
41221 s0 = M[0] ^ keySchedule[0]
41222 s1 = M[1] ^ keySchedule[1]
41223 s2 = M[2] ^ keySchedule[2]
41224 s3 = M[3] ^ keySchedule[3]
41225 ksRow = 4
41226 for (var round = 1; round < this._nRounds; round++) {
41227 t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
41228 t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
41229 t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
41230 t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
41231 s0 = t0
41232 s1 = t1
41233 s2 = t2
41234 s3 = t3
41235 }
41236 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
41237 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
41238 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
41239 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
41240 return [
41241 fixup_uint32(t0),
41242 fixup_uint32(t1),
41243 fixup_uint32(t2),
41244 fixup_uint32(t3)
41245 ]
41246}
41247
41248exports.AES = AES
41249}, {}],252: [function (exports, require, module, global) {var Transform = require('stream').Transform
41250var inherits = require('inherits')
41251var StringDecoder = require('string_decoder').StringDecoder
41252module.exports = CipherBase
41253inherits(CipherBase, Transform)
41254function CipherBase (hashMode) {
41255 Transform.call(this)
41256 this.hashMode = typeof hashMode === 'string'
41257 if (this.hashMode) {
41258 this[hashMode] = this._finalOrDigest
41259 } else {
41260 this.final = this._finalOrDigest
41261 }
41262 this._decoder = null
41263 this._encoding = null
41264}
41265CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
41266 if (typeof data === 'string') {
41267 data = new Buffer(data, inputEnc)
41268 }
41269 var outData = this._update(data)
41270 if (this.hashMode) {
41271 return this
41272 }
41273 if (outputEnc) {
41274 outData = this._toString(outData, outputEnc)
41275 }
41276 return outData
41277}
41278
41279CipherBase.prototype.setAutoPadding = function () {}
41280
41281CipherBase.prototype.getAuthTag = function () {
41282 throw new Error('trying to get auth tag in unsupported state')
41283}
41284
41285CipherBase.prototype.setAuthTag = function () {
41286 throw new Error('trying to set auth tag in unsupported state')
41287}
41288
41289CipherBase.prototype.setAAD = function () {
41290 throw new Error('trying to set aad in unsupported state')
41291}
41292
41293CipherBase.prototype._transform = function (data, _, next) {
41294 var err
41295 try {
41296 if (this.hashMode) {
41297 this._update(data)
41298 } else {
41299 this.push(this._update(data))
41300 }
41301 } catch (e) {
41302 err = e
41303 } finally {
41304 next(err)
41305 }
41306}
41307CipherBase.prototype._flush = function (done) {
41308 var err
41309 try {
41310 this.push(this._final())
41311 } catch (e) {
41312 err = e
41313 } finally {
41314 done(err)
41315 }
41316}
41317CipherBase.prototype._finalOrDigest = function (outputEnc) {
41318 var outData = this._final() || new Buffer('')
41319 if (outputEnc) {
41320 outData = this._toString(outData, outputEnc, true)
41321 }
41322 return outData
41323}
41324
41325CipherBase.prototype._toString = function (value, enc, final) {
41326 if (!this._decoder) {
41327 this._decoder = new StringDecoder(enc)
41328 this._encoding = enc
41329 }
41330 if (this._encoding !== enc) {
41331 throw new Error('can\'t switch encodings')
41332 }
41333 var out = this._decoder.write(value)
41334 if (final) {
41335 out += this._decoder.end()
41336 }
41337 return out
41338}
41339}, {"stream":52,"inherits":149,"string_decoder":62}],253: [function (exports, require, module, global) {exports['aes-128-ecb'] = {
41340 cipher: 'AES',
41341 key: 128,
41342 iv: 0,
41343 mode: 'ECB',
41344 type: 'block'
41345}
41346exports['aes-192-ecb'] = {
41347 cipher: 'AES',
41348 key: 192,
41349 iv: 0,
41350 mode: 'ECB',
41351 type: 'block'
41352}
41353exports['aes-256-ecb'] = {
41354 cipher: 'AES',
41355 key: 256,
41356 iv: 0,
41357 mode: 'ECB',
41358 type: 'block'
41359}
41360exports['aes-128-cbc'] = {
41361 cipher: 'AES',
41362 key: 128,
41363 iv: 16,
41364 mode: 'CBC',
41365 type: 'block'
41366}
41367exports['aes-192-cbc'] = {
41368 cipher: 'AES',
41369 key: 192,
41370 iv: 16,
41371 mode: 'CBC',
41372 type: 'block'
41373}
41374exports['aes-256-cbc'] = {
41375 cipher: 'AES',
41376 key: 256,
41377 iv: 16,
41378 mode: 'CBC',
41379 type: 'block'
41380}
41381exports['aes128'] = exports['aes-128-cbc']
41382exports['aes192'] = exports['aes-192-cbc']
41383exports['aes256'] = exports['aes-256-cbc']
41384exports['aes-128-cfb'] = {
41385 cipher: 'AES',
41386 key: 128,
41387 iv: 16,
41388 mode: 'CFB',
41389 type: 'stream'
41390}
41391exports['aes-192-cfb'] = {
41392 cipher: 'AES',
41393 key: 192,
41394 iv: 16,
41395 mode: 'CFB',
41396 type: 'stream'
41397}
41398exports['aes-256-cfb'] = {
41399 cipher: 'AES',
41400 key: 256,
41401 iv: 16,
41402 mode: 'CFB',
41403 type: 'stream'
41404}
41405exports['aes-128-cfb8'] = {
41406 cipher: 'AES',
41407 key: 128,
41408 iv: 16,
41409 mode: 'CFB8',
41410 type: 'stream'
41411}
41412exports['aes-192-cfb8'] = {
41413 cipher: 'AES',
41414 key: 192,
41415 iv: 16,
41416 mode: 'CFB8',
41417 type: 'stream'
41418}
41419exports['aes-256-cfb8'] = {
41420 cipher: 'AES',
41421 key: 256,
41422 iv: 16,
41423 mode: 'CFB8',
41424 type: 'stream'
41425}
41426exports['aes-128-cfb1'] = {
41427 cipher: 'AES',
41428 key: 128,
41429 iv: 16,
41430 mode: 'CFB1',
41431 type: 'stream'
41432}
41433exports['aes-192-cfb1'] = {
41434 cipher: 'AES',
41435 key: 192,
41436 iv: 16,
41437 mode: 'CFB1',
41438 type: 'stream'
41439}
41440exports['aes-256-cfb1'] = {
41441 cipher: 'AES',
41442 key: 256,
41443 iv: 16,
41444 mode: 'CFB1',
41445 type: 'stream'
41446}
41447exports['aes-128-ofb'] = {
41448 cipher: 'AES',
41449 key: 128,
41450 iv: 16,
41451 mode: 'OFB',
41452 type: 'stream'
41453}
41454exports['aes-192-ofb'] = {
41455 cipher: 'AES',
41456 key: 192,
41457 iv: 16,
41458 mode: 'OFB',
41459 type: 'stream'
41460}
41461exports['aes-256-ofb'] = {
41462 cipher: 'AES',
41463 key: 256,
41464 iv: 16,
41465 mode: 'OFB',
41466 type: 'stream'
41467}
41468exports['aes-128-ctr'] = {
41469 cipher: 'AES',
41470 key: 128,
41471 iv: 16,
41472 mode: 'CTR',
41473 type: 'stream'
41474}
41475exports['aes-192-ctr'] = {
41476 cipher: 'AES',
41477 key: 192,
41478 iv: 16,
41479 mode: 'CTR',
41480 type: 'stream'
41481}
41482exports['aes-256-ctr'] = {
41483 cipher: 'AES',
41484 key: 256,
41485 iv: 16,
41486 mode: 'CTR',
41487 type: 'stream'
41488}
41489exports['aes-128-gcm'] = {
41490 cipher: 'AES',
41491 key: 128,
41492 iv: 12,
41493 mode: 'GCM',
41494 type: 'auth'
41495}
41496exports['aes-192-gcm'] = {
41497 cipher: 'AES',
41498 key: 192,
41499 iv: 12,
41500 mode: 'GCM',
41501 type: 'auth'
41502}
41503exports['aes-256-gcm'] = {
41504 cipher: 'AES',
41505 key: 256,
41506 iv: 12,
41507 mode: 'GCM',
41508 type: 'auth'
41509}
41510}, {}],254: [function (exports, require, module, global) {var aes = require('./aes')
41511var Transform = require('cipher-base')
41512var inherits = require('inherits')
41513
41514inherits(StreamCipher, Transform)
41515module.exports = StreamCipher
41516function StreamCipher (mode, key, iv, decrypt) {
41517 if (!(this instanceof StreamCipher)) {
41518 return new StreamCipher(mode, key, iv)
41519 }
41520 Transform.call(this)
41521 this._cipher = new aes.AES(key)
41522 this._prev = new Buffer(iv.length)
41523 this._cache = new Buffer('')
41524 this._secCache = new Buffer('')
41525 this._decrypt = decrypt
41526 iv.copy(this._prev)
41527 this._mode = mode
41528}
41529StreamCipher.prototype._update = function (chunk) {
41530 return this._mode.encrypt(this, chunk, this._decrypt)
41531}
41532StreamCipher.prototype._final = function () {
41533 this._cipher.scrub()
41534}
41535}, {"./aes":251,"cipher-base":252,"inherits":149}],255: [function (exports, require, module, global) {var aes = require('./aes')
41536var Transform = require('cipher-base')
41537var inherits = require('inherits')
41538var GHASH = require('./ghash')
41539var xor = require('buffer-xor')
41540inherits(StreamCipher, Transform)
41541module.exports = StreamCipher
41542
41543function StreamCipher (mode, key, iv, decrypt) {
41544 if (!(this instanceof StreamCipher)) {
41545 return new StreamCipher(mode, key, iv)
41546 }
41547 Transform.call(this)
41548 this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])])
41549 iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])])
41550 this._cipher = new aes.AES(key)
41551 this._prev = new Buffer(iv.length)
41552 this._cache = new Buffer('')
41553 this._secCache = new Buffer('')
41554 this._decrypt = decrypt
41555 this._alen = 0
41556 this._len = 0
41557 iv.copy(this._prev)
41558 this._mode = mode
41559 var h = new Buffer(4)
41560 h.fill(0)
41561 this._ghash = new GHASH(this._cipher.encryptBlock(h))
41562 this._authTag = null
41563 this._called = false
41564}
41565StreamCipher.prototype._update = function (chunk) {
41566 if (!this._called && this._alen) {
41567 var rump = 16 - (this._alen % 16)
41568 if (rump < 16) {
41569 rump = new Buffer(rump)
41570 rump.fill(0)
41571 this._ghash.update(rump)
41572 }
41573 }
41574 this._called = true
41575 var out = this._mode.encrypt(this, chunk)
41576 if (this._decrypt) {
41577 this._ghash.update(chunk)
41578 } else {
41579 this._ghash.update(out)
41580 }
41581 this._len += chunk.length
41582 return out
41583}
41584StreamCipher.prototype._final = function () {
41585 if (this._decrypt && !this._authTag) {
41586 throw new Error('Unsupported state or unable to authenticate data')
41587 }
41588 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
41589 if (this._decrypt) {
41590 if (xorTest(tag, this._authTag)) {
41591 throw new Error('Unsupported state or unable to authenticate data')
41592 }
41593 } else {
41594 this._authTag = tag
41595 }
41596 this._cipher.scrub()
41597}
41598StreamCipher.prototype.getAuthTag = function getAuthTag () {
41599 if (!this._decrypt && Buffer.isBuffer(this._authTag)) {
41600 return this._authTag
41601 } else {
41602 throw new Error('Attempting to get auth tag in unsupported state')
41603 }
41604}
41605StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
41606 if (this._decrypt) {
41607 this._authTag = tag
41608 } else {
41609 throw new Error('Attempting to set auth tag in unsupported state')
41610 }
41611}
41612StreamCipher.prototype.setAAD = function setAAD (buf) {
41613 if (!this._called) {
41614 this._ghash.update(buf)
41615 this._alen += buf.length
41616 } else {
41617 throw new Error('Attempting to set AAD in unsupported state')
41618 }
41619}
41620function xorTest (a, b) {
41621 var out = 0
41622 if (a.length !== b.length) {
41623 out++
41624 }
41625 var len = Math.min(a.length, b.length)
41626 var i = -1
41627 while (++i < len) {
41628 out += (a[i] ^ b[i])
41629 }
41630 return out
41631}
41632}, {"./aes":251,"cipher-base":252,"inherits":149,"./ghash":256,"buffer-xor":257}],256: [function (exports, require, module, global) {var zeros = new Buffer(16)
41633zeros.fill(0)
41634module.exports = GHASH
41635function GHASH (key) {
41636 this.h = key
41637 this.state = new Buffer(16)
41638 this.state.fill(0)
41639 this.cache = new Buffer('')
41640}
41641// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
41642// by Juho Vähä-Herttua
41643GHASH.prototype.ghash = function (block) {
41644 var i = -1
41645 while (++i < block.length) {
41646 this.state[i] ^= block[i]
41647 }
41648 this._multiply()
41649}
41650
41651GHASH.prototype._multiply = function () {
41652 var Vi = toArray(this.h)
41653 var Zi = [0, 0, 0, 0]
41654 var j, xi, lsb_Vi
41655 var i = -1
41656 while (++i < 128) {
41657 xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0
41658 if (xi) {
41659 // Z_i+1 = Z_i ^ V_i
41660 Zi = xor(Zi, Vi)
41661 }
41662
41663 // Store the value of LSB(V_i)
41664 lsb_Vi = (Vi[3] & 1) !== 0
41665
41666 // V_i+1 = V_i >> 1
41667 for (j = 3; j > 0; j--) {
41668 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
41669 }
41670 Vi[0] = Vi[0] >>> 1
41671
41672 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
41673 if (lsb_Vi) {
41674 Vi[0] = Vi[0] ^ (0xe1 << 24)
41675 }
41676 }
41677 this.state = fromArray(Zi)
41678}
41679GHASH.prototype.update = function (buf) {
41680 this.cache = Buffer.concat([this.cache, buf])
41681 var chunk
41682 while (this.cache.length >= 16) {
41683 chunk = this.cache.slice(0, 16)
41684 this.cache = this.cache.slice(16)
41685 this.ghash(chunk)
41686 }
41687}
41688GHASH.prototype.final = function (abl, bl) {
41689 if (this.cache.length) {
41690 this.ghash(Buffer.concat([this.cache, zeros], 16))
41691 }
41692 this.ghash(fromArray([
41693 0, abl,
41694 0, bl
41695 ]))
41696 return this.state
41697}
41698
41699function toArray (buf) {
41700 return [
41701 buf.readUInt32BE(0),
41702 buf.readUInt32BE(4),
41703 buf.readUInt32BE(8),
41704 buf.readUInt32BE(12)
41705 ]
41706}
41707function fromArray (out) {
41708 out = out.map(fixup_uint32)
41709 var buf = new Buffer(16)
41710 buf.writeUInt32BE(out[0], 0)
41711 buf.writeUInt32BE(out[1], 4)
41712 buf.writeUInt32BE(out[2], 8)
41713 buf.writeUInt32BE(out[3], 12)
41714 return buf
41715}
41716var uint_max = Math.pow(2, 32)
41717function fixup_uint32 (x) {
41718 var ret, x_pos
41719 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
41720 return ret
41721}
41722function xor (a, b) {
41723 return [
41724 a[0] ^ b[0],
41725 a[1] ^ b[1],
41726 a[2] ^ b[2],
41727 a[3] ^ b[3]
41728 ]
41729}
41730}, {}],257: [function (exports, require, module, global) {module.exports = function xor (a, b) {
41731 var length = Math.min(a.length, b.length)
41732 var buffer = new Buffer(length)
41733
41734 for (var i = 0; i < length; ++i) {
41735 buffer[i] = a[i] ^ b[i]
41736 }
41737
41738 return buffer
41739}
41740}, {}],258: [function (exports, require, module, global) {exports.encrypt = function (self, block) {
41741 return self._cipher.encryptBlock(block)
41742}
41743exports.decrypt = function (self, block) {
41744 return self._cipher.decryptBlock(block)
41745}
41746}, {}],259: [function (exports, require, module, global) {var xor = require('buffer-xor')
41747
41748exports.encrypt = function (self, block) {
41749 var data = xor(block, self._prev)
41750
41751 self._prev = self._cipher.encryptBlock(data)
41752 return self._prev
41753}
41754
41755exports.decrypt = function (self, block) {
41756 var pad = self._prev
41757
41758 self._prev = block
41759 var out = self._cipher.decryptBlock(block)
41760
41761 return xor(out, pad)
41762}
41763}, {"buffer-xor":257}],260: [function (exports, require, module, global) {var xor = require('buffer-xor')
41764
41765exports.encrypt = function (self, data, decrypt) {
41766 var out = new Buffer('')
41767 var len
41768
41769 while (data.length) {
41770 if (self._cache.length === 0) {
41771 self._cache = self._cipher.encryptBlock(self._prev)
41772 self._prev = new Buffer('')
41773 }
41774
41775 if (self._cache.length <= data.length) {
41776 len = self._cache.length
41777 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
41778 data = data.slice(len)
41779 } else {
41780 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
41781 break
41782 }
41783 }
41784
41785 return out
41786}
41787function encryptStart (self, data, decrypt) {
41788 var len = data.length
41789 var out = xor(data, self._cache)
41790 self._cache = self._cache.slice(len)
41791 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
41792 return out
41793}
41794}, {"buffer-xor":257}],261: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
41795 var pad = self._cipher.encryptBlock(self._prev)
41796 var out = pad[0] ^ byteParam
41797 self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])])
41798 return out
41799}
41800exports.encrypt = function (self, chunk, decrypt) {
41801 var len = chunk.length
41802 var out = new Buffer(len)
41803 var i = -1
41804 while (++i < len) {
41805 out[i] = encryptByte(self, chunk[i], decrypt)
41806 }
41807 return out
41808}
41809}, {}],262: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
41810 var pad
41811 var i = -1
41812 var len = 8
41813 var out = 0
41814 var bit, value
41815 while (++i < len) {
41816 pad = self._cipher.encryptBlock(self._prev)
41817 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
41818 value = pad[0] ^ bit
41819 out += ((value & 0x80) >> (i % 8))
41820 self._prev = shiftIn(self._prev, decrypt ? bit : value)
41821 }
41822 return out
41823}
41824exports.encrypt = function (self, chunk, decrypt) {
41825 var len = chunk.length
41826 var out = new Buffer(len)
41827 var i = -1
41828 while (++i < len) {
41829 out[i] = encryptByte(self, chunk[i], decrypt)
41830 }
41831 return out
41832}
41833function shiftIn (buffer, value) {
41834 var len = buffer.length
41835 var i = -1
41836 var out = new Buffer(buffer.length)
41837 buffer = Buffer.concat([buffer, new Buffer([value])])
41838 while (++i < len) {
41839 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
41840 }
41841 return out
41842}
41843}, {}],263: [function (exports, require, module, global) {var xor = require('buffer-xor')
41844
41845function getBlock (self) {
41846 self._prev = self._cipher.encryptBlock(self._prev)
41847 return self._prev
41848}
41849
41850exports.encrypt = function (self, chunk) {
41851 while (self._cache.length < chunk.length) {
41852 self._cache = Buffer.concat([self._cache, getBlock(self)])
41853 }
41854
41855 var pad = self._cache.slice(0, chunk.length)
41856 self._cache = self._cache.slice(chunk.length)
41857 return xor(chunk, pad)
41858}
41859}, {"buffer-xor":257}],264: [function (exports, require, module, global) {var xor = require('buffer-xor')
41860
41861function incr32 (iv) {
41862 var len = iv.length
41863 var item
41864 while (len--) {
41865 item = iv.readUInt8(len)
41866 if (item === 255) {
41867 iv.writeUInt8(0, len)
41868 } else {
41869 item++
41870 iv.writeUInt8(item, len)
41871 break
41872 }
41873 }
41874}
41875
41876function getBlock (self) {
41877 var out = self._cipher.encryptBlock(self._prev)
41878 incr32(self._prev)
41879 return out
41880}
41881
41882exports.encrypt = function (self, chunk) {
41883 while (self._cache.length < chunk.length) {
41884 self._cache = Buffer.concat([self._cache, getBlock(self)])
41885 }
41886 var pad = self._cache.slice(0, chunk.length)
41887 self._cache = self._cache.slice(chunk.length)
41888 return xor(chunk, pad)
41889}
41890}, {"buffer-xor":257}],265: [function (exports, require, module, global) {var aes = require('./aes')
41891var Transform = require('cipher-base')
41892var inherits = require('inherits')
41893var modes = require('./modes')
41894var StreamCipher = require('./streamCipher')
41895var AuthCipher = require('./authCipher')
41896var ebtk = require('evp_bytestokey')
41897
41898inherits(Decipher, Transform)
41899function Decipher (mode, key, iv) {
41900 if (!(this instanceof Decipher)) {
41901 return new Decipher(mode, key, iv)
41902 }
41903 Transform.call(this)
41904 this._cache = new Splitter()
41905 this._last = void 0
41906 this._cipher = new aes.AES(key)
41907 this._prev = new Buffer(iv.length)
41908 iv.copy(this._prev)
41909 this._mode = mode
41910 this._autopadding = true
41911}
41912Decipher.prototype._update = function (data) {
41913 this._cache.add(data)
41914 var chunk
41915 var thing
41916 var out = []
41917 while ((chunk = this._cache.get(this._autopadding))) {
41918 thing = this._mode.decrypt(this, chunk)
41919 out.push(thing)
41920 }
41921 return Buffer.concat(out)
41922}
41923Decipher.prototype._final = function () {
41924 var chunk = this._cache.flush()
41925 if (this._autopadding) {
41926 return unpad(this._mode.decrypt(this, chunk))
41927 } else if (chunk) {
41928 throw new Error('data not multiple of block length')
41929 }
41930}
41931Decipher.prototype.setAutoPadding = function (setTo) {
41932 this._autopadding = !!setTo
41933}
41934function Splitter () {
41935 if (!(this instanceof Splitter)) {
41936 return new Splitter()
41937 }
41938 this.cache = new Buffer('')
41939}
41940Splitter.prototype.add = function (data) {
41941 this.cache = Buffer.concat([this.cache, data])
41942}
41943
41944Splitter.prototype.get = function (autoPadding) {
41945 var out
41946 if (autoPadding) {
41947 if (this.cache.length > 16) {
41948 out = this.cache.slice(0, 16)
41949 this.cache = this.cache.slice(16)
41950 return out
41951 }
41952 } else {
41953 if (this.cache.length >= 16) {
41954 out = this.cache.slice(0, 16)
41955 this.cache = this.cache.slice(16)
41956 return out
41957 }
41958 }
41959 return null
41960}
41961Splitter.prototype.flush = function () {
41962 if (this.cache.length) {
41963 return this.cache
41964 }
41965}
41966function unpad (last) {
41967 var padded = last[15]
41968 var i = -1
41969 while (++i < padded) {
41970 if (last[(i + (16 - padded))] !== padded) {
41971 throw new Error('unable to decrypt data')
41972 }
41973 }
41974 if (padded === 16) {
41975 return
41976 }
41977 return last.slice(0, 16 - padded)
41978}
41979
41980var modelist = {
41981 ECB: require('./modes/ecb'),
41982 CBC: require('./modes/cbc'),
41983 CFB: require('./modes/cfb'),
41984 CFB8: require('./modes/cfb8'),
41985 CFB1: require('./modes/cfb1'),
41986 OFB: require('./modes/ofb'),
41987 CTR: require('./modes/ctr'),
41988 GCM: require('./modes/ctr')
41989}
41990
41991function createDecipheriv (suite, password, iv) {
41992 var config = modes[suite.toLowerCase()]
41993 if (!config) {
41994 throw new TypeError('invalid suite type')
41995 }
41996 if (typeof iv === 'string') {
41997 iv = new Buffer(iv)
41998 }
41999 if (typeof password === 'string') {
42000 password = new Buffer(password)
42001 }
42002 if (password.length !== config.key / 8) {
42003 throw new TypeError('invalid key length ' + password.length)
42004 }
42005 if (iv.length !== config.iv) {
42006 throw new TypeError('invalid iv length ' + iv.length)
42007 }
42008 if (config.type === 'stream') {
42009 return new StreamCipher(modelist[config.mode], password, iv, true)
42010 } else if (config.type === 'auth') {
42011 return new AuthCipher(modelist[config.mode], password, iv, true)
42012 }
42013 return new Decipher(modelist[config.mode], password, iv)
42014}
42015
42016function createDecipher (suite, password) {
42017 var config = modes[suite.toLowerCase()]
42018 if (!config) {
42019 throw new TypeError('invalid suite type')
42020 }
42021 var keys = ebtk(password, false, config.key, config.iv)
42022 return createDecipheriv(suite, keys.key, keys.iv)
42023}
42024exports.createDecipher = createDecipher
42025exports.createDecipheriv = createDecipheriv
42026}, {"./aes":251,"cipher-base":252,"inherits":149,"./modes":253,"./streamCipher":254,"./authCipher":255,"evp_bytestokey":248,"./modes/ecb":258,"./modes/cbc":259,"./modes/cfb":260,"./modes/cfb8":261,"./modes/cfb1":262,"./modes/ofb":263,"./modes/ctr":264}],266: [function (exports, require, module, global) {// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
42027var curves = require('./curves')
42028var elliptic = require('elliptic')
42029var parseKeys = require('parse-asn1')
42030
42031var BN = require('bn.js')
42032var EC = elliptic.ec
42033
42034function verify (sig, hash, key, signType) {
42035 var pub = parseKeys(key)
42036 if (pub.type === 'ec') {
42037 if (signType !== 'ecdsa') {
42038 throw new Error('wrong public key type')
42039 }
42040 return ecVerify(sig, hash, pub)
42041 } else if (pub.type === 'dsa') {
42042 if (signType !== 'dsa') {
42043 throw new Error('wrong public key type')
42044 }
42045 return dsaVerify(sig, hash, pub)
42046 } else {
42047 if (signType !== 'rsa') {
42048 throw new Error('wrong public key type')
42049 }
42050 }
42051 var len = pub.modulus.byteLength()
42052 var pad = [ 1 ]
42053 var padNum = 0
42054 while (hash.length + pad.length + 2 < len) {
42055 pad.push(0xff)
42056 padNum++
42057 }
42058 pad.push(0x00)
42059 var i = -1
42060 while (++i < hash.length) {
42061 pad.push(hash[i])
42062 }
42063 pad = new Buffer(pad)
42064 var red = BN.mont(pub.modulus)
42065 sig = new BN(sig).toRed(red)
42066
42067 sig = sig.redPow(new BN(pub.publicExponent))
42068
42069 sig = new Buffer(sig.fromRed().toArray())
42070 var out = 0
42071 if (padNum < 8) {
42072 out = 1
42073 }
42074 len = Math.min(sig.length, pad.length)
42075 if (sig.length !== pad.length) {
42076 out = 1
42077 }
42078
42079 i = -1
42080 while (++i < len) {
42081 out |= (sig[i] ^ pad[i])
42082 }
42083 return out === 0
42084}
42085
42086function ecVerify (sig, hash, pub) {
42087 var curveId = curves[pub.data.algorithm.curve.join('.')]
42088 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
42089
42090 var curve = new EC(curveId)
42091 var pubkey = pub.data.subjectPrivateKey.data
42092
42093 return curve.verify(hash, sig, pubkey)
42094}
42095
42096function dsaVerify (sig, hash, pub) {
42097 var p = pub.data.p
42098 var q = pub.data.q
42099 var g = pub.data.g
42100 var y = pub.data.pub_key
42101 var unpacked = parseKeys.signature.decode(sig, 'der')
42102 var s = unpacked.s
42103 var r = unpacked.r
42104 checkValue(s, q)
42105 checkValue(r, q)
42106 var montp = BN.mont(p)
42107 var w = s.invm(q)
42108 var v = g.toRed(montp)
42109 .redPow(new BN(hash).mul(w).mod(q))
42110 .fromRed()
42111 .mul(
42112 y.toRed(montp)
42113 .redPow(r.mul(w).mod(q))
42114 .fromRed()
42115 ).mod(p).mod(q)
42116 return !v.cmp(r)
42117}
42118
42119function checkValue (b, q) {
42120 if (b.cmpn(0) <= 0) {
42121 throw new Error('invalid sig')
42122 }
42123 if (b.cmp(q) >= q) {
42124 throw new Error('invalid sig')
42125 }
42126}
42127
42128module.exports = verify
42129}, {"./curves":205,"elliptic":206,"parse-asn1":227,"bn.js":204}],267: [function (exports, require, module, global) {var elliptic = require('elliptic');
42130var BN = require('bn.js');
42131
42132module.exports = function createECDH(curve) {
42133 return new ECDH(curve);
42134};
42135
42136var aliases = {
42137 secp256k1: {
42138 name: 'secp256k1',
42139 byteLength: 32
42140 },
42141 secp224r1: {
42142 name: 'p224',
42143 byteLength: 28
42144 },
42145 prime256v1: {
42146 name: 'p256',
42147 byteLength: 32
42148 },
42149 prime192v1: {
42150 name: 'p192',
42151 byteLength: 24
42152 },
42153 ed25519: {
42154 name: 'ed25519',
42155 byteLength: 32
42156 }
42157};
42158
42159aliases.p224 = aliases.secp224r1;
42160aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
42161aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
42162
42163function ECDH(curve) {
42164 this.curveType = aliases[curve];
42165 if (!this.curveType ) {
42166 this.curveType = {
42167 name: curve
42168 };
42169 }
42170 this.curve = new elliptic.ec(this.curveType.name);
42171 this.keys = void 0;
42172}
42173
42174ECDH.prototype.generateKeys = function (enc, format) {
42175 this.keys = this.curve.genKeyPair();
42176 return this.getPublicKey(enc, format);
42177};
42178
42179ECDH.prototype.computeSecret = function (other, inenc, enc) {
42180 inenc = inenc || 'utf8';
42181 if (!Buffer.isBuffer(other)) {
42182 other = new Buffer(other, inenc);
42183 }
42184 var otherPub = this.curve.keyFromPublic(other).getPublic();
42185 var out = otherPub.mul(this.keys.getPrivate()).getX();
42186 return formatReturnValue(out, enc, this.curveType.byteLength);
42187};
42188
42189ECDH.prototype.getPublicKey = function (enc, format) {
42190 var key = this.keys.getPublic(format === 'compressed', true);
42191 if (format === 'hybrid') {
42192 if (key[key.length - 1] % 2) {
42193 key[0] = 7;
42194 } else {
42195 key [0] = 6;
42196 }
42197 }
42198 return formatReturnValue(key, enc);
42199};
42200
42201ECDH.prototype.getPrivateKey = function (enc) {
42202 return formatReturnValue(this.keys.getPrivate(), enc);
42203};
42204
42205ECDH.prototype.setPublicKey = function (pub, enc) {
42206 enc = enc || 'utf8';
42207 if (!Buffer.isBuffer(pub)) {
42208 pub = new Buffer(pub, enc);
42209 }
42210 this.keys._importPublic(pub);
42211 return this;
42212};
42213
42214ECDH.prototype.setPrivateKey = function (priv, enc) {
42215 enc = enc || 'utf8';
42216 if (!Buffer.isBuffer(priv)) {
42217 priv = new Buffer(priv, enc);
42218 }
42219 var _priv = new BN(priv);
42220 _priv = _priv.toString(16);
42221 this.keys._importPrivate(_priv);
42222 return this;
42223};
42224
42225function formatReturnValue(bn, enc, len) {
42226 if (!Array.isArray(bn)) {
42227 bn = bn.toArray();
42228 }
42229 var buf = new Buffer(bn);
42230 if (len && buf.length < len) {
42231 var zeros = new Buffer(len - buf.length);
42232 zeros.fill(0);
42233 buf = Buffer.concat([zeros, buf]);
42234 }
42235 if (!enc) {
42236 return buf;
42237 } else {
42238 return buf.toString(enc);
42239 }
42240}
42241}, {"elliptic":268,"bn.js":281}],268: [function (exports, require, module, global) {'use strict';
42242
42243var elliptic = exports;
42244
42245elliptic.version = require('../package.json').version;
42246elliptic.utils = require('./elliptic/utils');
42247elliptic.rand = require('brorand');
42248elliptic.hmacDRBG = require('./elliptic/hmac-drbg');
42249elliptic.curve = require('./elliptic/curve');
42250elliptic.curves = require('./elliptic/curves');
42251
42252// Protocols
42253elliptic.ec = require('./elliptic/ec');
42254}, {"../package.json":269,"./elliptic/utils":270,"brorand":271,"./elliptic/hmac-drbg":272,"./elliptic/curve":279,"./elliptic/curves":285,"./elliptic/ec":287}],269: [function (exports, require, module, global) {module.exports = {
42255 "name": "elliptic",
42256 "version": "3.1.0",
42257 "description": "EC cryptography",
42258 "main": "lib/elliptic.js",
42259 "scripts": {
42260 "test": "make lint && mocha --reporter=spec test/*-test.js"
42261 },
42262 "repository": {
42263 "type": "git",
42264 "url": "git+ssh://git@github.com/indutny/elliptic.git"
42265 },
42266 "keywords": [
42267 "EC",
42268 "Elliptic",
42269 "curve",
42270 "Cryptography"
42271 ],
42272 "author": {
42273 "name": "Fedor Indutny",
42274 "email": "fedor@indutny.com"
42275 },
42276 "license": "MIT",
42277 "bugs": {
42278 "url": "https://github.com/indutny/elliptic/issues"
42279 },
42280 "homepage": "https://github.com/indutny/elliptic",
42281 "devDependencies": {
42282 "browserify": "^3.44.2",
42283 "jscs": "^1.11.3",
42284 "jshint": "^2.6.0",
42285 "mocha": "^2.1.0",
42286 "uglify-js": "^2.4.13"
42287 },
42288 "dependencies": {
42289 "bn.js": "^2.0.3",
42290 "brorand": "^1.0.1",
42291 "hash.js": "^1.0.0",
42292 "inherits": "^2.0.1"
42293 },
42294 "gitHead": "d86cd2a8178f7e7cecbd6dd92eea084e2ab44c13",
42295 "_id": "elliptic@3.1.0",
42296 "_shasum": "c21682ef762769b56a74201609105da11d5f60cc",
42297 "_from": "elliptic@>=3.0.0 <4.0.0",
42298 "_npmVersion": "2.11.0",
42299 "_nodeVersion": "2.2.1",
42300 "_npmUser": {
42301 "name": "indutny",
42302 "email": "fedor@indutny.com"
42303 },
42304 "maintainers": [
42305 {
42306 "name": "indutny",
42307 "email": "fedor@indutny.com"
42308 }
42309 ],
42310 "dist": {
42311 "shasum": "c21682ef762769b56a74201609105da11d5f60cc",
42312 "tarball": "http://registry.npmjs.org/elliptic/-/elliptic-3.1.0.tgz"
42313 },
42314 "directories": {},
42315 "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-3.1.0.tgz",
42316 "readme": "ERROR: No README data found!"
42317}
42318}, {}],270: [function (exports, require, module, global) {'use strict';
42319
42320var utils = exports;
42321
42322utils.assert = function assert(val, msg) {
42323 if (!val)
42324 throw new Error(msg || 'Assertion failed');
42325};
42326
42327function toArray(msg, enc) {
42328 if (Array.isArray(msg))
42329 return msg.slice();
42330 if (!msg)
42331 return [];
42332 var res = [];
42333 if (typeof msg !== 'string') {
42334 for (var i = 0; i < msg.length; i++)
42335 res[i] = msg[i] | 0;
42336 return res;
42337 }
42338 if (!enc) {
42339 for (var i = 0; i < msg.length; i++) {
42340 var c = msg.charCodeAt(i);
42341 var hi = c >> 8;
42342 var lo = c & 0xff;
42343 if (hi)
42344 res.push(hi, lo);
42345 else
42346 res.push(lo);
42347 }
42348 } else if (enc === 'hex') {
42349 msg = msg.replace(/[^a-z0-9]+/ig, '');
42350 if (msg.length % 2 !== 0)
42351 msg = '0' + msg;
42352 for (var i = 0; i < msg.length; i += 2)
42353 res.push(parseInt(msg[i] + msg[i + 1], 16));
42354 }
42355 return res;
42356}
42357utils.toArray = toArray;
42358
42359function zero2(word) {
42360 if (word.length === 1)
42361 return '0' + word;
42362 else
42363 return word;
42364}
42365utils.zero2 = zero2;
42366
42367function toHex(msg) {
42368 var res = '';
42369 for (var i = 0; i < msg.length; i++)
42370 res += zero2(msg[i].toString(16));
42371 return res;
42372}
42373utils.toHex = toHex;
42374
42375utils.encode = function encode(arr, enc) {
42376 if (enc === 'hex')
42377 return toHex(arr);
42378 else
42379 return arr;
42380};
42381
42382// Represent num in a w-NAF form
42383function getNAF(num, w) {
42384 var naf = [];
42385 var ws = 1 << (w + 1);
42386 var k = num.clone();
42387 while (k.cmpn(1) >= 0) {
42388 var z;
42389 if (k.isOdd()) {
42390 var mod = k.andln(ws - 1);
42391 if (mod > (ws >> 1) - 1)
42392 z = (ws >> 1) - mod;
42393 else
42394 z = mod;
42395 k.isubn(z);
42396 } else {
42397 z = 0;
42398 }
42399 naf.push(z);
42400
42401 // Optimization, shift by word if possible
42402 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
42403 for (var i = 1; i < shift; i++)
42404 naf.push(0);
42405 k.ishrn(shift);
42406 }
42407
42408 return naf;
42409}
42410utils.getNAF = getNAF;
42411
42412// Represent k1, k2 in a Joint Sparse Form
42413function getJSF(k1, k2) {
42414 var jsf = [
42415 [],
42416 []
42417 ];
42418
42419 k1 = k1.clone();
42420 k2 = k2.clone();
42421 var d1 = 0;
42422 var d2 = 0;
42423 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
42424
42425 // First phase
42426 var m14 = (k1.andln(3) + d1) & 3;
42427 var m24 = (k2.andln(3) + d2) & 3;
42428 if (m14 === 3)
42429 m14 = -1;
42430 if (m24 === 3)
42431 m24 = -1;
42432 var u1;
42433 if ((m14 & 1) === 0) {
42434 u1 = 0;
42435 } else {
42436 var m8 = (k1.andln(7) + d1) & 7;
42437 if ((m8 === 3 || m8 === 5) && m24 === 2)
42438 u1 = -m14;
42439 else
42440 u1 = m14;
42441 }
42442 jsf[0].push(u1);
42443
42444 var u2;
42445 if ((m24 & 1) === 0) {
42446 u2 = 0;
42447 } else {
42448 var m8 = (k2.andln(7) + d2) & 7;
42449 if ((m8 === 3 || m8 === 5) && m14 === 2)
42450 u2 = -m24;
42451 else
42452 u2 = m24;
42453 }
42454 jsf[1].push(u2);
42455
42456 // Second phase
42457 if (2 * d1 === u1 + 1)
42458 d1 = 1 - d1;
42459 if (2 * d2 === u2 + 1)
42460 d2 = 1 - d2;
42461 k1.ishrn(1);
42462 k2.ishrn(1);
42463 }
42464
42465 return jsf;
42466}
42467utils.getJSF = getJSF;
42468}, {}],271: [function (exports, require, module, global) {var r;
42469
42470module.exports = function rand(len) {
42471 if (!r)
42472 r = new Rand(null);
42473
42474 return r.generate(len);
42475};
42476
42477function Rand(rand) {
42478 this.rand = rand;
42479}
42480module.exports.Rand = Rand;
42481
42482Rand.prototype.generate = function generate(len) {
42483 return this._rand(len);
42484};
42485
42486if (typeof window === 'object') {
42487 if (window.crypto && window.crypto.getRandomValues) {
42488 // Modern browsers
42489 Rand.prototype._rand = function _rand(n) {
42490 var arr = new Uint8Array(n);
42491 window.crypto.getRandomValues(arr);
42492 return arr;
42493 };
42494 } else if (window.msCrypto && window.msCrypto.getRandomValues) {
42495 // IE
42496 Rand.prototype._rand = function _rand(n) {
42497 var arr = new Uint8Array(n);
42498 window.msCrypto.getRandomValues(arr);
42499 return arr;
42500 };
42501 } else {
42502 // Old junk
42503 Rand.prototype._rand = function() {
42504 throw new Error('Not implemented yet');
42505 };
42506 }
42507} else {
42508 // Node.js or Web worker
42509 try {
42510 var crypto = require('cry' + 'pto');
42511
42512 Rand.prototype._rand = function _rand(n) {
42513 return crypto.randomBytes(n);
42514 };
42515 } catch (e) {
42516 // Emulate crypto API using randy
42517 Rand.prototype._rand = function _rand(n) {
42518 var res = new Uint8Array(n);
42519 for (var i = 0; i < res.length; i++)
42520 res[i] = this.rand.getByte();
42521 return res;
42522 };
42523 }
42524}
42525}, {}],272: [function (exports, require, module, global) {'use strict';
42526
42527var hash = require('hash.js');
42528var elliptic = require('../elliptic');
42529var utils = elliptic.utils;
42530var assert = utils.assert;
42531
42532function HmacDRBG(options) {
42533 if (!(this instanceof HmacDRBG))
42534 return new HmacDRBG(options);
42535 this.hash = options.hash;
42536 this.predResist = !!options.predResist;
42537
42538 this.outLen = this.hash.outSize;
42539 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
42540
42541 this.reseed = null;
42542 this.reseedInterval = null;
42543 this.K = null;
42544 this.V = null;
42545
42546 var entropy = utils.toArray(options.entropy, options.entropyEnc);
42547 var nonce = utils.toArray(options.nonce, options.nonceEnc);
42548 var pers = utils.toArray(options.pers, options.persEnc);
42549 assert(entropy.length >= (this.minEntropy / 8),
42550 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42551 this._init(entropy, nonce, pers);
42552}
42553module.exports = HmacDRBG;
42554
42555HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
42556 var seed = entropy.concat(nonce).concat(pers);
42557
42558 this.K = new Array(this.outLen / 8);
42559 this.V = new Array(this.outLen / 8);
42560 for (var i = 0; i < this.V.length; i++) {
42561 this.K[i] = 0x00;
42562 this.V[i] = 0x01;
42563 }
42564
42565 this._update(seed);
42566 this.reseed = 1;
42567 this.reseedInterval = 0x1000000000000; // 2^48
42568};
42569
42570HmacDRBG.prototype._hmac = function hmac() {
42571 return new hash.hmac(this.hash, this.K);
42572};
42573
42574HmacDRBG.prototype._update = function update(seed) {
42575 var kmac = this._hmac()
42576 .update(this.V)
42577 .update([ 0x00 ]);
42578 if (seed)
42579 kmac = kmac.update(seed);
42580 this.K = kmac.digest();
42581 this.V = this._hmac().update(this.V).digest();
42582 if (!seed)
42583 return;
42584
42585 this.K = this._hmac()
42586 .update(this.V)
42587 .update([ 0x01 ])
42588 .update(seed)
42589 .digest();
42590 this.V = this._hmac().update(this.V).digest();
42591};
42592
42593HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
42594 // Optional entropy enc
42595 if (typeof entropyEnc !== 'string') {
42596 addEnc = add;
42597 add = entropyEnc;
42598 entropyEnc = null;
42599 }
42600
42601 entropy = utils.toBuffer(entropy, entropyEnc);
42602 add = utils.toBuffer(add, addEnc);
42603
42604 assert(entropy.length >= (this.minEntropy / 8),
42605 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
42606
42607 this._update(entropy.concat(add || []));
42608 this.reseed = 1;
42609};
42610
42611HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
42612 if (this.reseed > this.reseedInterval)
42613 throw new Error('Reseed is required');
42614
42615 // Optional encoding
42616 if (typeof enc !== 'string') {
42617 addEnc = add;
42618 add = enc;
42619 enc = null;
42620 }
42621
42622 // Optional additional data
42623 if (add) {
42624 add = utils.toArray(add, addEnc);
42625 this._update(add);
42626 }
42627
42628 var temp = [];
42629 while (temp.length < len) {
42630 this.V = this._hmac().update(this.V).digest();
42631 temp = temp.concat(this.V);
42632 }
42633
42634 var res = temp.slice(0, len);
42635 this._update(add);
42636 this.reseed++;
42637 return utils.encode(res, enc);
42638};
42639}, {"hash.js":273,"../elliptic":268}],273: [function (exports, require, module, global) {var hash = exports;
42640
42641hash.utils = require('./hash/utils');
42642hash.common = require('./hash/common');
42643hash.sha = require('./hash/sha');
42644hash.ripemd = require('./hash/ripemd');
42645hash.hmac = require('./hash/hmac');
42646
42647// Proxy hash functions to the main object
42648hash.sha1 = hash.sha.sha1;
42649hash.sha256 = hash.sha.sha256;
42650hash.sha224 = hash.sha.sha224;
42651hash.sha384 = hash.sha.sha384;
42652hash.sha512 = hash.sha.sha512;
42653hash.ripemd160 = hash.ripemd.ripemd160;
42654}, {"./hash/utils":274,"./hash/common":275,"./hash/sha":276,"./hash/ripemd":277,"./hash/hmac":278}],274: [function (exports, require, module, global) {var utils = exports;
42655var inherits = require('inherits');
42656
42657function toArray(msg, enc) {
42658 if (Array.isArray(msg))
42659 return msg.slice();
42660 if (!msg)
42661 return [];
42662 var res = [];
42663 if (typeof msg === 'string') {
42664 if (!enc) {
42665 for (var i = 0; i < msg.length; i++) {
42666 var c = msg.charCodeAt(i);
42667 var hi = c >> 8;
42668 var lo = c & 0xff;
42669 if (hi)
42670 res.push(hi, lo);
42671 else
42672 res.push(lo);
42673 }
42674 } else if (enc === 'hex') {
42675 msg = msg.replace(/[^a-z0-9]+/ig, '');
42676 if (msg.length % 2 !== 0)
42677 msg = '0' + msg;
42678 for (var i = 0; i < msg.length; i += 2)
42679 res.push(parseInt(msg[i] + msg[i + 1], 16));
42680 }
42681 } else {
42682 for (var i = 0; i < msg.length; i++)
42683 res[i] = msg[i] | 0;
42684 }
42685 return res;
42686}
42687utils.toArray = toArray;
42688
42689function toHex(msg) {
42690 var res = '';
42691 for (var i = 0; i < msg.length; i++)
42692 res += zero2(msg[i].toString(16));
42693 return res;
42694}
42695utils.toHex = toHex;
42696
42697function htonl(w) {
42698 var res = (w >>> 24) |
42699 ((w >>> 8) & 0xff00) |
42700 ((w << 8) & 0xff0000) |
42701 ((w & 0xff) << 24);
42702 return res >>> 0;
42703}
42704utils.htonl = htonl;
42705
42706function toHex32(msg, endian) {
42707 var res = '';
42708 for (var i = 0; i < msg.length; i++) {
42709 var w = msg[i];
42710 if (endian === 'little')
42711 w = htonl(w);
42712 res += zero8(w.toString(16));
42713 }
42714 return res;
42715}
42716utils.toHex32 = toHex32;
42717
42718function zero2(word) {
42719 if (word.length === 1)
42720 return '0' + word;
42721 else
42722 return word;
42723}
42724utils.zero2 = zero2;
42725
42726function zero8(word) {
42727 if (word.length === 7)
42728 return '0' + word;
42729 else if (word.length === 6)
42730 return '00' + word;
42731 else if (word.length === 5)
42732 return '000' + word;
42733 else if (word.length === 4)
42734 return '0000' + word;
42735 else if (word.length === 3)
42736 return '00000' + word;
42737 else if (word.length === 2)
42738 return '000000' + word;
42739 else if (word.length === 1)
42740 return '0000000' + word;
42741 else
42742 return word;
42743}
42744utils.zero8 = zero8;
42745
42746function join32(msg, start, end, endian) {
42747 var len = end - start;
42748 assert(len % 4 === 0);
42749 var res = new Array(len / 4);
42750 for (var i = 0, k = start; i < res.length; i++, k += 4) {
42751 var w;
42752 if (endian === 'big')
42753 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
42754 else
42755 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
42756 res[i] = w >>> 0;
42757 }
42758 return res;
42759}
42760utils.join32 = join32;
42761
42762function split32(msg, endian) {
42763 var res = new Array(msg.length * 4);
42764 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
42765 var m = msg[i];
42766 if (endian === 'big') {
42767 res[k] = m >>> 24;
42768 res[k + 1] = (m >>> 16) & 0xff;
42769 res[k + 2] = (m >>> 8) & 0xff;
42770 res[k + 3] = m & 0xff;
42771 } else {
42772 res[k + 3] = m >>> 24;
42773 res[k + 2] = (m >>> 16) & 0xff;
42774 res[k + 1] = (m >>> 8) & 0xff;
42775 res[k] = m & 0xff;
42776 }
42777 }
42778 return res;
42779}
42780utils.split32 = split32;
42781
42782function rotr32(w, b) {
42783 return (w >>> b) | (w << (32 - b));
42784}
42785utils.rotr32 = rotr32;
42786
42787function rotl32(w, b) {
42788 return (w << b) | (w >>> (32 - b));
42789}
42790utils.rotl32 = rotl32;
42791
42792function sum32(a, b) {
42793 return (a + b) >>> 0;
42794}
42795utils.sum32 = sum32;
42796
42797function sum32_3(a, b, c) {
42798 return (a + b + c) >>> 0;
42799}
42800utils.sum32_3 = sum32_3;
42801
42802function sum32_4(a, b, c, d) {
42803 return (a + b + c + d) >>> 0;
42804}
42805utils.sum32_4 = sum32_4;
42806
42807function sum32_5(a, b, c, d, e) {
42808 return (a + b + c + d + e) >>> 0;
42809}
42810utils.sum32_5 = sum32_5;
42811
42812function assert(cond, msg) {
42813 if (!cond)
42814 throw new Error(msg || 'Assertion failed');
42815}
42816utils.assert = assert;
42817
42818utils.inherits = inherits;
42819
42820function sum64(buf, pos, ah, al) {
42821 var bh = buf[pos];
42822 var bl = buf[pos + 1];
42823
42824 var lo = (al + bl) >>> 0;
42825 var hi = (lo < al ? 1 : 0) + ah + bh;
42826 buf[pos] = hi >>> 0;
42827 buf[pos + 1] = lo;
42828}
42829exports.sum64 = sum64;
42830
42831function sum64_hi(ah, al, bh, bl) {
42832 var lo = (al + bl) >>> 0;
42833 var hi = (lo < al ? 1 : 0) + ah + bh;
42834 return hi >>> 0;
42835};
42836exports.sum64_hi = sum64_hi;
42837
42838function sum64_lo(ah, al, bh, bl) {
42839 var lo = al + bl;
42840 return lo >>> 0;
42841};
42842exports.sum64_lo = sum64_lo;
42843
42844function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
42845 var carry = 0;
42846 var lo = al;
42847 lo = (lo + bl) >>> 0;
42848 carry += lo < al ? 1 : 0;
42849 lo = (lo + cl) >>> 0;
42850 carry += lo < cl ? 1 : 0;
42851 lo = (lo + dl) >>> 0;
42852 carry += lo < dl ? 1 : 0;
42853
42854 var hi = ah + bh + ch + dh + carry;
42855 return hi >>> 0;
42856};
42857exports.sum64_4_hi = sum64_4_hi;
42858
42859function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
42860 var lo = al + bl + cl + dl;
42861 return lo >>> 0;
42862};
42863exports.sum64_4_lo = sum64_4_lo;
42864
42865function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
42866 var carry = 0;
42867 var lo = al;
42868 lo = (lo + bl) >>> 0;
42869 carry += lo < al ? 1 : 0;
42870 lo = (lo + cl) >>> 0;
42871 carry += lo < cl ? 1 : 0;
42872 lo = (lo + dl) >>> 0;
42873 carry += lo < dl ? 1 : 0;
42874 lo = (lo + el) >>> 0;
42875 carry += lo < el ? 1 : 0;
42876
42877 var hi = ah + bh + ch + dh + eh + carry;
42878 return hi >>> 0;
42879};
42880exports.sum64_5_hi = sum64_5_hi;
42881
42882function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
42883 var lo = al + bl + cl + dl + el;
42884
42885 return lo >>> 0;
42886};
42887exports.sum64_5_lo = sum64_5_lo;
42888
42889function rotr64_hi(ah, al, num) {
42890 var r = (al << (32 - num)) | (ah >>> num);
42891 return r >>> 0;
42892};
42893exports.rotr64_hi = rotr64_hi;
42894
42895function rotr64_lo(ah, al, num) {
42896 var r = (ah << (32 - num)) | (al >>> num);
42897 return r >>> 0;
42898};
42899exports.rotr64_lo = rotr64_lo;
42900
42901function shr64_hi(ah, al, num) {
42902 return ah >>> num;
42903};
42904exports.shr64_hi = shr64_hi;
42905
42906function shr64_lo(ah, al, num) {
42907 var r = (ah << (32 - num)) | (al >>> num);
42908 return r >>> 0;
42909};
42910exports.shr64_lo = shr64_lo;
42911}, {"inherits":149}],275: [function (exports, require, module, global) {var hash = require('../hash');
42912var utils = hash.utils;
42913var assert = utils.assert;
42914
42915function BlockHash() {
42916 this.pending = null;
42917 this.pendingTotal = 0;
42918 this.blockSize = this.constructor.blockSize;
42919 this.outSize = this.constructor.outSize;
42920 this.hmacStrength = this.constructor.hmacStrength;
42921 this.padLength = this.constructor.padLength / 8;
42922 this.endian = 'big';
42923
42924 this._delta8 = this.blockSize / 8;
42925 this._delta32 = this.blockSize / 32;
42926}
42927exports.BlockHash = BlockHash;
42928
42929BlockHash.prototype.update = function update(msg, enc) {
42930 // Convert message to array, pad it, and join into 32bit blocks
42931 msg = utils.toArray(msg, enc);
42932 if (!this.pending)
42933 this.pending = msg;
42934 else
42935 this.pending = this.pending.concat(msg);
42936 this.pendingTotal += msg.length;
42937
42938 // Enough data, try updating
42939 if (this.pending.length >= this._delta8) {
42940 msg = this.pending;
42941
42942 // Process pending data in blocks
42943 var r = msg.length % this._delta8;
42944 this.pending = msg.slice(msg.length - r, msg.length);
42945 if (this.pending.length === 0)
42946 this.pending = null;
42947
42948 msg = utils.join32(msg, 0, msg.length - r, this.endian);
42949 for (var i = 0; i < msg.length; i += this._delta32)
42950 this._update(msg, i, i + this._delta32);
42951 }
42952
42953 return this;
42954};
42955
42956BlockHash.prototype.digest = function digest(enc) {
42957 this.update(this._pad());
42958 assert(this.pending === null);
42959
42960 return this._digest(enc);
42961};
42962
42963BlockHash.prototype._pad = function pad() {
42964 var len = this.pendingTotal;
42965 var bytes = this._delta8;
42966 var k = bytes - ((len + this.padLength) % bytes);
42967 var res = new Array(k + this.padLength);
42968 res[0] = 0x80;
42969 for (var i = 1; i < k; i++)
42970 res[i] = 0;
42971
42972 // Append length
42973 len <<= 3;
42974 if (this.endian === 'big') {
42975 for (var t = 8; t < this.padLength; t++)
42976 res[i++] = 0;
42977
42978 res[i++] = 0;
42979 res[i++] = 0;
42980 res[i++] = 0;
42981 res[i++] = 0;
42982 res[i++] = (len >>> 24) & 0xff;
42983 res[i++] = (len >>> 16) & 0xff;
42984 res[i++] = (len >>> 8) & 0xff;
42985 res[i++] = len & 0xff;
42986 } else {
42987 res[i++] = len & 0xff;
42988 res[i++] = (len >>> 8) & 0xff;
42989 res[i++] = (len >>> 16) & 0xff;
42990 res[i++] = (len >>> 24) & 0xff;
42991 res[i++] = 0;
42992 res[i++] = 0;
42993 res[i++] = 0;
42994 res[i++] = 0;
42995
42996 for (var t = 8; t < this.padLength; t++)
42997 res[i++] = 0;
42998 }
42999
43000 return res;
43001};
43002}, {"../hash":273}],276: [function (exports, require, module, global) {var hash = require('../hash');
43003var utils = hash.utils;
43004var assert = utils.assert;
43005
43006var rotr32 = utils.rotr32;
43007var rotl32 = utils.rotl32;
43008var sum32 = utils.sum32;
43009var sum32_4 = utils.sum32_4;
43010var sum32_5 = utils.sum32_5;
43011var rotr64_hi = utils.rotr64_hi;
43012var rotr64_lo = utils.rotr64_lo;
43013var shr64_hi = utils.shr64_hi;
43014var shr64_lo = utils.shr64_lo;
43015var sum64 = utils.sum64;
43016var sum64_hi = utils.sum64_hi;
43017var sum64_lo = utils.sum64_lo;
43018var sum64_4_hi = utils.sum64_4_hi;
43019var sum64_4_lo = utils.sum64_4_lo;
43020var sum64_5_hi = utils.sum64_5_hi;
43021var sum64_5_lo = utils.sum64_5_lo;
43022var BlockHash = hash.common.BlockHash;
43023
43024var sha256_K = [
43025 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
43026 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
43027 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
43028 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
43029 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
43030 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
43031 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
43032 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
43033 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
43034 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
43035 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
43036 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
43037 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
43038 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
43039 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
43040 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
43041];
43042
43043var sha512_K = [
43044 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
43045 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
43046 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
43047 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
43048 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
43049 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
43050 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
43051 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
43052 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
43053 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
43054 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
43055 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
43056 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
43057 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
43058 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
43059 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
43060 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
43061 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
43062 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
43063 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
43064 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
43065 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
43066 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
43067 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
43068 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
43069 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
43070 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
43071 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
43072 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
43073 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
43074 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
43075 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
43076 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
43077 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
43078 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
43079 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
43080 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
43081 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
43082 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
43083 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
43084];
43085
43086var sha1_K = [
43087 0x5A827999, 0x6ED9EBA1,
43088 0x8F1BBCDC, 0xCA62C1D6
43089];
43090
43091function SHA256() {
43092 if (!(this instanceof SHA256))
43093 return new SHA256();
43094
43095 BlockHash.call(this);
43096 this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
43097 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ];
43098 this.k = sha256_K;
43099 this.W = new Array(64);
43100}
43101utils.inherits(SHA256, BlockHash);
43102exports.sha256 = SHA256;
43103
43104SHA256.blockSize = 512;
43105SHA256.outSize = 256;
43106SHA256.hmacStrength = 192;
43107SHA256.padLength = 64;
43108
43109SHA256.prototype._update = function _update(msg, start) {
43110 var W = this.W;
43111
43112 for (var i = 0; i < 16; i++)
43113 W[i] = msg[start + i];
43114 for (; i < W.length; i++)
43115 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
43116
43117 var a = this.h[0];
43118 var b = this.h[1];
43119 var c = this.h[2];
43120 var d = this.h[3];
43121 var e = this.h[4];
43122 var f = this.h[5];
43123 var g = this.h[6];
43124 var h = this.h[7];
43125
43126 assert(this.k.length === W.length);
43127 for (var i = 0; i < W.length; i++) {
43128 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
43129 var T2 = sum32(s0_256(a), maj32(a, b, c));
43130 h = g;
43131 g = f;
43132 f = e;
43133 e = sum32(d, T1);
43134 d = c;
43135 c = b;
43136 b = a;
43137 a = sum32(T1, T2);
43138 }
43139
43140 this.h[0] = sum32(this.h[0], a);
43141 this.h[1] = sum32(this.h[1], b);
43142 this.h[2] = sum32(this.h[2], c);
43143 this.h[3] = sum32(this.h[3], d);
43144 this.h[4] = sum32(this.h[4], e);
43145 this.h[5] = sum32(this.h[5], f);
43146 this.h[6] = sum32(this.h[6], g);
43147 this.h[7] = sum32(this.h[7], h);
43148};
43149
43150SHA256.prototype._digest = function digest(enc) {
43151 if (enc === 'hex')
43152 return utils.toHex32(this.h, 'big');
43153 else
43154 return utils.split32(this.h, 'big');
43155};
43156
43157function SHA224() {
43158 if (!(this instanceof SHA224))
43159 return new SHA224();
43160
43161 SHA256.call(this);
43162 this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
43163 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
43164}
43165utils.inherits(SHA224, SHA256);
43166exports.sha224 = SHA224;
43167
43168SHA224.blockSize = 512;
43169SHA224.outSize = 224;
43170SHA224.hmacStrength = 192;
43171SHA224.padLength = 64;
43172
43173SHA224.prototype._digest = function digest(enc) {
43174 // Just truncate output
43175 if (enc === 'hex')
43176 return utils.toHex32(this.h.slice(0, 7), 'big');
43177 else
43178 return utils.split32(this.h.slice(0, 7), 'big');
43179};
43180
43181function SHA512() {
43182 if (!(this instanceof SHA512))
43183 return new SHA512();
43184
43185 BlockHash.call(this);
43186 this.h = [ 0x6a09e667, 0xf3bcc908,
43187 0xbb67ae85, 0x84caa73b,
43188 0x3c6ef372, 0xfe94f82b,
43189 0xa54ff53a, 0x5f1d36f1,
43190 0x510e527f, 0xade682d1,
43191 0x9b05688c, 0x2b3e6c1f,
43192 0x1f83d9ab, 0xfb41bd6b,
43193 0x5be0cd19, 0x137e2179 ];
43194 this.k = sha512_K;
43195 this.W = new Array(160);
43196}
43197utils.inherits(SHA512, BlockHash);
43198exports.sha512 = SHA512;
43199
43200SHA512.blockSize = 1024;
43201SHA512.outSize = 512;
43202SHA512.hmacStrength = 192;
43203SHA512.padLength = 128;
43204
43205SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
43206 var W = this.W;
43207
43208 // 32 x 32bit words
43209 for (var i = 0; i < 32; i++)
43210 W[i] = msg[start + i];
43211 for (; i < W.length; i += 2) {
43212 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
43213 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
43214 var c1_hi = W[i - 14]; // i - 7
43215 var c1_lo = W[i - 13];
43216 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
43217 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
43218 var c3_hi = W[i - 32]; // i - 16
43219 var c3_lo = W[i - 31];
43220
43221 W[i] = sum64_4_hi(c0_hi, c0_lo,
43222 c1_hi, c1_lo,
43223 c2_hi, c2_lo,
43224 c3_hi, c3_lo);
43225 W[i + 1] = sum64_4_lo(c0_hi, c0_lo,
43226 c1_hi, c1_lo,
43227 c2_hi, c2_lo,
43228 c3_hi, c3_lo);
43229 }
43230};
43231
43232SHA512.prototype._update = function _update(msg, start) {
43233 this._prepareBlock(msg, start);
43234
43235 var W = this.W;
43236
43237 var ah = this.h[0];
43238 var al = this.h[1];
43239 var bh = this.h[2];
43240 var bl = this.h[3];
43241 var ch = this.h[4];
43242 var cl = this.h[5];
43243 var dh = this.h[6];
43244 var dl = this.h[7];
43245 var eh = this.h[8];
43246 var el = this.h[9];
43247 var fh = this.h[10];
43248 var fl = this.h[11];
43249 var gh = this.h[12];
43250 var gl = this.h[13];
43251 var hh = this.h[14];
43252 var hl = this.h[15];
43253
43254 assert(this.k.length === W.length);
43255 for (var i = 0; i < W.length; i += 2) {
43256 var c0_hi = hh;
43257 var c0_lo = hl;
43258 var c1_hi = s1_512_hi(eh, el);
43259 var c1_lo = s1_512_lo(eh, el);
43260 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
43261 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
43262 var c3_hi = this.k[i];
43263 var c3_lo = this.k[i + 1];
43264 var c4_hi = W[i];
43265 var c4_lo = W[i + 1];
43266
43267 var T1_hi = sum64_5_hi(c0_hi, c0_lo,
43268 c1_hi, c1_lo,
43269 c2_hi, c2_lo,
43270 c3_hi, c3_lo,
43271 c4_hi, c4_lo);
43272 var T1_lo = sum64_5_lo(c0_hi, c0_lo,
43273 c1_hi, c1_lo,
43274 c2_hi, c2_lo,
43275 c3_hi, c3_lo,
43276 c4_hi, c4_lo);
43277
43278 var c0_hi = s0_512_hi(ah, al);
43279 var c0_lo = s0_512_lo(ah, al);
43280 var c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
43281 var c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
43282
43283 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
43284 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
43285
43286 hh = gh;
43287 hl = gl;
43288
43289 gh = fh;
43290 gl = fl;
43291
43292 fh = eh;
43293 fl = el;
43294
43295 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
43296 el = sum64_lo(dl, dl, T1_hi, T1_lo);
43297
43298 dh = ch;
43299 dl = cl;
43300
43301 ch = bh;
43302 cl = bl;
43303
43304 bh = ah;
43305 bl = al;
43306
43307 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
43308 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
43309 }
43310
43311 sum64(this.h, 0, ah, al);
43312 sum64(this.h, 2, bh, bl);
43313 sum64(this.h, 4, ch, cl);
43314 sum64(this.h, 6, dh, dl);
43315 sum64(this.h, 8, eh, el);
43316 sum64(this.h, 10, fh, fl);
43317 sum64(this.h, 12, gh, gl);
43318 sum64(this.h, 14, hh, hl);
43319};
43320
43321SHA512.prototype._digest = function digest(enc) {
43322 if (enc === 'hex')
43323 return utils.toHex32(this.h, 'big');
43324 else
43325 return utils.split32(this.h, 'big');
43326};
43327
43328function SHA384() {
43329 if (!(this instanceof SHA384))
43330 return new SHA384();
43331
43332 SHA512.call(this);
43333 this.h = [ 0xcbbb9d5d, 0xc1059ed8,
43334 0x629a292a, 0x367cd507,
43335 0x9159015a, 0x3070dd17,
43336 0x152fecd8, 0xf70e5939,
43337 0x67332667, 0xffc00b31,
43338 0x8eb44a87, 0x68581511,
43339 0xdb0c2e0d, 0x64f98fa7,
43340 0x47b5481d, 0xbefa4fa4 ];
43341}
43342utils.inherits(SHA384, SHA512);
43343exports.sha384 = SHA384;
43344
43345SHA384.blockSize = 1024;
43346SHA384.outSize = 384;
43347SHA384.hmacStrength = 192;
43348SHA384.padLength = 128;
43349
43350SHA384.prototype._digest = function digest(enc) {
43351 if (enc === 'hex')
43352 return utils.toHex32(this.h.slice(0, 12), 'big');
43353 else
43354 return utils.split32(this.h.slice(0, 12), 'big');
43355};
43356
43357function SHA1() {
43358 if (!(this instanceof SHA1))
43359 return new SHA1();
43360
43361 BlockHash.call(this);
43362 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe,
43363 0x10325476, 0xc3d2e1f0 ];
43364 this.W = new Array(80);
43365}
43366
43367utils.inherits(SHA1, BlockHash);
43368exports.sha1 = SHA1;
43369
43370SHA1.blockSize = 512;
43371SHA1.outSize = 160;
43372SHA1.hmacStrength = 80;
43373SHA1.padLength = 64;
43374
43375SHA1.prototype._update = function _update(msg, start) {
43376 var W = this.W;
43377
43378 for (var i = 0; i < 16; i++)
43379 W[i] = msg[start + i];
43380
43381 for(; i < W.length; i++)
43382 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
43383
43384 var a = this.h[0];
43385 var b = this.h[1];
43386 var c = this.h[2];
43387 var d = this.h[3];
43388 var e = this.h[4];
43389
43390 for (var i = 0; i < W.length; i++) {
43391 var s = ~~(i / 20);
43392 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
43393 e = d;
43394 d = c;
43395 c = rotl32(b, 30);
43396 b = a;
43397 a = t;
43398 }
43399
43400 this.h[0] = sum32(this.h[0], a);
43401 this.h[1] = sum32(this.h[1], b);
43402 this.h[2] = sum32(this.h[2], c);
43403 this.h[3] = sum32(this.h[3], d);
43404 this.h[4] = sum32(this.h[4], e);
43405};
43406
43407SHA1.prototype._digest = function digest(enc) {
43408 if (enc === 'hex')
43409 return utils.toHex32(this.h, 'big');
43410 else
43411 return utils.split32(this.h, 'big');
43412};
43413
43414function ch32(x, y, z) {
43415 return (x & y) ^ ((~x) & z);
43416}
43417
43418function maj32(x, y, z) {
43419 return (x & y) ^ (x & z) ^ (y & z);
43420}
43421
43422function p32(x, y, z) {
43423 return x ^ y ^ z;
43424}
43425
43426function s0_256(x) {
43427 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
43428}
43429
43430function s1_256(x) {
43431 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
43432}
43433
43434function g0_256(x) {
43435 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
43436}
43437
43438function g1_256(x) {
43439 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
43440}
43441
43442function ft_1(s, x, y, z) {
43443 if (s === 0)
43444 return ch32(x, y, z);
43445 if (s === 1 || s === 3)
43446 return p32(x, y, z);
43447 if (s === 2)
43448 return maj32(x, y, z);
43449}
43450
43451function ch64_hi(xh, xl, yh, yl, zh, zl) {
43452 var r = (xh & yh) ^ ((~xh) & zh);
43453 if (r < 0)
43454 r += 0x100000000;
43455 return r;
43456}
43457
43458function ch64_lo(xh, xl, yh, yl, zh, zl) {
43459 var r = (xl & yl) ^ ((~xl) & zl);
43460 if (r < 0)
43461 r += 0x100000000;
43462 return r;
43463}
43464
43465function maj64_hi(xh, xl, yh, yl, zh, zl) {
43466 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
43467 if (r < 0)
43468 r += 0x100000000;
43469 return r;
43470}
43471
43472function maj64_lo(xh, xl, yh, yl, zh, zl) {
43473 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
43474 if (r < 0)
43475 r += 0x100000000;
43476 return r;
43477}
43478
43479function s0_512_hi(xh, xl) {
43480 var c0_hi = rotr64_hi(xh, xl, 28);
43481 var c1_hi = rotr64_hi(xl, xh, 2); // 34
43482 var c2_hi = rotr64_hi(xl, xh, 7); // 39
43483
43484 var r = c0_hi ^ c1_hi ^ c2_hi;
43485 if (r < 0)
43486 r += 0x100000000;
43487 return r;
43488}
43489
43490function s0_512_lo(xh, xl) {
43491 var c0_lo = rotr64_lo(xh, xl, 28);
43492 var c1_lo = rotr64_lo(xl, xh, 2); // 34
43493 var c2_lo = rotr64_lo(xl, xh, 7); // 39
43494
43495 var r = c0_lo ^ c1_lo ^ c2_lo;
43496 if (r < 0)
43497 r += 0x100000000;
43498 return r;
43499}
43500
43501function s1_512_hi(xh, xl) {
43502 var c0_hi = rotr64_hi(xh, xl, 14);
43503 var c1_hi = rotr64_hi(xh, xl, 18);
43504 var c2_hi = rotr64_hi(xl, xh, 9); // 41
43505
43506 var r = c0_hi ^ c1_hi ^ c2_hi;
43507 if (r < 0)
43508 r += 0x100000000;
43509 return r;
43510}
43511
43512function s1_512_lo(xh, xl) {
43513 var c0_lo = rotr64_lo(xh, xl, 14);
43514 var c1_lo = rotr64_lo(xh, xl, 18);
43515 var c2_lo = rotr64_lo(xl, xh, 9); // 41
43516
43517 var r = c0_lo ^ c1_lo ^ c2_lo;
43518 if (r < 0)
43519 r += 0x100000000;
43520 return r;
43521}
43522
43523function g0_512_hi(xh, xl) {
43524 var c0_hi = rotr64_hi(xh, xl, 1);
43525 var c1_hi = rotr64_hi(xh, xl, 8);
43526 var c2_hi = shr64_hi(xh, xl, 7);
43527
43528 var r = c0_hi ^ c1_hi ^ c2_hi;
43529 if (r < 0)
43530 r += 0x100000000;
43531 return r;
43532}
43533
43534function g0_512_lo(xh, xl) {
43535 var c0_lo = rotr64_lo(xh, xl, 1);
43536 var c1_lo = rotr64_lo(xh, xl, 8);
43537 var c2_lo = shr64_lo(xh, xl, 7);
43538
43539 var r = c0_lo ^ c1_lo ^ c2_lo;
43540 if (r < 0)
43541 r += 0x100000000;
43542 return r;
43543}
43544
43545function g1_512_hi(xh, xl) {
43546 var c0_hi = rotr64_hi(xh, xl, 19);
43547 var c1_hi = rotr64_hi(xl, xh, 29); // 61
43548 var c2_hi = shr64_hi(xh, xl, 6);
43549
43550 var r = c0_hi ^ c1_hi ^ c2_hi;
43551 if (r < 0)
43552 r += 0x100000000;
43553 return r;
43554}
43555
43556function g1_512_lo(xh, xl) {
43557 var c0_lo = rotr64_lo(xh, xl, 19);
43558 var c1_lo = rotr64_lo(xl, xh, 29); // 61
43559 var c2_lo = shr64_lo(xh, xl, 6);
43560
43561 var r = c0_lo ^ c1_lo ^ c2_lo;
43562 if (r < 0)
43563 r += 0x100000000;
43564 return r;
43565}
43566}, {"../hash":273}],277: [function (exports, require, module, global) {var hash = require('../hash');
43567var utils = hash.utils;
43568
43569var rotl32 = utils.rotl32;
43570var sum32 = utils.sum32;
43571var sum32_3 = utils.sum32_3;
43572var sum32_4 = utils.sum32_4;
43573var BlockHash = hash.common.BlockHash;
43574
43575function RIPEMD160() {
43576 if (!(this instanceof RIPEMD160))
43577 return new RIPEMD160();
43578
43579 BlockHash.call(this);
43580
43581 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
43582 this.endian = 'little';
43583}
43584utils.inherits(RIPEMD160, BlockHash);
43585exports.ripemd160 = RIPEMD160;
43586
43587RIPEMD160.blockSize = 512;
43588RIPEMD160.outSize = 160;
43589RIPEMD160.hmacStrength = 192;
43590RIPEMD160.padLength = 64;
43591
43592RIPEMD160.prototype._update = function update(msg, start) {
43593 var A = this.h[0];
43594 var B = this.h[1];
43595 var C = this.h[2];
43596 var D = this.h[3];
43597 var E = this.h[4];
43598 var Ah = A;
43599 var Bh = B;
43600 var Ch = C;
43601 var Dh = D;
43602 var Eh = E;
43603 for (var j = 0; j < 80; j++) {
43604 var T = sum32(
43605 rotl32(
43606 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
43607 s[j]),
43608 E);
43609 A = E;
43610 E = D;
43611 D = rotl32(C, 10);
43612 C = B;
43613 B = T;
43614 T = sum32(
43615 rotl32(
43616 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
43617 sh[j]),
43618 Eh);
43619 Ah = Eh;
43620 Eh = Dh;
43621 Dh = rotl32(Ch, 10);
43622 Ch = Bh;
43623 Bh = T;
43624 }
43625 T = sum32_3(this.h[1], C, Dh);
43626 this.h[1] = sum32_3(this.h[2], D, Eh);
43627 this.h[2] = sum32_3(this.h[3], E, Ah);
43628 this.h[3] = sum32_3(this.h[4], A, Bh);
43629 this.h[4] = sum32_3(this.h[0], B, Ch);
43630 this.h[0] = T;
43631};
43632
43633RIPEMD160.prototype._digest = function digest(enc) {
43634 if (enc === 'hex')
43635 return utils.toHex32(this.h, 'little');
43636 else
43637 return utils.split32(this.h, 'little');
43638};
43639
43640function f(j, x, y, z) {
43641 if (j <= 15)
43642 return x ^ y ^ z;
43643 else if (j <= 31)
43644 return (x & y) | ((~x) & z);
43645 else if (j <= 47)
43646 return (x | (~y)) ^ z;
43647 else if (j <= 63)
43648 return (x & z) | (y & (~z));
43649 else
43650 return x ^ (y | (~z));
43651}
43652
43653function K(j) {
43654 if (j <= 15)
43655 return 0x00000000;
43656 else if (j <= 31)
43657 return 0x5a827999;
43658 else if (j <= 47)
43659 return 0x6ed9eba1;
43660 else if (j <= 63)
43661 return 0x8f1bbcdc;
43662 else
43663 return 0xa953fd4e;
43664}
43665
43666function Kh(j) {
43667 if (j <= 15)
43668 return 0x50a28be6;
43669 else if (j <= 31)
43670 return 0x5c4dd124;
43671 else if (j <= 47)
43672 return 0x6d703ef3;
43673 else if (j <= 63)
43674 return 0x7a6d76e9;
43675 else
43676 return 0x00000000;
43677}
43678
43679var r = [
43680 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
43681 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
43682 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
43683 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
43684 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
43685];
43686
43687var rh = [
43688 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
43689 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
43690 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
43691 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
43692 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
43693];
43694
43695var s = [
43696 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
43697 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
43698 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
43699 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
43700 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
43701];
43702
43703var sh = [
43704 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
43705 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
43706 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
43707 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
43708 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
43709];
43710}, {"../hash":273}],278: [function (exports, require, module, global) {var hmac = exports;
43711
43712var hash = require('../hash');
43713var utils = hash.utils;
43714var assert = utils.assert;
43715
43716function Hmac(hash, key, enc) {
43717 if (!(this instanceof Hmac))
43718 return new Hmac(hash, key, enc);
43719 this.Hash = hash;
43720 this.blockSize = hash.blockSize / 8;
43721 this.outSize = hash.outSize / 8;
43722 this.inner = null;
43723 this.outer = null;
43724
43725 this._init(utils.toArray(key, enc));
43726}
43727module.exports = Hmac;
43728
43729Hmac.prototype._init = function init(key) {
43730 // Shorten key, if needed
43731 if (key.length > this.blockSize)
43732 key = new this.Hash().update(key).digest();
43733 assert(key.length <= this.blockSize);
43734
43735 // Add padding to key
43736 for (var i = key.length; i < this.blockSize; i++)
43737 key.push(0);
43738
43739 for (var i = 0; i < key.length; i++)
43740 key[i] ^= 0x36;
43741 this.inner = new this.Hash().update(key);
43742
43743 // 0x36 ^ 0x5c = 0x6a
43744 for (var i = 0; i < key.length; i++)
43745 key[i] ^= 0x6a;
43746 this.outer = new this.Hash().update(key);
43747};
43748
43749Hmac.prototype.update = function update(msg, enc) {
43750 this.inner.update(msg, enc);
43751 return this;
43752};
43753
43754Hmac.prototype.digest = function digest(enc) {
43755 this.outer.update(this.inner.digest());
43756 return this.outer.digest(enc);
43757};
43758}, {"../hash":273}],279: [function (exports, require, module, global) {'use strict';
43759
43760var curve = exports;
43761
43762curve.base = require('./base');
43763curve.short = require('./short');
43764curve.mont = require('./mont');
43765curve.edwards = require('./edwards');
43766}, {"./base":280,"./short":282,"./mont":283,"./edwards":284}],280: [function (exports, require, module, global) {'use strict';
43767
43768var bn = require('bn.js');
43769var elliptic = require('../../elliptic');
43770
43771var getNAF = elliptic.utils.getNAF;
43772var getJSF = elliptic.utils.getJSF;
43773var assert = elliptic.utils.assert;
43774
43775function BaseCurve(type, conf) {
43776 this.type = type;
43777 this.p = new bn(conf.p, 16);
43778
43779 // Use Montgomery, when there is no fast reduction for the prime
43780 this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
43781
43782 // Useful for many curves
43783 this.zero = new bn(0).toRed(this.red);
43784 this.one = new bn(1).toRed(this.red);
43785 this.two = new bn(2).toRed(this.red);
43786
43787 // Curve configuration, optional
43788 this.n = conf.n && new bn(conf.n, 16);
43789 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
43790
43791 // Temporary arrays
43792 this._wnafT1 = new Array(4);
43793 this._wnafT2 = new Array(4);
43794 this._wnafT3 = new Array(4);
43795 this._wnafT4 = new Array(4);
43796}
43797module.exports = BaseCurve;
43798
43799BaseCurve.prototype.point = function point() {
43800 throw new Error('Not implemented');
43801};
43802
43803BaseCurve.prototype.validate = function validate() {
43804 throw new Error('Not implemented');
43805};
43806
43807BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
43808 assert(p.precomputed);
43809 var doubles = p._getDoubles();
43810
43811 var naf = getNAF(k, 1);
43812 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
43813 I /= 3;
43814
43815 // Translate into more windowed form
43816 var repr = [];
43817 for (var j = 0; j < naf.length; j += doubles.step) {
43818 var nafW = 0;
43819 for (var k = j + doubles.step - 1; k >= j; k--)
43820 nafW = (nafW << 1) + naf[k];
43821 repr.push(nafW);
43822 }
43823
43824 var a = this.jpoint(null, null, null);
43825 var b = this.jpoint(null, null, null);
43826 for (var i = I; i > 0; i--) {
43827 for (var j = 0; j < repr.length; j++) {
43828 var nafW = repr[j];
43829 if (nafW === i)
43830 b = b.mixedAdd(doubles.points[j]);
43831 else if (nafW === -i)
43832 b = b.mixedAdd(doubles.points[j].neg());
43833 }
43834 a = a.add(b);
43835 }
43836 return a.toP();
43837};
43838
43839BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
43840 var w = 4;
43841
43842 // Precompute window
43843 var nafPoints = p._getNAFPoints(w);
43844 w = nafPoints.wnd;
43845 var wnd = nafPoints.points;
43846
43847 // Get NAF form
43848 var naf = getNAF(k, w);
43849
43850 // Add `this`*(N+1) for every w-NAF index
43851 var acc = this.jpoint(null, null, null);
43852 for (var i = naf.length - 1; i >= 0; i--) {
43853 // Count zeroes
43854 for (var k = 0; i >= 0 && naf[i] === 0; i--)
43855 k++;
43856 if (i >= 0)
43857 k++;
43858 acc = acc.dblp(k);
43859
43860 if (i < 0)
43861 break;
43862 var z = naf[i];
43863 assert(z !== 0);
43864 if (p.type === 'affine') {
43865 // J +- P
43866 if (z > 0)
43867 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
43868 else
43869 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
43870 } else {
43871 // J +- J
43872 if (z > 0)
43873 acc = acc.add(wnd[(z - 1) >> 1]);
43874 else
43875 acc = acc.add(wnd[(-z - 1) >> 1].neg());
43876 }
43877 }
43878 return p.type === 'affine' ? acc.toP() : acc;
43879};
43880
43881BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
43882 points,
43883 coeffs,
43884 len) {
43885 var wndWidth = this._wnafT1;
43886 var wnd = this._wnafT2;
43887 var naf = this._wnafT3;
43888
43889 // Fill all arrays
43890 var max = 0;
43891 for (var i = 0; i < len; i++) {
43892 var p = points[i];
43893 var nafPoints = p._getNAFPoints(defW);
43894 wndWidth[i] = nafPoints.wnd;
43895 wnd[i] = nafPoints.points;
43896 }
43897
43898 // Comb small window NAFs
43899 for (var i = len - 1; i >= 1; i -= 2) {
43900 var a = i - 1;
43901 var b = i;
43902 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
43903 naf[a] = getNAF(coeffs[a], wndWidth[a]);
43904 naf[b] = getNAF(coeffs[b], wndWidth[b]);
43905 max = Math.max(naf[a].length, max);
43906 max = Math.max(naf[b].length, max);
43907 continue;
43908 }
43909
43910 var comb = [
43911 points[a], /* 1 */
43912 null, /* 3 */
43913 null, /* 5 */
43914 points[b] /* 7 */
43915 ];
43916
43917 // Try to avoid Projective points, if possible
43918 if (points[a].y.cmp(points[b].y) === 0) {
43919 comb[1] = points[a].add(points[b]);
43920 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
43921 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
43922 comb[1] = points[a].toJ().mixedAdd(points[b]);
43923 comb[2] = points[a].add(points[b].neg());
43924 } else {
43925 comb[1] = points[a].toJ().mixedAdd(points[b]);
43926 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
43927 }
43928
43929 var index = [
43930 -3, /* -1 -1 */
43931 -1, /* -1 0 */
43932 -5, /* -1 1 */
43933 -7, /* 0 -1 */
43934 0, /* 0 0 */
43935 7, /* 0 1 */
43936 5, /* 1 -1 */
43937 1, /* 1 0 */
43938 3 /* 1 1 */
43939 ];
43940
43941 var jsf = getJSF(coeffs[a], coeffs[b]);
43942 max = Math.max(jsf[0].length, max);
43943 naf[a] = new Array(max);
43944 naf[b] = new Array(max);
43945 for (var j = 0; j < max; j++) {
43946 var ja = jsf[0][j] | 0;
43947 var jb = jsf[1][j] | 0;
43948
43949 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
43950 naf[b][j] = 0;
43951 wnd[a] = comb;
43952 }
43953 }
43954
43955 var acc = this.jpoint(null, null, null);
43956 var tmp = this._wnafT4;
43957 for (var i = max; i >= 0; i--) {
43958 var k = 0;
43959
43960 while (i >= 0) {
43961 var zero = true;
43962 for (var j = 0; j < len; j++) {
43963 tmp[j] = naf[j][i] | 0;
43964 if (tmp[j] !== 0)
43965 zero = false;
43966 }
43967 if (!zero)
43968 break;
43969 k++;
43970 i--;
43971 }
43972 if (i >= 0)
43973 k++;
43974 acc = acc.dblp(k);
43975 if (i < 0)
43976 break;
43977
43978 for (var j = 0; j < len; j++) {
43979 var z = tmp[j];
43980 var p;
43981 if (z === 0)
43982 continue;
43983 else if (z > 0)
43984 p = wnd[j][(z - 1) >> 1];
43985 else if (z < 0)
43986 p = wnd[j][(-z - 1) >> 1].neg();
43987
43988 if (p.type === 'affine')
43989 acc = acc.mixedAdd(p);
43990 else
43991 acc = acc.add(p);
43992 }
43993 }
43994 // Zeroify references
43995 for (var i = 0; i < len; i++)
43996 wnd[i] = null;
43997 return acc.toP();
43998};
43999
44000function BasePoint(curve, type) {
44001 this.curve = curve;
44002 this.type = type;
44003 this.precomputed = null;
44004}
44005BaseCurve.BasePoint = BasePoint;
44006
44007BasePoint.prototype.validate = function validate() {
44008 return this.curve.validate(this);
44009};
44010
44011BasePoint.prototype.precompute = function precompute(power) {
44012 if (this.precomputed)
44013 return this;
44014
44015 var precomputed = {
44016 doubles: null,
44017 naf: null,
44018 beta: null
44019 };
44020 precomputed.naf = this._getNAFPoints(8);
44021 precomputed.doubles = this._getDoubles(4, power);
44022 precomputed.beta = this._getBeta();
44023 this.precomputed = precomputed;
44024
44025 return this;
44026};
44027
44028BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
44029 if (!this.precomputed)
44030 return false;
44031
44032 var doubles = this.precomputed.doubles;
44033 if (!doubles)
44034 return false;
44035
44036 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
44037};
44038
44039BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
44040 if (this.precomputed && this.precomputed.doubles)
44041 return this.precomputed.doubles;
44042
44043 var doubles = [ this ];
44044 var acc = this;
44045 for (var i = 0; i < power; i += step) {
44046 for (var j = 0; j < step; j++)
44047 acc = acc.dbl();
44048 doubles.push(acc);
44049 }
44050 return {
44051 step: step,
44052 points: doubles
44053 };
44054};
44055
44056BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
44057 if (this.precomputed && this.precomputed.naf)
44058 return this.precomputed.naf;
44059
44060 var res = [ this ];
44061 var max = (1 << wnd) - 1;
44062 var dbl = max === 1 ? null : this.dbl();
44063 for (var i = 1; i < max; i++)
44064 res[i] = res[i - 1].add(dbl);
44065 return {
44066 wnd: wnd,
44067 points: res
44068 };
44069};
44070
44071BasePoint.prototype._getBeta = function _getBeta() {
44072 return null;
44073};
44074
44075BasePoint.prototype.dblp = function dblp(k) {
44076 var r = this;
44077 for (var i = 0; i < k; i++)
44078 r = r.dbl();
44079 return r;
44080};
44081}, {"bn.js":281,"../../elliptic":268}],281: [function (exports, require, module, global) {(function (module, exports) {
44082
44083'use strict';
44084
44085// Utils
44086
44087function assert(val, msg) {
44088 if (!val)
44089 throw new Error(msg || 'Assertion failed');
44090}
44091
44092// Could use `inherits` module, but don't want to move from single file
44093// architecture yet.
44094function inherits(ctor, superCtor) {
44095 ctor.super_ = superCtor;
44096 var TempCtor = function () {};
44097 TempCtor.prototype = superCtor.prototype;
44098 ctor.prototype = new TempCtor();
44099 ctor.prototype.constructor = ctor;
44100}
44101
44102// BN
44103
44104function BN(number, base, endian) {
44105 // May be `new BN(bn)` ?
44106 if (number !== null &&
44107 typeof number === 'object' &&
44108 Array.isArray(number.words)) {
44109 return number;
44110 }
44111
44112 this.sign = false;
44113 this.words = null;
44114 this.length = 0;
44115
44116 // Reduction context
44117 this.red = null;
44118
44119 if (base === 'le' || base === 'be') {
44120 endian = base;
44121 base = 10;
44122 }
44123
44124 if (number !== null)
44125 this._init(number || 0, base || 10, endian || 'be');
44126}
44127if (typeof module === 'object')
44128 module.exports = BN;
44129else
44130 exports.BN = BN;
44131
44132BN.BN = BN;
44133BN.wordSize = 26;
44134
44135BN.prototype._init = function init(number, base, endian) {
44136 if (typeof number === 'number') {
44137 return this._initNumber(number, base, endian);
44138 } else if (typeof number === 'object') {
44139 return this._initArray(number, base, endian);
44140 }
44141 if (base === 'hex')
44142 base = 16;
44143 assert(base === (base | 0) && base >= 2 && base <= 36);
44144
44145 number = number.toString().replace(/\s+/g, '');
44146 var start = 0;
44147 if (number[0] === '-')
44148 start++;
44149
44150 if (base === 16)
44151 this._parseHex(number, start);
44152 else
44153 this._parseBase(number, base, start);
44154
44155 if (number[0] === '-')
44156 this.sign = true;
44157
44158 this.strip();
44159
44160 if (endian !== 'le')
44161 return;
44162
44163 this._initArray(this.toArray(), base, endian);
44164};
44165
44166BN.prototype._initNumber = function _initNumber(number, base, endian) {
44167 if (number < 0) {
44168 this.sign = true;
44169 number = -number;
44170 }
44171 if (number < 0x4000000) {
44172 this.words = [ number & 0x3ffffff ];
44173 this.length = 1;
44174 } else if (number < 0x10000000000000) {
44175 this.words = [
44176 number & 0x3ffffff,
44177 (number / 0x4000000) & 0x3ffffff
44178 ];
44179 this.length = 2;
44180 } else {
44181 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
44182 this.words = [
44183 number & 0x3ffffff,
44184 (number / 0x4000000) & 0x3ffffff,
44185 1
44186 ];
44187 this.length = 3;
44188 }
44189
44190 if (endian !== 'le')
44191 return;
44192
44193 // Reverse the bytes
44194 this._initArray(this.toArray(), base, endian);
44195};
44196
44197BN.prototype._initArray = function _initArray(number, base, endian) {
44198 // Perhaps a Uint8Array
44199 assert(typeof number.length === 'number');
44200 if (number.length <= 0) {
44201 this.words = [ 0 ];
44202 this.length = 1;
44203 return this;
44204 }
44205
44206 this.length = Math.ceil(number.length / 3);
44207 this.words = new Array(this.length);
44208 for (var i = 0; i < this.length; i++)
44209 this.words[i] = 0;
44210
44211 var off = 0;
44212 if (endian === 'be') {
44213 for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
44214 var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
44215 this.words[j] |= (w << off) & 0x3ffffff;
44216 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
44217 off += 24;
44218 if (off >= 26) {
44219 off -= 26;
44220 j++;
44221 }
44222 }
44223 } else if (endian === 'le') {
44224 for (var i = 0, j = 0; i < number.length; i += 3) {
44225 var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
44226 this.words[j] |= (w << off) & 0x3ffffff;
44227 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
44228 off += 24;
44229 if (off >= 26) {
44230 off -= 26;
44231 j++;
44232 }
44233 }
44234 }
44235 return this.strip();
44236};
44237
44238function parseHex(str, start, end) {
44239 var r = 0;
44240 var len = Math.min(str.length, end);
44241 for (var i = start; i < len; i++) {
44242 var c = str.charCodeAt(i) - 48;
44243
44244 r <<= 4;
44245
44246 // 'a' - 'f'
44247 if (c >= 49 && c <= 54)
44248 r |= c - 49 + 0xa;
44249
44250 // 'A' - 'F'
44251 else if (c >= 17 && c <= 22)
44252 r |= c - 17 + 0xa;
44253
44254 // '0' - '9'
44255 else
44256 r |= c & 0xf;
44257 }
44258 return r;
44259}
44260
44261BN.prototype._parseHex = function _parseHex(number, start) {
44262 // Create possibly bigger array to ensure that it fits the number
44263 this.length = Math.ceil((number.length - start) / 6);
44264 this.words = new Array(this.length);
44265 for (var i = 0; i < this.length; i++)
44266 this.words[i] = 0;
44267
44268 // Scan 24-bit chunks and add them to the number
44269 var off = 0;
44270 for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
44271 var w = parseHex(number, i, i + 6);
44272 this.words[j] |= (w << off) & 0x3ffffff;
44273 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
44274 off += 24;
44275 if (off >= 26) {
44276 off -= 26;
44277 j++;
44278 }
44279 }
44280 if (i + 6 !== start) {
44281 var w = parseHex(number, start, i + 6);
44282 this.words[j] |= (w << off) & 0x3ffffff;
44283 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
44284 }
44285 this.strip();
44286};
44287
44288function parseBase(str, start, end, mul) {
44289 var r = 0;
44290 var len = Math.min(str.length, end);
44291 for (var i = start; i < len; i++) {
44292 var c = str.charCodeAt(i) - 48;
44293
44294 r *= mul;
44295
44296 // 'a'
44297 if (c >= 49)
44298 r += c - 49 + 0xa;
44299
44300 // 'A'
44301 else if (c >= 17)
44302 r += c - 17 + 0xa;
44303
44304 // '0' - '9'
44305 else
44306 r += c;
44307 }
44308 return r;
44309}
44310
44311BN.prototype._parseBase = function _parseBase(number, base, start) {
44312 // Initialize as zero
44313 this.words = [ 0 ];
44314 this.length = 1;
44315
44316 // Find length of limb in base
44317 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
44318 limbLen++;
44319 limbLen--;
44320 limbPow = (limbPow / base) | 0;
44321
44322 var total = number.length - start;
44323 var mod = total % limbLen;
44324 var end = Math.min(total, total - mod) + start;
44325
44326 var word = 0;
44327 for (var i = start; i < end; i += limbLen) {
44328 word = parseBase(number, i, i + limbLen, base);
44329
44330 this.imuln(limbPow);
44331 if (this.words[0] + word < 0x4000000)
44332 this.words[0] += word;
44333 else
44334 this._iaddn(word);
44335 }
44336
44337 if (mod !== 0) {
44338 var pow = 1;
44339 var word = parseBase(number, i, number.length, base);
44340
44341 for (var i = 0; i < mod; i++)
44342 pow *= base;
44343 this.imuln(pow);
44344 if (this.words[0] + word < 0x4000000)
44345 this.words[0] += word;
44346 else
44347 this._iaddn(word);
44348 }
44349};
44350
44351BN.prototype.copy = function copy(dest) {
44352 dest.words = new Array(this.length);
44353 for (var i = 0; i < this.length; i++)
44354 dest.words[i] = this.words[i];
44355 dest.length = this.length;
44356 dest.sign = this.sign;
44357 dest.red = this.red;
44358};
44359
44360BN.prototype.clone = function clone() {
44361 var r = new BN(null);
44362 this.copy(r);
44363 return r;
44364};
44365
44366// Remove leading `0` from `this`
44367BN.prototype.strip = function strip() {
44368 while (this.length > 1 && this.words[this.length - 1] === 0)
44369 this.length--;
44370 return this._normSign();
44371};
44372
44373BN.prototype._normSign = function _normSign() {
44374 // -0 = 0
44375 if (this.length === 1 && this.words[0] === 0)
44376 this.sign = false;
44377 return this;
44378};
44379
44380BN.prototype.inspect = function inspect() {
44381 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
44382};
44383
44384/*
44385
44386var zeros = [];
44387var groupSizes = [];
44388var groupBases = [];
44389
44390var s = '';
44391var i = -1;
44392while (++i < BN.wordSize) {
44393 zeros[i] = s;
44394 s += '0';
44395}
44396groupSizes[0] = 0;
44397groupSizes[1] = 0;
44398groupBases[0] = 0;
44399groupBases[1] = 0;
44400var base = 2 - 1;
44401while (++base < 36 + 1) {
44402 var groupSize = 0;
44403 var groupBase = 1;
44404 while (groupBase < (1 << BN.wordSize) / base) {
44405 groupBase *= base;
44406 groupSize += 1;
44407 }
44408 groupSizes[base] = groupSize;
44409 groupBases[base] = groupBase;
44410}
44411
44412*/
44413
44414var zeros = [
44415 '',
44416 '0',
44417 '00',
44418 '000',
44419 '0000',
44420 '00000',
44421 '000000',
44422 '0000000',
44423 '00000000',
44424 '000000000',
44425 '0000000000',
44426 '00000000000',
44427 '000000000000',
44428 '0000000000000',
44429 '00000000000000',
44430 '000000000000000',
44431 '0000000000000000',
44432 '00000000000000000',
44433 '000000000000000000',
44434 '0000000000000000000',
44435 '00000000000000000000',
44436 '000000000000000000000',
44437 '0000000000000000000000',
44438 '00000000000000000000000',
44439 '000000000000000000000000',
44440 '0000000000000000000000000'
44441];
44442
44443var groupSizes = [
44444 0, 0,
44445 25, 16, 12, 11, 10, 9, 8,
44446 8, 7, 7, 7, 7, 6, 6,
44447 6, 6, 6, 6, 6, 5, 5,
44448 5, 5, 5, 5, 5, 5, 5,
44449 5, 5, 5, 5, 5, 5, 5
44450];
44451
44452var groupBases = [
44453 0, 0,
44454 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
44455 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
44456 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
44457 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
44458 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
44459];
44460
44461BN.prototype.toString = function toString(base, padding) {
44462 base = base || 10;
44463 if (base === 16 || base === 'hex') {
44464 var out = '';
44465 var off = 0;
44466 var padding = padding | 0 || 1;
44467 var carry = 0;
44468 for (var i = 0; i < this.length; i++) {
44469 var w = this.words[i];
44470 var word = (((w << off) | carry) & 0xffffff).toString(16);
44471 carry = (w >>> (24 - off)) & 0xffffff;
44472 if (carry !== 0 || i !== this.length - 1)
44473 out = zeros[6 - word.length] + word + out;
44474 else
44475 out = word + out;
44476 off += 2;
44477 if (off >= 26) {
44478 off -= 26;
44479 i--;
44480 }
44481 }
44482 if (carry !== 0)
44483 out = carry.toString(16) + out;
44484 while (out.length % padding !== 0)
44485 out = '0' + out;
44486 if (this.sign)
44487 out = '-' + out;
44488 return out;
44489 } else if (base === (base | 0) && base >= 2 && base <= 36) {
44490 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
44491 var groupSize = groupSizes[base];
44492 // var groupBase = Math.pow(base, groupSize);
44493 var groupBase = groupBases[base];
44494 var out = '';
44495 var c = this.clone();
44496 c.sign = false;
44497 while (c.cmpn(0) !== 0) {
44498 var r = c.modn(groupBase).toString(base);
44499 c = c.idivn(groupBase);
44500
44501 if (c.cmpn(0) !== 0)
44502 out = zeros[groupSize - r.length] + r + out;
44503 else
44504 out = r + out;
44505 }
44506 if (this.cmpn(0) === 0)
44507 out = '0' + out;
44508 if (this.sign)
44509 out = '-' + out;
44510 return out;
44511 } else {
44512 assert(false, 'Base should be between 2 and 36');
44513 }
44514};
44515
44516BN.prototype.toJSON = function toJSON() {
44517 return this.toString(16);
44518};
44519
44520BN.prototype.toArray = function toArray(endian) {
44521 this.strip();
44522 var res = new Array(this.byteLength());
44523 res[0] = 0;
44524
44525 var q = this.clone();
44526 if (endian !== 'le') {
44527 // Assume big-endian
44528 for (var i = 0; q.cmpn(0) !== 0; i++) {
44529 var b = q.andln(0xff);
44530 q.ishrn(8);
44531
44532 res[res.length - i - 1] = b;
44533 }
44534 } else {
44535 // Assume little-endian
44536 for (var i = 0; q.cmpn(0) !== 0; i++) {
44537 var b = q.andln(0xff);
44538 q.ishrn(8);
44539
44540 res[i] = b;
44541 }
44542 }
44543
44544 return res;
44545};
44546
44547if (Math.clz32) {
44548 BN.prototype._countBits = function _countBits(w) {
44549 return 32 - Math.clz32(w);
44550 };
44551} else {
44552 BN.prototype._countBits = function _countBits(w) {
44553 var t = w;
44554 var r = 0;
44555 if (t >= 0x1000) {
44556 r += 13;
44557 t >>>= 13;
44558 }
44559 if (t >= 0x40) {
44560 r += 7;
44561 t >>>= 7;
44562 }
44563 if (t >= 0x8) {
44564 r += 4;
44565 t >>>= 4;
44566 }
44567 if (t >= 0x02) {
44568 r += 2;
44569 t >>>= 2;
44570 }
44571 return r + t;
44572 };
44573}
44574
44575BN.prototype._zeroBits = function _zeroBits(w) {
44576 // Short-cut
44577 if (w === 0)
44578 return 26;
44579
44580 var t = w;
44581 var r = 0;
44582 if ((t & 0x1fff) === 0) {
44583 r += 13;
44584 t >>>= 13;
44585 }
44586 if ((t & 0x7f) === 0) {
44587 r += 7;
44588 t >>>= 7;
44589 }
44590 if ((t & 0xf) === 0) {
44591 r += 4;
44592 t >>>= 4;
44593 }
44594 if ((t & 0x3) === 0) {
44595 r += 2;
44596 t >>>= 2;
44597 }
44598 if ((t & 0x1) === 0)
44599 r++;
44600 return r;
44601};
44602
44603// Return number of used bits in a BN
44604BN.prototype.bitLength = function bitLength() {
44605 var hi = 0;
44606 var w = this.words[this.length - 1];
44607 var hi = this._countBits(w);
44608 return (this.length - 1) * 26 + hi;
44609};
44610
44611// Number of trailing zero bits
44612BN.prototype.zeroBits = function zeroBits() {
44613 if (this.cmpn(0) === 0)
44614 return 0;
44615
44616 var r = 0;
44617 for (var i = 0; i < this.length; i++) {
44618 var b = this._zeroBits(this.words[i]);
44619 r += b;
44620 if (b !== 26)
44621 break;
44622 }
44623 return r;
44624};
44625
44626BN.prototype.byteLength = function byteLength() {
44627 return Math.ceil(this.bitLength() / 8);
44628};
44629
44630// Return negative clone of `this`
44631BN.prototype.neg = function neg() {
44632 if (this.cmpn(0) === 0)
44633 return this.clone();
44634
44635 var r = this.clone();
44636 r.sign = !this.sign;
44637 return r;
44638};
44639
44640
44641// Or `num` with `this` in-place
44642BN.prototype.ior = function ior(num) {
44643 this.sign = this.sign || num.sign;
44644
44645 while (this.length < num.length)
44646 this.words[this.length++] = 0;
44647
44648 for (var i = 0; i < num.length; i++)
44649 this.words[i] = this.words[i] | num.words[i];
44650
44651 return this.strip();
44652};
44653
44654
44655// Or `num` with `this`
44656BN.prototype.or = function or(num) {
44657 if (this.length > num.length)
44658 return this.clone().ior(num);
44659 else
44660 return num.clone().ior(this);
44661};
44662
44663
44664// And `num` with `this` in-place
44665BN.prototype.iand = function iand(num) {
44666 this.sign = this.sign && num.sign;
44667
44668 // b = min-length(num, this)
44669 var b;
44670 if (this.length > num.length)
44671 b = num;
44672 else
44673 b = this;
44674
44675 for (var i = 0; i < b.length; i++)
44676 this.words[i] = this.words[i] & num.words[i];
44677
44678 this.length = b.length;
44679
44680 return this.strip();
44681};
44682
44683
44684// And `num` with `this`
44685BN.prototype.and = function and(num) {
44686 if (this.length > num.length)
44687 return this.clone().iand(num);
44688 else
44689 return num.clone().iand(this);
44690};
44691
44692
44693// Xor `num` with `this` in-place
44694BN.prototype.ixor = function ixor(num) {
44695 this.sign = this.sign || num.sign;
44696
44697 // a.length > b.length
44698 var a;
44699 var b;
44700 if (this.length > num.length) {
44701 a = this;
44702 b = num;
44703 } else {
44704 a = num;
44705 b = this;
44706 }
44707
44708 for (var i = 0; i < b.length; i++)
44709 this.words[i] = a.words[i] ^ b.words[i];
44710
44711 if (this !== a)
44712 for (; i < a.length; i++)
44713 this.words[i] = a.words[i];
44714
44715 this.length = a.length;
44716
44717 return this.strip();
44718};
44719
44720
44721// Xor `num` with `this`
44722BN.prototype.xor = function xor(num) {
44723 if (this.length > num.length)
44724 return this.clone().ixor(num);
44725 else
44726 return num.clone().ixor(this);
44727};
44728
44729
44730// Set `bit` of `this`
44731BN.prototype.setn = function setn(bit, val) {
44732 assert(typeof bit === 'number' && bit >= 0);
44733
44734 var off = (bit / 26) | 0;
44735 var wbit = bit % 26;
44736
44737 while (this.length <= off)
44738 this.words[this.length++] = 0;
44739
44740 if (val)
44741 this.words[off] = this.words[off] | (1 << wbit);
44742 else
44743 this.words[off] = this.words[off] & ~(1 << wbit);
44744
44745 return this.strip();
44746};
44747
44748
44749// Add `num` to `this` in-place
44750BN.prototype.iadd = function iadd(num) {
44751 // negative + positive
44752 if (this.sign && !num.sign) {
44753 this.sign = false;
44754 var r = this.isub(num);
44755 this.sign = !this.sign;
44756 return this._normSign();
44757
44758 // positive + negative
44759 } else if (!this.sign && num.sign) {
44760 num.sign = false;
44761 var r = this.isub(num);
44762 num.sign = true;
44763 return r._normSign();
44764 }
44765
44766 // a.length > b.length
44767 var a;
44768 var b;
44769 if (this.length > num.length) {
44770 a = this;
44771 b = num;
44772 } else {
44773 a = num;
44774 b = this;
44775 }
44776
44777 var carry = 0;
44778 for (var i = 0; i < b.length; i++) {
44779 var r = a.words[i] + b.words[i] + carry;
44780 this.words[i] = r & 0x3ffffff;
44781 carry = r >>> 26;
44782 }
44783 for (; carry !== 0 && i < a.length; i++) {
44784 var r = a.words[i] + carry;
44785 this.words[i] = r & 0x3ffffff;
44786 carry = r >>> 26;
44787 }
44788
44789 this.length = a.length;
44790 if (carry !== 0) {
44791 this.words[this.length] = carry;
44792 this.length++;
44793 // Copy the rest of the words
44794 } else if (a !== this) {
44795 for (; i < a.length; i++)
44796 this.words[i] = a.words[i];
44797 }
44798
44799 return this;
44800};
44801
44802// Add `num` to `this`
44803BN.prototype.add = function add(num) {
44804 if (num.sign && !this.sign) {
44805 num.sign = false;
44806 var res = this.sub(num);
44807 num.sign = true;
44808 return res;
44809 } else if (!num.sign && this.sign) {
44810 this.sign = false;
44811 var res = num.sub(this);
44812 this.sign = true;
44813 return res;
44814 }
44815
44816 if (this.length > num.length)
44817 return this.clone().iadd(num);
44818 else
44819 return num.clone().iadd(this);
44820};
44821
44822// Subtract `num` from `this` in-place
44823BN.prototype.isub = function isub(num) {
44824 // this - (-num) = this + num
44825 if (num.sign) {
44826 num.sign = false;
44827 var r = this.iadd(num);
44828 num.sign = true;
44829 return r._normSign();
44830
44831 // -this - num = -(this + num)
44832 } else if (this.sign) {
44833 this.sign = false;
44834 this.iadd(num);
44835 this.sign = true;
44836 return this._normSign();
44837 }
44838
44839 // At this point both numbers are positive
44840 var cmp = this.cmp(num);
44841
44842 // Optimization - zeroify
44843 if (cmp === 0) {
44844 this.sign = false;
44845 this.length = 1;
44846 this.words[0] = 0;
44847 return this;
44848 }
44849
44850 // a > b
44851 var a;
44852 var b;
44853 if (cmp > 0) {
44854 a = this;
44855 b = num;
44856 } else {
44857 a = num;
44858 b = this;
44859 }
44860
44861 var carry = 0;
44862 for (var i = 0; i < b.length; i++) {
44863 var r = a.words[i] - b.words[i] + carry;
44864 carry = r >> 26;
44865 this.words[i] = r & 0x3ffffff;
44866 }
44867 for (; carry !== 0 && i < a.length; i++) {
44868 var r = a.words[i] + carry;
44869 carry = r >> 26;
44870 this.words[i] = r & 0x3ffffff;
44871 }
44872
44873 // Copy rest of the words
44874 if (carry === 0 && i < a.length && a !== this)
44875 for (; i < a.length; i++)
44876 this.words[i] = a.words[i];
44877 this.length = Math.max(this.length, i);
44878
44879 if (a !== this)
44880 this.sign = true;
44881
44882 return this.strip();
44883};
44884
44885// Subtract `num` from `this`
44886BN.prototype.sub = function sub(num) {
44887 return this.clone().isub(num);
44888};
44889
44890/*
44891// NOTE: This could be potentionally used to generate loop-less multiplications
44892function _genCombMulTo(alen, blen) {
44893 var len = alen + blen - 1;
44894 var src = [
44895 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
44896 'mask = 0x3ffffff, shift = 0x4000000;',
44897 'out.length = ' + len + ';'
44898 ];
44899 for (var k = 0; k < len; k++) {
44900 var minJ = Math.max(0, k - alen + 1);
44901 var maxJ = Math.min(k, blen - 1);
44902
44903 for (var j = minJ; j <= maxJ; j++) {
44904 var i = k - j;
44905 var mul = 'a[' + i + '] * b[' + j + ']';
44906
44907 if (j === minJ) {
44908 src.push('w = ' + mul + ' + c;');
44909 src.push('c = (w / shift) | 0;');
44910 } else {
44911 src.push('w += ' + mul + ';');
44912 src.push('c += (w / shift) | 0;');
44913 }
44914 src.push('w &= mask;');
44915 }
44916 src.push('o[' + k + '] = w;');
44917 }
44918 src.push('if (c !== 0) {',
44919 ' o[' + k + '] = c;',
44920 ' out.length++;',
44921 '}',
44922 'return out;');
44923
44924 return src.join('\n');
44925}
44926*/
44927
44928BN.prototype._smallMulTo = function _smallMulTo(num, out) {
44929 out.sign = num.sign !== this.sign;
44930 out.length = this.length + num.length;
44931
44932 var carry = 0;
44933 for (var k = 0; k < out.length - 1; k++) {
44934 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
44935 // note that ncarry could be >= 0x3ffffff
44936 var ncarry = carry >>> 26;
44937 var rword = carry & 0x3ffffff;
44938 var maxJ = Math.min(k, num.length - 1);
44939 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
44940 var i = k - j;
44941 var a = this.words[i] | 0;
44942 var b = num.words[j] | 0;
44943 var r = a * b;
44944
44945 var lo = r & 0x3ffffff;
44946 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
44947 lo = (lo + rword) | 0;
44948 rword = lo & 0x3ffffff;
44949 ncarry = (ncarry + (lo >>> 26)) | 0;
44950 }
44951 out.words[k] = rword;
44952 carry = ncarry;
44953 }
44954 if (carry !== 0) {
44955 out.words[k] = carry;
44956 } else {
44957 out.length--;
44958 }
44959
44960 return out.strip();
44961};
44962
44963BN.prototype._bigMulTo = function _bigMulTo(num, out) {
44964 out.sign = num.sign !== this.sign;
44965 out.length = this.length + num.length;
44966
44967 var carry = 0;
44968 var hncarry = 0;
44969 for (var k = 0; k < out.length - 1; k++) {
44970 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
44971 // note that ncarry could be >= 0x3ffffff
44972 var ncarry = hncarry;
44973 hncarry = 0;
44974 var rword = carry & 0x3ffffff;
44975 var maxJ = Math.min(k, num.length - 1);
44976 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
44977 var i = k - j;
44978 var a = this.words[i] | 0;
44979 var b = num.words[j] | 0;
44980 var r = a * b;
44981
44982 var lo = r & 0x3ffffff;
44983 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
44984 lo = (lo + rword) | 0;
44985 rword = lo & 0x3ffffff;
44986 ncarry = (ncarry + (lo >>> 26)) | 0;
44987
44988 hncarry += ncarry >>> 26;
44989 ncarry &= 0x3ffffff;
44990 }
44991 out.words[k] = rword;
44992 carry = ncarry;
44993 ncarry = hncarry;
44994 }
44995 if (carry !== 0) {
44996 out.words[k] = carry;
44997 } else {
44998 out.length--;
44999 }
45000
45001 return out.strip();
45002};
45003
45004BN.prototype.mulTo = function mulTo(num, out) {
45005 var res;
45006 if (this.length + num.length < 63)
45007 res = this._smallMulTo(num, out);
45008 else
45009 res = this._bigMulTo(num, out);
45010 return res;
45011};
45012
45013// Multiply `this` by `num`
45014BN.prototype.mul = function mul(num) {
45015 var out = new BN(null);
45016 out.words = new Array(this.length + num.length);
45017 return this.mulTo(num, out);
45018};
45019
45020// In-place Multiplication
45021BN.prototype.imul = function imul(num) {
45022 if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
45023 this.words[0] = 0;
45024 this.length = 1;
45025 return this;
45026 }
45027
45028 var tlen = this.length;
45029 var nlen = num.length;
45030
45031 this.sign = num.sign !== this.sign;
45032 this.length = this.length + num.length;
45033 this.words[this.length - 1] = 0;
45034
45035 for (var k = this.length - 2; k >= 0; k--) {
45036 // Sum all words with the same `i + j = k` and accumulate `carry`,
45037 // note that carry could be >= 0x3ffffff
45038 var carry = 0;
45039 var rword = 0;
45040 var maxJ = Math.min(k, nlen - 1);
45041 for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
45042 var i = k - j;
45043 var a = this.words[i];
45044 var b = num.words[j];
45045 var r = a * b;
45046
45047 var lo = r & 0x3ffffff;
45048 carry += (r / 0x4000000) | 0;
45049 lo += rword;
45050 rword = lo & 0x3ffffff;
45051 carry += lo >>> 26;
45052 }
45053 this.words[k] = rword;
45054 this.words[k + 1] += carry;
45055 carry = 0;
45056 }
45057
45058 // Propagate overflows
45059 var carry = 0;
45060 for (var i = 1; i < this.length; i++) {
45061 var w = this.words[i] + carry;
45062 this.words[i] = w & 0x3ffffff;
45063 carry = w >>> 26;
45064 }
45065
45066 return this.strip();
45067};
45068
45069BN.prototype.imuln = function imuln(num) {
45070 assert(typeof num === 'number');
45071
45072 // Carry
45073 var carry = 0;
45074 for (var i = 0; i < this.length; i++) {
45075 var w = this.words[i] * num;
45076 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
45077 carry >>= 26;
45078 carry += (w / 0x4000000) | 0;
45079 // NOTE: lo is 27bit maximum
45080 carry += lo >>> 26;
45081 this.words[i] = lo & 0x3ffffff;
45082 }
45083
45084 if (carry !== 0) {
45085 this.words[i] = carry;
45086 this.length++;
45087 }
45088
45089 return this;
45090};
45091
45092BN.prototype.muln = function muln(num) {
45093 return this.clone().imuln(num);
45094};
45095
45096// `this` * `this`
45097BN.prototype.sqr = function sqr() {
45098 return this.mul(this);
45099};
45100
45101// `this` * `this` in-place
45102BN.prototype.isqr = function isqr() {
45103 return this.mul(this);
45104};
45105
45106// Shift-left in-place
45107BN.prototype.ishln = function ishln(bits) {
45108 assert(typeof bits === 'number' && bits >= 0);
45109 var r = bits % 26;
45110 var s = (bits - r) / 26;
45111 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
45112
45113 if (r !== 0) {
45114 var carry = 0;
45115 for (var i = 0; i < this.length; i++) {
45116 var newCarry = this.words[i] & carryMask;
45117 var c = (this.words[i] - newCarry) << r;
45118 this.words[i] = c | carry;
45119 carry = newCarry >>> (26 - r);
45120 }
45121 if (carry) {
45122 this.words[i] = carry;
45123 this.length++;
45124 }
45125 }
45126
45127 if (s !== 0) {
45128 for (var i = this.length - 1; i >= 0; i--)
45129 this.words[i + s] = this.words[i];
45130 for (var i = 0; i < s; i++)
45131 this.words[i] = 0;
45132 this.length += s;
45133 }
45134
45135 return this.strip();
45136};
45137
45138// Shift-right in-place
45139// NOTE: `hint` is a lowest bit before trailing zeroes
45140// NOTE: if `extended` is present - it will be filled with destroyed bits
45141BN.prototype.ishrn = function ishrn(bits, hint, extended) {
45142 assert(typeof bits === 'number' && bits >= 0);
45143 var h;
45144 if (hint)
45145 h = (hint - (hint % 26)) / 26;
45146 else
45147 h = 0;
45148
45149 var r = bits % 26;
45150 var s = Math.min((bits - r) / 26, this.length);
45151 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
45152 var maskedWords = extended;
45153
45154 h -= s;
45155 h = Math.max(0, h);
45156
45157 // Extended mode, copy masked part
45158 if (maskedWords) {
45159 for (var i = 0; i < s; i++)
45160 maskedWords.words[i] = this.words[i];
45161 maskedWords.length = s;
45162 }
45163
45164 if (s === 0) {
45165 // No-op, we should not move anything at all
45166 } else if (this.length > s) {
45167 this.length -= s;
45168 for (var i = 0; i < this.length; i++)
45169 this.words[i] = this.words[i + s];
45170 } else {
45171 this.words[0] = 0;
45172 this.length = 1;
45173 }
45174
45175 var carry = 0;
45176 for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
45177 var word = this.words[i];
45178 this.words[i] = (carry << (26 - r)) | (word >>> r);
45179 carry = word & mask;
45180 }
45181
45182 // Push carried bits as a mask
45183 if (maskedWords && carry !== 0)
45184 maskedWords.words[maskedWords.length++] = carry;
45185
45186 if (this.length === 0) {
45187 this.words[0] = 0;
45188 this.length = 1;
45189 }
45190
45191 this.strip();
45192
45193 return this;
45194};
45195
45196// Shift-left
45197BN.prototype.shln = function shln(bits) {
45198 return this.clone().ishln(bits);
45199};
45200
45201// Shift-right
45202BN.prototype.shrn = function shrn(bits) {
45203 return this.clone().ishrn(bits);
45204};
45205
45206// Test if n bit is set
45207BN.prototype.testn = function testn(bit) {
45208 assert(typeof bit === 'number' && bit >= 0);
45209 var r = bit % 26;
45210 var s = (bit - r) / 26;
45211 var q = 1 << r;
45212
45213 // Fast case: bit is much higher than all existing words
45214 if (this.length <= s) {
45215 return false;
45216 }
45217
45218 // Check bit and return
45219 var w = this.words[s];
45220
45221 return !!(w & q);
45222};
45223
45224// Return only lowers bits of number (in-place)
45225BN.prototype.imaskn = function imaskn(bits) {
45226 assert(typeof bits === 'number' && bits >= 0);
45227 var r = bits % 26;
45228 var s = (bits - r) / 26;
45229
45230 assert(!this.sign, 'imaskn works only with positive numbers');
45231
45232 if (r !== 0)
45233 s++;
45234 this.length = Math.min(s, this.length);
45235
45236 if (r !== 0) {
45237 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
45238 this.words[this.length - 1] &= mask;
45239 }
45240
45241 return this.strip();
45242};
45243
45244// Return only lowers bits of number
45245BN.prototype.maskn = function maskn(bits) {
45246 return this.clone().imaskn(bits);
45247};
45248
45249// Add plain number `num` to `this`
45250BN.prototype.iaddn = function iaddn(num) {
45251 assert(typeof num === 'number');
45252 if (num < 0)
45253 return this.isubn(-num);
45254
45255 // Possible sign change
45256 if (this.sign) {
45257 if (this.length === 1 && this.words[0] < num) {
45258 this.words[0] = num - this.words[0];
45259 this.sign = false;
45260 return this;
45261 }
45262
45263 this.sign = false;
45264 this.isubn(num);
45265 this.sign = true;
45266 return this;
45267 }
45268
45269 // Add without checks
45270 return this._iaddn(num);
45271};
45272
45273BN.prototype._iaddn = function _iaddn(num) {
45274 this.words[0] += num;
45275
45276 // Carry
45277 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
45278 this.words[i] -= 0x4000000;
45279 if (i === this.length - 1)
45280 this.words[i + 1] = 1;
45281 else
45282 this.words[i + 1]++;
45283 }
45284 this.length = Math.max(this.length, i + 1);
45285
45286 return this;
45287};
45288
45289// Subtract plain number `num` from `this`
45290BN.prototype.isubn = function isubn(num) {
45291 assert(typeof num === 'number');
45292 if (num < 0)
45293 return this.iaddn(-num);
45294
45295 if (this.sign) {
45296 this.sign = false;
45297 this.iaddn(num);
45298 this.sign = true;
45299 return this;
45300 }
45301
45302 this.words[0] -= num;
45303
45304 // Carry
45305 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
45306 this.words[i] += 0x4000000;
45307 this.words[i + 1] -= 1;
45308 }
45309
45310 return this.strip();
45311};
45312
45313BN.prototype.addn = function addn(num) {
45314 return this.clone().iaddn(num);
45315};
45316
45317BN.prototype.subn = function subn(num) {
45318 return this.clone().isubn(num);
45319};
45320
45321BN.prototype.iabs = function iabs() {
45322 this.sign = false;
45323
45324 return this;
45325};
45326
45327BN.prototype.abs = function abs() {
45328 return this.clone().iabs();
45329};
45330
45331BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
45332 // Bigger storage is needed
45333 var len = num.length + shift;
45334 var i;
45335 if (this.words.length < len) {
45336 var t = new Array(len);
45337 for (var i = 0; i < this.length; i++)
45338 t[i] = this.words[i];
45339 this.words = t;
45340 } else {
45341 i = this.length;
45342 }
45343
45344 // Zeroify rest
45345 this.length = Math.max(this.length, len);
45346 for (; i < this.length; i++)
45347 this.words[i] = 0;
45348
45349 var carry = 0;
45350 for (var i = 0; i < num.length; i++) {
45351 var w = this.words[i + shift] + carry;
45352 var right = num.words[i] * mul;
45353 w -= right & 0x3ffffff;
45354 carry = (w >> 26) - ((right / 0x4000000) | 0);
45355 this.words[i + shift] = w & 0x3ffffff;
45356 }
45357 for (; i < this.length - shift; i++) {
45358 var w = this.words[i + shift] + carry;
45359 carry = w >> 26;
45360 this.words[i + shift] = w & 0x3ffffff;
45361 }
45362
45363 if (carry === 0)
45364 return this.strip();
45365
45366 // Subtraction overflow
45367 assert(carry === -1);
45368 carry = 0;
45369 for (var i = 0; i < this.length; i++) {
45370 var w = -this.words[i] + carry;
45371 carry = w >> 26;
45372 this.words[i] = w & 0x3ffffff;
45373 }
45374 this.sign = true;
45375
45376 return this.strip();
45377};
45378
45379BN.prototype._wordDiv = function _wordDiv(num, mode) {
45380 var shift = this.length - num.length;
45381
45382 var a = this.clone();
45383 var b = num;
45384
45385 // Normalize
45386 var bhi = b.words[b.length - 1];
45387 var bhiBits = this._countBits(bhi);
45388 shift = 26 - bhiBits;
45389 if (shift !== 0) {
45390 b = b.shln(shift);
45391 a.ishln(shift);
45392 bhi = b.words[b.length - 1];
45393 }
45394
45395 // Initialize quotient
45396 var m = a.length - b.length;
45397 var q;
45398
45399 if (mode !== 'mod') {
45400 q = new BN(null);
45401 q.length = m + 1;
45402 q.words = new Array(q.length);
45403 for (var i = 0; i < q.length; i++)
45404 q.words[i] = 0;
45405 }
45406
45407 var diff = a.clone()._ishlnsubmul(b, 1, m);
45408 if (!diff.sign) {
45409 a = diff;
45410 if (q)
45411 q.words[m] = 1;
45412 }
45413
45414 for (var j = m - 1; j >= 0; j--) {
45415 var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
45416
45417 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
45418 // (0x7ffffff)
45419 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
45420
45421 a._ishlnsubmul(b, qj, j);
45422 while (a.sign) {
45423 qj--;
45424 a.sign = false;
45425 a._ishlnsubmul(b, 1, j);
45426 if (a.cmpn(0) !== 0)
45427 a.sign = !a.sign;
45428 }
45429 if (q)
45430 q.words[j] = qj;
45431 }
45432 if (q)
45433 q.strip();
45434 a.strip();
45435
45436 // Denormalize
45437 if (mode !== 'div' && shift !== 0)
45438 a.ishrn(shift);
45439 return { div: q ? q : null, mod: a };
45440};
45441
45442BN.prototype.divmod = function divmod(num, mode) {
45443 assert(num.cmpn(0) !== 0);
45444
45445 if (this.sign && !num.sign) {
45446 var res = this.neg().divmod(num, mode);
45447 var div;
45448 var mod;
45449 if (mode !== 'mod')
45450 div = res.div.neg();
45451 if (mode !== 'div')
45452 mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod);
45453 return {
45454 div: div,
45455 mod: mod
45456 };
45457 } else if (!this.sign && num.sign) {
45458 var res = this.divmod(num.neg(), mode);
45459 var div;
45460 if (mode !== 'mod')
45461 div = res.div.neg();
45462 return { div: div, mod: res.mod };
45463 } else if (this.sign && num.sign) {
45464 return this.neg().divmod(num.neg(), mode);
45465 }
45466
45467 // Both numbers are positive at this point
45468
45469 // Strip both numbers to approximate shift value
45470 if (num.length > this.length || this.cmp(num) < 0)
45471 return { div: new BN(0), mod: this };
45472
45473 // Very short reduction
45474 if (num.length === 1) {
45475 if (mode === 'div')
45476 return { div: this.divn(num.words[0]), mod: null };
45477 else if (mode === 'mod')
45478 return { div: null, mod: new BN(this.modn(num.words[0])) };
45479 return {
45480 div: this.divn(num.words[0]),
45481 mod: new BN(this.modn(num.words[0]))
45482 };
45483 }
45484
45485 return this._wordDiv(num, mode);
45486};
45487
45488// Find `this` / `num`
45489BN.prototype.div = function div(num) {
45490 return this.divmod(num, 'div').div;
45491};
45492
45493// Find `this` % `num`
45494BN.prototype.mod = function mod(num) {
45495 return this.divmod(num, 'mod').mod;
45496};
45497
45498// Find Round(`this` / `num`)
45499BN.prototype.divRound = function divRound(num) {
45500 var dm = this.divmod(num);
45501
45502 // Fast case - exact division
45503 if (dm.mod.cmpn(0) === 0)
45504 return dm.div;
45505
45506 var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
45507
45508 var half = num.shrn(1);
45509 var r2 = num.andln(1);
45510 var cmp = mod.cmp(half);
45511
45512 // Round down
45513 if (cmp < 0 || r2 === 1 && cmp === 0)
45514 return dm.div;
45515
45516 // Round up
45517 return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
45518};
45519
45520BN.prototype.modn = function modn(num) {
45521 assert(num <= 0x3ffffff);
45522 var p = (1 << 26) % num;
45523
45524 var acc = 0;
45525 for (var i = this.length - 1; i >= 0; i--)
45526 acc = (p * acc + this.words[i]) % num;
45527
45528 return acc;
45529};
45530
45531// In-place division by number
45532BN.prototype.idivn = function idivn(num) {
45533 assert(num <= 0x3ffffff);
45534
45535 var carry = 0;
45536 for (var i = this.length - 1; i >= 0; i--) {
45537 var w = this.words[i] + carry * 0x4000000;
45538 this.words[i] = (w / num) | 0;
45539 carry = w % num;
45540 }
45541
45542 return this.strip();
45543};
45544
45545BN.prototype.divn = function divn(num) {
45546 return this.clone().idivn(num);
45547};
45548
45549BN.prototype.egcd = function egcd(p) {
45550 assert(!p.sign);
45551 assert(p.cmpn(0) !== 0);
45552
45553 var x = this;
45554 var y = p.clone();
45555
45556 if (x.sign)
45557 x = x.mod(p);
45558 else
45559 x = x.clone();
45560
45561 // A * x + B * y = x
45562 var A = new BN(1);
45563 var B = new BN(0);
45564
45565 // C * x + D * y = y
45566 var C = new BN(0);
45567 var D = new BN(1);
45568
45569 var g = 0;
45570
45571 while (x.isEven() && y.isEven()) {
45572 x.ishrn(1);
45573 y.ishrn(1);
45574 ++g;
45575 }
45576
45577 var yp = y.clone();
45578 var xp = x.clone();
45579
45580 while (x.cmpn(0) !== 0) {
45581 while (x.isEven()) {
45582 x.ishrn(1);
45583 if (A.isEven() && B.isEven()) {
45584 A.ishrn(1);
45585 B.ishrn(1);
45586 } else {
45587 A.iadd(yp).ishrn(1);
45588 B.isub(xp).ishrn(1);
45589 }
45590 }
45591
45592 while (y.isEven()) {
45593 y.ishrn(1);
45594 if (C.isEven() && D.isEven()) {
45595 C.ishrn(1);
45596 D.ishrn(1);
45597 } else {
45598 C.iadd(yp).ishrn(1);
45599 D.isub(xp).ishrn(1);
45600 }
45601 }
45602
45603 if (x.cmp(y) >= 0) {
45604 x.isub(y);
45605 A.isub(C);
45606 B.isub(D);
45607 } else {
45608 y.isub(x);
45609 C.isub(A);
45610 D.isub(B);
45611 }
45612 }
45613
45614 return {
45615 a: C,
45616 b: D,
45617 gcd: y.ishln(g)
45618 };
45619};
45620
45621// This is reduced incarnation of the binary EEA
45622// above, designated to invert members of the
45623// _prime_ fields F(p) at a maximal speed
45624BN.prototype._invmp = function _invmp(p) {
45625 assert(!p.sign);
45626 assert(p.cmpn(0) !== 0);
45627
45628 var a = this;
45629 var b = p.clone();
45630
45631 if (a.sign)
45632 a = a.mod(p);
45633 else
45634 a = a.clone();
45635
45636 var x1 = new BN(1);
45637 var x2 = new BN(0);
45638
45639 var delta = b.clone();
45640
45641 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
45642 while (a.isEven()) {
45643 a.ishrn(1);
45644 if (x1.isEven())
45645 x1.ishrn(1);
45646 else
45647 x1.iadd(delta).ishrn(1);
45648 }
45649 while (b.isEven()) {
45650 b.ishrn(1);
45651 if (x2.isEven())
45652 x2.ishrn(1);
45653 else
45654 x2.iadd(delta).ishrn(1);
45655 }
45656 if (a.cmp(b) >= 0) {
45657 a.isub(b);
45658 x1.isub(x2);
45659 } else {
45660 b.isub(a);
45661 x2.isub(x1);
45662 }
45663 }
45664 if (a.cmpn(1) === 0)
45665 return x1;
45666 else
45667 return x2;
45668};
45669
45670BN.prototype.gcd = function gcd(num) {
45671 if (this.cmpn(0) === 0)
45672 return num.clone();
45673 if (num.cmpn(0) === 0)
45674 return this.clone();
45675
45676 var a = this.clone();
45677 var b = num.clone();
45678 a.sign = false;
45679 b.sign = false;
45680
45681 // Remove common factor of two
45682 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
45683 a.ishrn(1);
45684 b.ishrn(1);
45685 }
45686
45687 do {
45688 while (a.isEven())
45689 a.ishrn(1);
45690 while (b.isEven())
45691 b.ishrn(1);
45692
45693 var r = a.cmp(b);
45694 if (r < 0) {
45695 // Swap `a` and `b` to make `a` always bigger than `b`
45696 var t = a;
45697 a = b;
45698 b = t;
45699 } else if (r === 0 || b.cmpn(1) === 0) {
45700 break;
45701 }
45702
45703 a.isub(b);
45704 } while (true);
45705
45706 return b.ishln(shift);
45707};
45708
45709// Invert number in the field F(num)
45710BN.prototype.invm = function invm(num) {
45711 return this.egcd(num).a.mod(num);
45712};
45713
45714BN.prototype.isEven = function isEven() {
45715 return (this.words[0] & 1) === 0;
45716};
45717
45718BN.prototype.isOdd = function isOdd() {
45719 return (this.words[0] & 1) === 1;
45720};
45721
45722// And first word and num
45723BN.prototype.andln = function andln(num) {
45724 return this.words[0] & num;
45725};
45726
45727// Increment at the bit position in-line
45728BN.prototype.bincn = function bincn(bit) {
45729 assert(typeof bit === 'number');
45730 var r = bit % 26;
45731 var s = (bit - r) / 26;
45732 var q = 1 << r;
45733
45734 // Fast case: bit is much higher than all existing words
45735 if (this.length <= s) {
45736 for (var i = this.length; i < s + 1; i++)
45737 this.words[i] = 0;
45738 this.words[s] |= q;
45739 this.length = s + 1;
45740 return this;
45741 }
45742
45743 // Add bit and propagate, if needed
45744 var carry = q;
45745 for (var i = s; carry !== 0 && i < this.length; i++) {
45746 var w = this.words[i];
45747 w += carry;
45748 carry = w >>> 26;
45749 w &= 0x3ffffff;
45750 this.words[i] = w;
45751 }
45752 if (carry !== 0) {
45753 this.words[i] = carry;
45754 this.length++;
45755 }
45756 return this;
45757};
45758
45759BN.prototype.cmpn = function cmpn(num) {
45760 var sign = num < 0;
45761 if (sign)
45762 num = -num;
45763
45764 if (this.sign && !sign)
45765 return -1;
45766 else if (!this.sign && sign)
45767 return 1;
45768
45769 num &= 0x3ffffff;
45770 this.strip();
45771
45772 var res;
45773 if (this.length > 1) {
45774 res = 1;
45775 } else {
45776 var w = this.words[0];
45777 res = w === num ? 0 : w < num ? -1 : 1;
45778 }
45779 if (this.sign)
45780 res = -res;
45781 return res;
45782};
45783
45784// Compare two numbers and return:
45785// 1 - if `this` > `num`
45786// 0 - if `this` == `num`
45787// -1 - if `this` < `num`
45788BN.prototype.cmp = function cmp(num) {
45789 if (this.sign && !num.sign)
45790 return -1;
45791 else if (!this.sign && num.sign)
45792 return 1;
45793
45794 var res = this.ucmp(num);
45795 if (this.sign)
45796 return -res;
45797 else
45798 return res;
45799};
45800
45801// Unsigned comparison
45802BN.prototype.ucmp = function ucmp(num) {
45803 // At this point both numbers have the same sign
45804 if (this.length > num.length)
45805 return 1;
45806 else if (this.length < num.length)
45807 return -1;
45808
45809 var res = 0;
45810 for (var i = this.length - 1; i >= 0; i--) {
45811 var a = this.words[i];
45812 var b = num.words[i];
45813
45814 if (a === b)
45815 continue;
45816 if (a < b)
45817 res = -1;
45818 else if (a > b)
45819 res = 1;
45820 break;
45821 }
45822 return res;
45823};
45824
45825//
45826// A reduce context, could be using montgomery or something better, depending
45827// on the `m` itself.
45828//
45829BN.red = function red(num) {
45830 return new Red(num);
45831};
45832
45833BN.prototype.toRed = function toRed(ctx) {
45834 assert(!this.red, 'Already a number in reduction context');
45835 assert(!this.sign, 'red works only with positives');
45836 return ctx.convertTo(this)._forceRed(ctx);
45837};
45838
45839BN.prototype.fromRed = function fromRed() {
45840 assert(this.red, 'fromRed works only with numbers in reduction context');
45841 return this.red.convertFrom(this);
45842};
45843
45844BN.prototype._forceRed = function _forceRed(ctx) {
45845 this.red = ctx;
45846 return this;
45847};
45848
45849BN.prototype.forceRed = function forceRed(ctx) {
45850 assert(!this.red, 'Already a number in reduction context');
45851 return this._forceRed(ctx);
45852};
45853
45854BN.prototype.redAdd = function redAdd(num) {
45855 assert(this.red, 'redAdd works only with red numbers');
45856 return this.red.add(this, num);
45857};
45858
45859BN.prototype.redIAdd = function redIAdd(num) {
45860 assert(this.red, 'redIAdd works only with red numbers');
45861 return this.red.iadd(this, num);
45862};
45863
45864BN.prototype.redSub = function redSub(num) {
45865 assert(this.red, 'redSub works only with red numbers');
45866 return this.red.sub(this, num);
45867};
45868
45869BN.prototype.redISub = function redISub(num) {
45870 assert(this.red, 'redISub works only with red numbers');
45871 return this.red.isub(this, num);
45872};
45873
45874BN.prototype.redShl = function redShl(num) {
45875 assert(this.red, 'redShl works only with red numbers');
45876 return this.red.shl(this, num);
45877};
45878
45879BN.prototype.redMul = function redMul(num) {
45880 assert(this.red, 'redMul works only with red numbers');
45881 this.red._verify2(this, num);
45882 return this.red.mul(this, num);
45883};
45884
45885BN.prototype.redIMul = function redIMul(num) {
45886 assert(this.red, 'redMul works only with red numbers');
45887 this.red._verify2(this, num);
45888 return this.red.imul(this, num);
45889};
45890
45891BN.prototype.redSqr = function redSqr() {
45892 assert(this.red, 'redSqr works only with red numbers');
45893 this.red._verify1(this);
45894 return this.red.sqr(this);
45895};
45896
45897BN.prototype.redISqr = function redISqr() {
45898 assert(this.red, 'redISqr works only with red numbers');
45899 this.red._verify1(this);
45900 return this.red.isqr(this);
45901};
45902
45903// Square root over p
45904BN.prototype.redSqrt = function redSqrt() {
45905 assert(this.red, 'redSqrt works only with red numbers');
45906 this.red._verify1(this);
45907 return this.red.sqrt(this);
45908};
45909
45910BN.prototype.redInvm = function redInvm() {
45911 assert(this.red, 'redInvm works only with red numbers');
45912 this.red._verify1(this);
45913 return this.red.invm(this);
45914};
45915
45916// Return negative clone of `this` % `red modulo`
45917BN.prototype.redNeg = function redNeg() {
45918 assert(this.red, 'redNeg works only with red numbers');
45919 this.red._verify1(this);
45920 return this.red.neg(this);
45921};
45922
45923BN.prototype.redPow = function redPow(num) {
45924 assert(this.red && !num.red, 'redPow(normalNum)');
45925 this.red._verify1(this);
45926 return this.red.pow(this, num);
45927};
45928
45929// Prime numbers with efficient reduction
45930var primes = {
45931 k256: null,
45932 p224: null,
45933 p192: null,
45934 p25519: null
45935};
45936
45937// Pseudo-Mersenne prime
45938function MPrime(name, p) {
45939 // P = 2 ^ N - K
45940 this.name = name;
45941 this.p = new BN(p, 16);
45942 this.n = this.p.bitLength();
45943 this.k = new BN(1).ishln(this.n).isub(this.p);
45944
45945 this.tmp = this._tmp();
45946}
45947
45948MPrime.prototype._tmp = function _tmp() {
45949 var tmp = new BN(null);
45950 tmp.words = new Array(Math.ceil(this.n / 13));
45951 return tmp;
45952};
45953
45954MPrime.prototype.ireduce = function ireduce(num) {
45955 // Assumes that `num` is less than `P^2`
45956 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
45957 var r = num;
45958 var rlen;
45959
45960 do {
45961 this.split(r, this.tmp);
45962 r = this.imulK(r);
45963 r = r.iadd(this.tmp);
45964 rlen = r.bitLength();
45965 } while (rlen > this.n);
45966
45967 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
45968 if (cmp === 0) {
45969 r.words[0] = 0;
45970 r.length = 1;
45971 } else if (cmp > 0) {
45972 r.isub(this.p);
45973 } else {
45974 r.strip();
45975 }
45976
45977 return r;
45978};
45979
45980MPrime.prototype.split = function split(input, out) {
45981 input.ishrn(this.n, 0, out);
45982};
45983
45984MPrime.prototype.imulK = function imulK(num) {
45985 return num.imul(this.k);
45986};
45987
45988function K256() {
45989 MPrime.call(
45990 this,
45991 'k256',
45992 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
45993}
45994inherits(K256, MPrime);
45995
45996K256.prototype.split = function split(input, output) {
45997 // 256 = 9 * 26 + 22
45998 var mask = 0x3fffff;
45999
46000 var outLen = Math.min(input.length, 9);
46001 for (var i = 0; i < outLen; i++)
46002 output.words[i] = input.words[i];
46003 output.length = outLen;
46004
46005 if (input.length <= 9) {
46006 input.words[0] = 0;
46007 input.length = 1;
46008 return;
46009 }
46010
46011 // Shift by 9 limbs
46012 var prev = input.words[9];
46013 output.words[output.length++] = prev & mask;
46014
46015 for (var i = 10; i < input.length; i++) {
46016 var next = input.words[i];
46017 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
46018 prev = next;
46019 }
46020 input.words[i - 10] = prev >>> 22;
46021 input.length -= 9;
46022};
46023
46024K256.prototype.imulK = function imulK(num) {
46025 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
46026 num.words[num.length] = 0;
46027 num.words[num.length + 1] = 0;
46028 num.length += 2;
46029
46030 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
46031 var hi;
46032 var lo = 0;
46033 for (var i = 0; i < num.length; i++) {
46034 var w = num.words[i];
46035 hi = w * 0x40;
46036 lo += w * 0x3d1;
46037 hi += (lo / 0x4000000) | 0;
46038 lo &= 0x3ffffff;
46039
46040 num.words[i] = lo;
46041
46042 lo = hi;
46043 }
46044
46045 // Fast length reduction
46046 if (num.words[num.length - 1] === 0) {
46047 num.length--;
46048 if (num.words[num.length - 1] === 0)
46049 num.length--;
46050 }
46051 return num;
46052};
46053
46054function P224() {
46055 MPrime.call(
46056 this,
46057 'p224',
46058 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
46059}
46060inherits(P224, MPrime);
46061
46062function P192() {
46063 MPrime.call(
46064 this,
46065 'p192',
46066 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
46067}
46068inherits(P192, MPrime);
46069
46070function P25519() {
46071 // 2 ^ 255 - 19
46072 MPrime.call(
46073 this,
46074 '25519',
46075 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
46076}
46077inherits(P25519, MPrime);
46078
46079P25519.prototype.imulK = function imulK(num) {
46080 // K = 0x13
46081 var carry = 0;
46082 for (var i = 0; i < num.length; i++) {
46083 var hi = num.words[i] * 0x13 + carry;
46084 var lo = hi & 0x3ffffff;
46085 hi >>>= 26;
46086
46087 num.words[i] = lo;
46088 carry = hi;
46089 }
46090 if (carry !== 0)
46091 num.words[num.length++] = carry;
46092 return num;
46093};
46094
46095// Exported mostly for testing purposes, use plain name instead
46096BN._prime = function prime(name) {
46097 // Cached version of prime
46098 if (primes[name])
46099 return primes[name];
46100
46101 var prime;
46102 if (name === 'k256')
46103 prime = new K256();
46104 else if (name === 'p224')
46105 prime = new P224();
46106 else if (name === 'p192')
46107 prime = new P192();
46108 else if (name === 'p25519')
46109 prime = new P25519();
46110 else
46111 throw new Error('Unknown prime ' + name);
46112 primes[name] = prime;
46113
46114 return prime;
46115};
46116
46117//
46118// Base reduction engine
46119//
46120function Red(m) {
46121 if (typeof m === 'string') {
46122 var prime = BN._prime(m);
46123 this.m = prime.p;
46124 this.prime = prime;
46125 } else {
46126 this.m = m;
46127 this.prime = null;
46128 }
46129}
46130
46131Red.prototype._verify1 = function _verify1(a) {
46132 assert(!a.sign, 'red works only with positives');
46133 assert(a.red, 'red works only with red numbers');
46134};
46135
46136Red.prototype._verify2 = function _verify2(a, b) {
46137 assert(!a.sign && !b.sign, 'red works only with positives');
46138 assert(a.red && a.red === b.red,
46139 'red works only with red numbers');
46140};
46141
46142Red.prototype.imod = function imod(a) {
46143 if (this.prime)
46144 return this.prime.ireduce(a)._forceRed(this);
46145 return a.mod(this.m)._forceRed(this);
46146};
46147
46148Red.prototype.neg = function neg(a) {
46149 var r = a.clone();
46150 r.sign = !r.sign;
46151 return r.iadd(this.m)._forceRed(this);
46152};
46153
46154Red.prototype.add = function add(a, b) {
46155 this._verify2(a, b);
46156
46157 var res = a.add(b);
46158 if (res.cmp(this.m) >= 0)
46159 res.isub(this.m);
46160 return res._forceRed(this);
46161};
46162
46163Red.prototype.iadd = function iadd(a, b) {
46164 this._verify2(a, b);
46165
46166 var res = a.iadd(b);
46167 if (res.cmp(this.m) >= 0)
46168 res.isub(this.m);
46169 return res;
46170};
46171
46172Red.prototype.sub = function sub(a, b) {
46173 this._verify2(a, b);
46174
46175 var res = a.sub(b);
46176 if (res.cmpn(0) < 0)
46177 res.iadd(this.m);
46178 return res._forceRed(this);
46179};
46180
46181Red.prototype.isub = function isub(a, b) {
46182 this._verify2(a, b);
46183
46184 var res = a.isub(b);
46185 if (res.cmpn(0) < 0)
46186 res.iadd(this.m);
46187 return res;
46188};
46189
46190Red.prototype.shl = function shl(a, num) {
46191 this._verify1(a);
46192 return this.imod(a.shln(num));
46193};
46194
46195Red.prototype.imul = function imul(a, b) {
46196 this._verify2(a, b);
46197 return this.imod(a.imul(b));
46198};
46199
46200Red.prototype.mul = function mul(a, b) {
46201 this._verify2(a, b);
46202 return this.imod(a.mul(b));
46203};
46204
46205Red.prototype.isqr = function isqr(a) {
46206 return this.imul(a, a);
46207};
46208
46209Red.prototype.sqr = function sqr(a) {
46210 return this.mul(a, a);
46211};
46212
46213Red.prototype.sqrt = function sqrt(a) {
46214 if (a.cmpn(0) === 0)
46215 return a.clone();
46216
46217 var mod3 = this.m.andln(3);
46218 assert(mod3 % 2 === 1);
46219
46220 // Fast case
46221 if (mod3 === 3) {
46222 var pow = this.m.add(new BN(1)).ishrn(2);
46223 var r = this.pow(a, pow);
46224 return r;
46225 }
46226
46227 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
46228 //
46229 // Find Q and S, that Q * 2 ^ S = (P - 1)
46230 var q = this.m.subn(1);
46231 var s = 0;
46232 while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
46233 s++;
46234 q.ishrn(1);
46235 }
46236 assert(q.cmpn(0) !== 0);
46237
46238 var one = new BN(1).toRed(this);
46239 var nOne = one.redNeg();
46240
46241 // Find quadratic non-residue
46242 // NOTE: Max is such because of generalized Riemann hypothesis.
46243 var lpow = this.m.subn(1).ishrn(1);
46244 var z = this.m.bitLength();
46245 z = new BN(2 * z * z).toRed(this);
46246 while (this.pow(z, lpow).cmp(nOne) !== 0)
46247 z.redIAdd(nOne);
46248
46249 var c = this.pow(z, q);
46250 var r = this.pow(a, q.addn(1).ishrn(1));
46251 var t = this.pow(a, q);
46252 var m = s;
46253 while (t.cmp(one) !== 0) {
46254 var tmp = t;
46255 for (var i = 0; tmp.cmp(one) !== 0; i++)
46256 tmp = tmp.redSqr();
46257 assert(i < m);
46258 var b = this.pow(c, new BN(1).ishln(m - i - 1));
46259
46260 r = r.redMul(b);
46261 c = b.redSqr();
46262 t = t.redMul(c);
46263 m = i;
46264 }
46265
46266 return r;
46267};
46268
46269Red.prototype.invm = function invm(a) {
46270 var inv = a._invmp(this.m);
46271 if (inv.sign) {
46272 inv.sign = false;
46273 return this.imod(inv).redNeg();
46274 } else {
46275 return this.imod(inv);
46276 }
46277};
46278
46279Red.prototype.pow = function pow(a, num) {
46280 var w = [];
46281
46282 if (num.cmpn(0) === 0)
46283 return new BN(1);
46284
46285 var q = num.clone();
46286
46287 while (q.cmpn(0) !== 0) {
46288 w.push(q.andln(1));
46289 q.ishrn(1);
46290 }
46291
46292 // Skip leading zeroes
46293 var res = a;
46294 for (var i = 0; i < w.length; i++, res = this.sqr(res))
46295 if (w[i] !== 0)
46296 break;
46297
46298 if (++i < w.length) {
46299 for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
46300 if (w[i] === 0)
46301 continue;
46302 res = this.mul(res, q);
46303 }
46304 }
46305
46306 return res;
46307};
46308
46309Red.prototype.convertTo = function convertTo(num) {
46310 var r = num.mod(this.m);
46311 if (r === num)
46312 return r.clone();
46313 else
46314 return r;
46315};
46316
46317Red.prototype.convertFrom = function convertFrom(num) {
46318 var res = num.clone();
46319 res.red = null;
46320 return res;
46321};
46322
46323//
46324// Montgomery method engine
46325//
46326
46327BN.mont = function mont(num) {
46328 return new Mont(num);
46329};
46330
46331function Mont(m) {
46332 Red.call(this, m);
46333
46334 this.shift = this.m.bitLength();
46335 if (this.shift % 26 !== 0)
46336 this.shift += 26 - (this.shift % 26);
46337 this.r = new BN(1).ishln(this.shift);
46338 this.r2 = this.imod(this.r.sqr());
46339 this.rinv = this.r._invmp(this.m);
46340
46341 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
46342 this.minv.sign = true;
46343 this.minv = this.minv.mod(this.r);
46344}
46345inherits(Mont, Red);
46346
46347Mont.prototype.convertTo = function convertTo(num) {
46348 return this.imod(num.shln(this.shift));
46349};
46350
46351Mont.prototype.convertFrom = function convertFrom(num) {
46352 var r = this.imod(num.mul(this.rinv));
46353 r.red = null;
46354 return r;
46355};
46356
46357Mont.prototype.imul = function imul(a, b) {
46358 if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
46359 a.words[0] = 0;
46360 a.length = 1;
46361 return a;
46362 }
46363
46364 var t = a.imul(b);
46365 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
46366 var u = t.isub(c).ishrn(this.shift);
46367 var res = u;
46368 if (u.cmp(this.m) >= 0)
46369 res = u.isub(this.m);
46370 else if (u.cmpn(0) < 0)
46371 res = u.iadd(this.m);
46372
46373 return res._forceRed(this);
46374};
46375
46376Mont.prototype.mul = function mul(a, b) {
46377 if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
46378 return new BN(0)._forceRed(this);
46379
46380 var t = a.mul(b);
46381 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
46382 var u = t.isub(c).ishrn(this.shift);
46383 var res = u;
46384 if (u.cmp(this.m) >= 0)
46385 res = u.isub(this.m);
46386 else if (u.cmpn(0) < 0)
46387 res = u.iadd(this.m);
46388
46389 return res._forceRed(this);
46390};
46391
46392Mont.prototype.invm = function invm(a) {
46393 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
46394 var res = this.imod(a._invmp(this.m).mul(this.r2));
46395 return res._forceRed(this);
46396};
46397
46398})(typeof module === 'undefined' || module, this);
46399}, {}],282: [function (exports, require, module, global) {'use strict';
46400
46401var curve = require('../curve');
46402var elliptic = require('../../elliptic');
46403var bn = require('bn.js');
46404var inherits = require('inherits');
46405var Base = curve.base;
46406
46407var assert = elliptic.utils.assert;
46408
46409function ShortCurve(conf) {
46410 Base.call(this, 'short', conf);
46411
46412 this.a = new bn(conf.a, 16).toRed(this.red);
46413 this.b = new bn(conf.b, 16).toRed(this.red);
46414 this.tinv = this.two.redInvm();
46415
46416 this.zeroA = this.a.fromRed().cmpn(0) === 0;
46417 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
46418
46419 // If the curve is endomorphic, precalculate beta and lambda
46420 this.endo = this._getEndomorphism(conf);
46421 this._endoWnafT1 = new Array(4);
46422 this._endoWnafT2 = new Array(4);
46423}
46424inherits(ShortCurve, Base);
46425module.exports = ShortCurve;
46426
46427ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
46428 // No efficient endomorphism
46429 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
46430 return;
46431
46432 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
46433 var beta;
46434 var lambda;
46435 if (conf.beta) {
46436 beta = new bn(conf.beta, 16).toRed(this.red);
46437 } else {
46438 var betas = this._getEndoRoots(this.p);
46439 // Choose the smallest beta
46440 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
46441 beta = beta.toRed(this.red);
46442 }
46443 if (conf.lambda) {
46444 lambda = new bn(conf.lambda, 16);
46445 } else {
46446 // Choose the lambda that is matching selected beta
46447 var lambdas = this._getEndoRoots(this.n);
46448 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
46449 lambda = lambdas[0];
46450 } else {
46451 lambda = lambdas[1];
46452 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
46453 }
46454 }
46455
46456 // Get basis vectors, used for balanced length-two representation
46457 var basis;
46458 if (conf.basis) {
46459 basis = conf.basis.map(function(vec) {
46460 return {
46461 a: new bn(vec.a, 16),
46462 b: new bn(vec.b, 16)
46463 };
46464 });
46465 } else {
46466 basis = this._getEndoBasis(lambda);
46467 }
46468
46469 return {
46470 beta: beta,
46471 lambda: lambda,
46472 basis: basis
46473 };
46474};
46475
46476ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
46477 // Find roots of for x^2 + x + 1 in F
46478 // Root = (-1 +- Sqrt(-3)) / 2
46479 //
46480 var red = num === this.p ? this.red : bn.mont(num);
46481 var tinv = new bn(2).toRed(red).redInvm();
46482 var ntinv = tinv.redNeg();
46483
46484 var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
46485
46486 var l1 = ntinv.redAdd(s).fromRed();
46487 var l2 = ntinv.redSub(s).fromRed();
46488 return [ l1, l2 ];
46489};
46490
46491ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
46492 // aprxSqrt >= sqrt(this.n)
46493 var aprxSqrt = this.n.shrn(Math.floor(this.n.bitLength() / 2));
46494
46495 // 3.74
46496 // Run EGCD, until r(L + 1) < aprxSqrt
46497 var u = lambda;
46498 var v = this.n.clone();
46499 var x1 = new bn(1);
46500 var y1 = new bn(0);
46501 var x2 = new bn(0);
46502 var y2 = new bn(1);
46503
46504 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
46505 var a0;
46506 var b0;
46507 // First vector
46508 var a1;
46509 var b1;
46510 // Second vector
46511 var a2;
46512 var b2;
46513
46514 var prevR;
46515 var i = 0;
46516 var r;
46517 var x;
46518 while (u.cmpn(0) !== 0) {
46519 var q = v.div(u);
46520 r = v.sub(q.mul(u));
46521 x = x2.sub(q.mul(x1));
46522 var y = y2.sub(q.mul(y1));
46523
46524 if (!a1 && r.cmp(aprxSqrt) < 0) {
46525 a0 = prevR.neg();
46526 b0 = x1;
46527 a1 = r.neg();
46528 b1 = x;
46529 } else if (a1 && ++i === 2) {
46530 break;
46531 }
46532 prevR = r;
46533
46534 v = u;
46535 u = r;
46536 x2 = x1;
46537 x1 = x;
46538 y2 = y1;
46539 y1 = y;
46540 }
46541 a2 = r.neg();
46542 b2 = x;
46543
46544 var len1 = a1.sqr().add(b1.sqr());
46545 var len2 = a2.sqr().add(b2.sqr());
46546 if (len2.cmp(len1) >= 0) {
46547 a2 = a0;
46548 b2 = b0;
46549 }
46550
46551 // Normalize signs
46552 if (a1.sign) {
46553 a1 = a1.neg();
46554 b1 = b1.neg();
46555 }
46556 if (a2.sign) {
46557 a2 = a2.neg();
46558 b2 = b2.neg();
46559 }
46560
46561 return [
46562 { a: a1, b: b1 },
46563 { a: a2, b: b2 }
46564 ];
46565};
46566
46567ShortCurve.prototype._endoSplit = function _endoSplit(k) {
46568 var basis = this.endo.basis;
46569 var v1 = basis[0];
46570 var v2 = basis[1];
46571
46572 var c1 = v2.b.mul(k).divRound(this.n);
46573 var c2 = v1.b.neg().mul(k).divRound(this.n);
46574
46575 var p1 = c1.mul(v1.a);
46576 var p2 = c2.mul(v2.a);
46577 var q1 = c1.mul(v1.b);
46578 var q2 = c2.mul(v2.b);
46579
46580 // Calculate answer
46581 var k1 = k.sub(p1).sub(p2);
46582 var k2 = q1.add(q2).neg();
46583 return { k1: k1, k2: k2 };
46584};
46585
46586ShortCurve.prototype.pointFromX = function pointFromX(odd, x) {
46587 x = new bn(x, 16);
46588 if (!x.red)
46589 x = x.toRed(this.red);
46590
46591 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
46592 var y = y2.redSqrt();
46593
46594 // XXX Is there any way to tell if the number is odd without converting it
46595 // to non-red form?
46596 var isOdd = y.fromRed().isOdd();
46597 if (odd && !isOdd || !odd && isOdd)
46598 y = y.redNeg();
46599
46600 return this.point(x, y);
46601};
46602
46603ShortCurve.prototype.validate = function validate(point) {
46604 if (point.inf)
46605 return true;
46606
46607 var x = point.x;
46608 var y = point.y;
46609
46610 var ax = this.a.redMul(x);
46611 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
46612 return y.redSqr().redISub(rhs).cmpn(0) === 0;
46613};
46614
46615ShortCurve.prototype._endoWnafMulAdd =
46616 function _endoWnafMulAdd(points, coeffs) {
46617 var npoints = this._endoWnafT1;
46618 var ncoeffs = this._endoWnafT2;
46619 for (var i = 0; i < points.length; i++) {
46620 var split = this._endoSplit(coeffs[i]);
46621 var p = points[i];
46622 var beta = p._getBeta();
46623
46624 if (split.k1.sign) {
46625 split.k1.sign = !split.k1.sign;
46626 p = p.neg(true);
46627 }
46628 if (split.k2.sign) {
46629 split.k2.sign = !split.k2.sign;
46630 beta = beta.neg(true);
46631 }
46632
46633 npoints[i * 2] = p;
46634 npoints[i * 2 + 1] = beta;
46635 ncoeffs[i * 2] = split.k1;
46636 ncoeffs[i * 2 + 1] = split.k2;
46637 }
46638 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2);
46639
46640 // Clean-up references to points and coefficients
46641 for (var j = 0; j < i * 2; j++) {
46642 npoints[j] = null;
46643 ncoeffs[j] = null;
46644 }
46645 return res;
46646};
46647
46648function Point(curve, x, y, isRed) {
46649 Base.BasePoint.call(this, curve, 'affine');
46650 if (x === null && y === null) {
46651 this.x = null;
46652 this.y = null;
46653 this.inf = true;
46654 } else {
46655 this.x = new bn(x, 16);
46656 this.y = new bn(y, 16);
46657 // Force redgomery representation when loading from JSON
46658 if (isRed) {
46659 this.x.forceRed(this.curve.red);
46660 this.y.forceRed(this.curve.red);
46661 }
46662 if (!this.x.red)
46663 this.x = this.x.toRed(this.curve.red);
46664 if (!this.y.red)
46665 this.y = this.y.toRed(this.curve.red);
46666 this.inf = false;
46667 }
46668}
46669inherits(Point, Base.BasePoint);
46670
46671ShortCurve.prototype.point = function point(x, y, isRed) {
46672 return new Point(this, x, y, isRed);
46673};
46674
46675ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
46676 return Point.fromJSON(this, obj, red);
46677};
46678
46679Point.prototype._getBeta = function _getBeta() {
46680 if (!this.curve.endo)
46681 return;
46682
46683 var pre = this.precomputed;
46684 if (pre && pre.beta)
46685 return pre.beta;
46686
46687 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
46688 if (pre) {
46689 var curve = this.curve;
46690 var endoMul = function(p) {
46691 return curve.point(p.x.redMul(curve.endo.beta), p.y);
46692 };
46693 pre.beta = beta;
46694 beta.precomputed = {
46695 beta: null,
46696 naf: pre.naf && {
46697 wnd: pre.naf.wnd,
46698 points: pre.naf.points.map(endoMul)
46699 },
46700 doubles: pre.doubles && {
46701 step: pre.doubles.step,
46702 points: pre.doubles.points.map(endoMul)
46703 }
46704 };
46705 }
46706 return beta;
46707};
46708
46709Point.prototype.toJSON = function toJSON() {
46710 if (!this.precomputed)
46711 return [ this.x, this.y ];
46712
46713 return [ this.x, this.y, this.precomputed && {
46714 doubles: this.precomputed.doubles && {
46715 step: this.precomputed.doubles.step,
46716 points: this.precomputed.doubles.points.slice(1)
46717 },
46718 naf: this.precomputed.naf && {
46719 wnd: this.precomputed.naf.wnd,
46720 points: this.precomputed.naf.points.slice(1)
46721 }
46722 } ];
46723};
46724
46725Point.fromJSON = function fromJSON(curve, obj, red) {
46726 if (typeof obj === 'string')
46727 obj = JSON.parse(obj);
46728 var res = curve.point(obj[0], obj[1], red);
46729 if (!obj[2])
46730 return res;
46731
46732 function obj2point(obj) {
46733 return curve.point(obj[0], obj[1], red);
46734 }
46735
46736 var pre = obj[2];
46737 res.precomputed = {
46738 beta: null,
46739 doubles: pre.doubles && {
46740 step: pre.doubles.step,
46741 points: [ res ].concat(pre.doubles.points.map(obj2point))
46742 },
46743 naf: pre.naf && {
46744 wnd: pre.naf.wnd,
46745 points: [ res ].concat(pre.naf.points.map(obj2point))
46746 }
46747 };
46748 return res;
46749};
46750
46751Point.prototype.inspect = function inspect() {
46752 if (this.isInfinity())
46753 return '<EC Point Infinity>';
46754 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
46755 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
46756};
46757
46758Point.prototype.isInfinity = function isInfinity() {
46759 return this.inf;
46760};
46761
46762Point.prototype.add = function add(p) {
46763 // O + P = P
46764 if (this.inf)
46765 return p;
46766
46767 // P + O = P
46768 if (p.inf)
46769 return this;
46770
46771 // P + P = 2P
46772 if (this.eq(p))
46773 return this.dbl();
46774
46775 // P + (-P) = O
46776 if (this.neg().eq(p))
46777 return this.curve.point(null, null);
46778
46779 // P + Q = O
46780 if (this.x.cmp(p.x) === 0)
46781 return this.curve.point(null, null);
46782
46783 var c = this.y.redSub(p.y);
46784 if (c.cmpn(0) !== 0)
46785 c = c.redMul(this.x.redSub(p.x).redInvm());
46786 var nx = c.redSqr().redISub(this.x).redISub(p.x);
46787 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
46788 return this.curve.point(nx, ny);
46789};
46790
46791Point.prototype.dbl = function dbl() {
46792 if (this.inf)
46793 return this;
46794
46795 // 2P = O
46796 var ys1 = this.y.redAdd(this.y);
46797 if (ys1.cmpn(0) === 0)
46798 return this.curve.point(null, null);
46799
46800 var a = this.curve.a;
46801
46802 var x2 = this.x.redSqr();
46803 var dyinv = ys1.redInvm();
46804 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
46805
46806 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
46807 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
46808 return this.curve.point(nx, ny);
46809};
46810
46811Point.prototype.getX = function getX() {
46812 return this.x.fromRed();
46813};
46814
46815Point.prototype.getY = function getY() {
46816 return this.y.fromRed();
46817};
46818
46819Point.prototype.mul = function mul(k) {
46820 k = new bn(k, 16);
46821
46822 if (this._hasDoubles(k))
46823 return this.curve._fixedNafMul(this, k);
46824 else if (this.curve.endo)
46825 return this.curve._endoWnafMulAdd([ this ], [ k ]);
46826 else
46827 return this.curve._wnafMul(this, k);
46828};
46829
46830Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
46831 var points = [ this, p2 ];
46832 var coeffs = [ k1, k2 ];
46833 if (this.curve.endo)
46834 return this.curve._endoWnafMulAdd(points, coeffs);
46835 else
46836 return this.curve._wnafMulAdd(1, points, coeffs, 2);
46837};
46838
46839Point.prototype.eq = function eq(p) {
46840 return this === p ||
46841 this.inf === p.inf &&
46842 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
46843};
46844
46845Point.prototype.neg = function neg(_precompute) {
46846 if (this.inf)
46847 return this;
46848
46849 var res = this.curve.point(this.x, this.y.redNeg());
46850 if (_precompute && this.precomputed) {
46851 var pre = this.precomputed;
46852 var negate = function(p) {
46853 return p.neg();
46854 };
46855 res.precomputed = {
46856 naf: pre.naf && {
46857 wnd: pre.naf.wnd,
46858 points: pre.naf.points.map(negate)
46859 },
46860 doubles: pre.doubles && {
46861 step: pre.doubles.step,
46862 points: pre.doubles.points.map(negate)
46863 }
46864 };
46865 }
46866 return res;
46867};
46868
46869Point.prototype.toJ = function toJ() {
46870 if (this.inf)
46871 return this.curve.jpoint(null, null, null);
46872
46873 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
46874 return res;
46875};
46876
46877function JPoint(curve, x, y, z) {
46878 Base.BasePoint.call(this, curve, 'jacobian');
46879 if (x === null && y === null && z === null) {
46880 this.x = this.curve.one;
46881 this.y = this.curve.one;
46882 this.z = new bn(0);
46883 } else {
46884 this.x = new bn(x, 16);
46885 this.y = new bn(y, 16);
46886 this.z = new bn(z, 16);
46887 }
46888 if (!this.x.red)
46889 this.x = this.x.toRed(this.curve.red);
46890 if (!this.y.red)
46891 this.y = this.y.toRed(this.curve.red);
46892 if (!this.z.red)
46893 this.z = this.z.toRed(this.curve.red);
46894
46895 this.zOne = this.z === this.curve.one;
46896}
46897inherits(JPoint, Base.BasePoint);
46898
46899ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
46900 return new JPoint(this, x, y, z);
46901};
46902
46903JPoint.prototype.toP = function toP() {
46904 if (this.isInfinity())
46905 return this.curve.point(null, null);
46906
46907 var zinv = this.z.redInvm();
46908 var zinv2 = zinv.redSqr();
46909 var ax = this.x.redMul(zinv2);
46910 var ay = this.y.redMul(zinv2).redMul(zinv);
46911
46912 return this.curve.point(ax, ay);
46913};
46914
46915JPoint.prototype.neg = function neg() {
46916 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
46917};
46918
46919JPoint.prototype.add = function add(p) {
46920 // O + P = P
46921 if (this.isInfinity())
46922 return p;
46923
46924 // P + O = P
46925 if (p.isInfinity())
46926 return this;
46927
46928 // 12M + 4S + 7A
46929 var pz2 = p.z.redSqr();
46930 var z2 = this.z.redSqr();
46931 var u1 = this.x.redMul(pz2);
46932 var u2 = p.x.redMul(z2);
46933 var s1 = this.y.redMul(pz2.redMul(p.z));
46934 var s2 = p.y.redMul(z2.redMul(this.z));
46935
46936 var h = u1.redSub(u2);
46937 var r = s1.redSub(s2);
46938 if (h.cmpn(0) === 0) {
46939 if (r.cmpn(0) !== 0)
46940 return this.curve.jpoint(null, null, null);
46941 else
46942 return this.dbl();
46943 }
46944
46945 var h2 = h.redSqr();
46946 var h3 = h2.redMul(h);
46947 var v = u1.redMul(h2);
46948
46949 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
46950 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
46951 var nz = this.z.redMul(p.z).redMul(h);
46952
46953 return this.curve.jpoint(nx, ny, nz);
46954};
46955
46956JPoint.prototype.mixedAdd = function mixedAdd(p) {
46957 // O + P = P
46958 if (this.isInfinity())
46959 return p.toJ();
46960
46961 // P + O = P
46962 if (p.isInfinity())
46963 return this;
46964
46965 // 8M + 3S + 7A
46966 var z2 = this.z.redSqr();
46967 var u1 = this.x;
46968 var u2 = p.x.redMul(z2);
46969 var s1 = this.y;
46970 var s2 = p.y.redMul(z2).redMul(this.z);
46971
46972 var h = u1.redSub(u2);
46973 var r = s1.redSub(s2);
46974 if (h.cmpn(0) === 0) {
46975 if (r.cmpn(0) !== 0)
46976 return this.curve.jpoint(null, null, null);
46977 else
46978 return this.dbl();
46979 }
46980
46981 var h2 = h.redSqr();
46982 var h3 = h2.redMul(h);
46983 var v = u1.redMul(h2);
46984
46985 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
46986 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
46987 var nz = this.z.redMul(h);
46988
46989 return this.curve.jpoint(nx, ny, nz);
46990};
46991
46992JPoint.prototype.dblp = function dblp(pow) {
46993 if (pow === 0)
46994 return this;
46995 if (this.isInfinity())
46996 return this;
46997 if (!pow)
46998 return this.dbl();
46999
47000 if (this.curve.zeroA || this.curve.threeA) {
47001 var r = this;
47002 for (var i = 0; i < pow; i++)
47003 r = r.dbl();
47004 return r;
47005 }
47006
47007 // 1M + 2S + 1A + N * (4S + 5M + 8A)
47008 // N = 1 => 6M + 6S + 9A
47009 var a = this.curve.a;
47010 var tinv = this.curve.tinv;
47011
47012 var jx = this.x;
47013 var jy = this.y;
47014 var jz = this.z;
47015 var jz4 = jz.redSqr().redSqr();
47016
47017 // Reuse results
47018 var jyd = jy.redAdd(jy);
47019 for (var i = 0; i < pow; i++) {
47020 var jx2 = jx.redSqr();
47021 var jyd2 = jyd.redSqr();
47022 var jyd4 = jyd2.redSqr();
47023 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
47024
47025 var t1 = jx.redMul(jyd2);
47026 var nx = c.redSqr().redISub(t1.redAdd(t1));
47027 var t2 = t1.redISub(nx);
47028 var dny = c.redMul(t2);
47029 dny = dny.redIAdd(dny).redISub(jyd4);
47030 var nz = jyd.redMul(jz);
47031 if (i + 1 < pow)
47032 jz4 = jz4.redMul(jyd4);
47033
47034 jx = nx;
47035 jz = nz;
47036 jyd = dny;
47037 }
47038
47039 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
47040};
47041
47042JPoint.prototype.dbl = function dbl() {
47043 if (this.isInfinity())
47044 return this;
47045
47046 if (this.curve.zeroA)
47047 return this._zeroDbl();
47048 else if (this.curve.threeA)
47049 return this._threeDbl();
47050 else
47051 return this._dbl();
47052};
47053
47054JPoint.prototype._zeroDbl = function _zeroDbl() {
47055 var nx;
47056 var ny;
47057 var nz;
47058 // Z = 1
47059 if (this.zOne) {
47060 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
47061 // #doubling-mdbl-2007-bl
47062 // 1M + 5S + 14A
47063
47064 // XX = X1^2
47065 var xx = this.x.redSqr();
47066 // YY = Y1^2
47067 var yy = this.y.redSqr();
47068 // YYYY = YY^2
47069 var yyyy = yy.redSqr();
47070 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
47071 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
47072 s = s.redIAdd(s);
47073 // M = 3 * XX + a; a = 0
47074 var m = xx.redAdd(xx).redIAdd(xx);
47075 // T = M ^ 2 - 2*S
47076 var t = m.redSqr().redISub(s).redISub(s);
47077
47078 // 8 * YYYY
47079 var yyyy8 = yyyy.redIAdd(yyyy);
47080 yyyy8 = yyyy8.redIAdd(yyyy8);
47081 yyyy8 = yyyy8.redIAdd(yyyy8);
47082
47083 // X3 = T
47084 nx = t;
47085 // Y3 = M * (S - T) - 8 * YYYY
47086 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
47087 // Z3 = 2*Y1
47088 nz = this.y.redAdd(this.y);
47089 } else {
47090 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
47091 // #doubling-dbl-2009-l
47092 // 2M + 5S + 13A
47093
47094 // A = X1^2
47095 var a = this.x.redSqr();
47096 // B = Y1^2
47097 var b = this.y.redSqr();
47098 // C = B^2
47099 var c = b.redSqr();
47100 // D = 2 * ((X1 + B)^2 - A - C)
47101 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
47102 d = d.redIAdd(d);
47103 // E = 3 * A
47104 var e = a.redAdd(a).redIAdd(a);
47105 // F = E^2
47106 var f = e.redSqr();
47107
47108 // 8 * C
47109 var c8 = c.redIAdd(c);
47110 c8 = c8.redIAdd(c8);
47111 c8 = c8.redIAdd(c8);
47112
47113 // X3 = F - 2 * D
47114 nx = f.redISub(d).redISub(d);
47115 // Y3 = E * (D - X3) - 8 * C
47116 ny = e.redMul(d.redISub(nx)).redISub(c8);
47117 // Z3 = 2 * Y1 * Z1
47118 nz = this.y.redMul(this.z);
47119 nz = nz.redIAdd(nz);
47120 }
47121
47122 return this.curve.jpoint(nx, ny, nz);
47123};
47124
47125JPoint.prototype._threeDbl = function _threeDbl() {
47126 var nx;
47127 var ny;
47128 var nz;
47129 // Z = 1
47130 if (this.zOne) {
47131 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
47132 // #doubling-mdbl-2007-bl
47133 // 1M + 5S + 15A
47134
47135 // XX = X1^2
47136 var xx = this.x.redSqr();
47137 // YY = Y1^2
47138 var yy = this.y.redSqr();
47139 // YYYY = YY^2
47140 var yyyy = yy.redSqr();
47141 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
47142 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
47143 s = s.redIAdd(s);
47144 // M = 3 * XX + a
47145 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
47146 // T = M^2 - 2 * S
47147 var t = m.redSqr().redISub(s).redISub(s);
47148 // X3 = T
47149 nx = t;
47150 // Y3 = M * (S - T) - 8 * YYYY
47151 var yyyy8 = yyyy.redIAdd(yyyy);
47152 yyyy8 = yyyy8.redIAdd(yyyy8);
47153 yyyy8 = yyyy8.redIAdd(yyyy8);
47154 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
47155 // Z3 = 2 * Y1
47156 nz = this.y.redAdd(this.y);
47157 } else {
47158 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
47159 // 3M + 5S
47160
47161 // delta = Z1^2
47162 var delta = this.z.redSqr();
47163 // gamma = Y1^2
47164 var gamma = this.y.redSqr();
47165 // beta = X1 * gamma
47166 var beta = this.x.redMul(gamma);
47167 // alpha = 3 * (X1 - delta) * (X1 + delta)
47168 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
47169 alpha = alpha.redAdd(alpha).redIAdd(alpha);
47170 // X3 = alpha^2 - 8 * beta
47171 var beta4 = beta.redIAdd(beta);
47172 beta4 = beta4.redIAdd(beta4);
47173 var beta8 = beta4.redAdd(beta4);
47174 nx = alpha.redSqr().redISub(beta8);
47175 // Z3 = (Y1 + Z1)^2 - gamma - delta
47176 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
47177 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
47178 var ggamma8 = gamma.redSqr();
47179 ggamma8 = ggamma8.redIAdd(ggamma8);
47180 ggamma8 = ggamma8.redIAdd(ggamma8);
47181 ggamma8 = ggamma8.redIAdd(ggamma8);
47182 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
47183 }
47184
47185 return this.curve.jpoint(nx, ny, nz);
47186};
47187
47188JPoint.prototype._dbl = function _dbl() {
47189 var a = this.curve.a;
47190
47191 // 4M + 6S + 10A
47192 var jx = this.x;
47193 var jy = this.y;
47194 var jz = this.z;
47195 var jz4 = jz.redSqr().redSqr();
47196
47197 var jx2 = jx.redSqr();
47198 var jy2 = jy.redSqr();
47199
47200 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
47201
47202 var jxd4 = jx.redAdd(jx);
47203 jxd4 = jxd4.redIAdd(jxd4);
47204 var t1 = jxd4.redMul(jy2);
47205 var nx = c.redSqr().redISub(t1.redAdd(t1));
47206 var t2 = t1.redISub(nx);
47207
47208 var jyd8 = jy2.redSqr();
47209 jyd8 = jyd8.redIAdd(jyd8);
47210 jyd8 = jyd8.redIAdd(jyd8);
47211 jyd8 = jyd8.redIAdd(jyd8);
47212 var ny = c.redMul(t2).redISub(jyd8);
47213 var nz = jy.redAdd(jy).redMul(jz);
47214
47215 return this.curve.jpoint(nx, ny, nz);
47216};
47217
47218JPoint.prototype.trpl = function trpl() {
47219 if (!this.curve.zeroA)
47220 return this.dbl().add(this);
47221
47222 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
47223 // 5M + 10S + ...
47224
47225 // XX = X1^2
47226 var xx = this.x.redSqr();
47227 // YY = Y1^2
47228 var yy = this.y.redSqr();
47229 // ZZ = Z1^2
47230 var zz = this.z.redSqr();
47231 // YYYY = YY^2
47232 var yyyy = yy.redSqr();
47233 // M = 3 * XX + a * ZZ2; a = 0
47234 var m = xx.redAdd(xx).redIAdd(xx);
47235 // MM = M^2
47236 var mm = m.redSqr();
47237 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
47238 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
47239 e = e.redIAdd(e);
47240 e = e.redAdd(e).redIAdd(e);
47241 e = e.redISub(mm);
47242 // EE = E^2
47243 var ee = e.redSqr();
47244 // T = 16*YYYY
47245 var t = yyyy.redIAdd(yyyy);
47246 t = t.redIAdd(t);
47247 t = t.redIAdd(t);
47248 t = t.redIAdd(t);
47249 // U = (M + E)^2 - MM - EE - T
47250 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
47251 // X3 = 4 * (X1 * EE - 4 * YY * U)
47252 var yyu4 = yy.redMul(u);
47253 yyu4 = yyu4.redIAdd(yyu4);
47254 yyu4 = yyu4.redIAdd(yyu4);
47255 var nx = this.x.redMul(ee).redISub(yyu4);
47256 nx = nx.redIAdd(nx);
47257 nx = nx.redIAdd(nx);
47258 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
47259 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
47260 ny = ny.redIAdd(ny);
47261 ny = ny.redIAdd(ny);
47262 ny = ny.redIAdd(ny);
47263 // Z3 = (Z1 + E)^2 - ZZ - EE
47264 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
47265
47266 return this.curve.jpoint(nx, ny, nz);
47267};
47268
47269JPoint.prototype.mul = function mul(k, kbase) {
47270 k = new bn(k, kbase);
47271
47272 return this.curve._wnafMul(this, k);
47273};
47274
47275JPoint.prototype.eq = function eq(p) {
47276 if (p.type === 'affine')
47277 return this.eq(p.toJ());
47278
47279 if (this === p)
47280 return true;
47281
47282 // x1 * z2^2 == x2 * z1^2
47283 var z2 = this.z.redSqr();
47284 var pz2 = p.z.redSqr();
47285 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
47286 return false;
47287
47288 // y1 * z2^3 == y2 * z1^3
47289 var z3 = z2.redMul(this.z);
47290 var pz3 = pz2.redMul(p.z);
47291 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
47292};
47293
47294JPoint.prototype.inspect = function inspect() {
47295 if (this.isInfinity())
47296 return '<EC JPoint Infinity>';
47297 return '<EC JPoint x: ' + this.x.toString(16, 2) +
47298 ' y: ' + this.y.toString(16, 2) +
47299 ' z: ' + this.z.toString(16, 2) + '>';
47300};
47301
47302JPoint.prototype.isInfinity = function isInfinity() {
47303 // XXX This code assumes that zero is always zero in red
47304 return this.z.cmpn(0) === 0;
47305};
47306}, {"../curve":279,"../../elliptic":268,"bn.js":281,"inherits":149}],283: [function (exports, require, module, global) {'use strict';
47307
47308var curve = require('../curve');
47309var bn = require('bn.js');
47310var inherits = require('inherits');
47311var Base = curve.base;
47312
47313function MontCurve(conf) {
47314 Base.call(this, 'mont', conf);
47315
47316 this.a = new bn(conf.a, 16).toRed(this.red);
47317 this.b = new bn(conf.b, 16).toRed(this.red);
47318 this.i4 = new bn(4).toRed(this.red).redInvm();
47319 this.two = new bn(2).toRed(this.red);
47320 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
47321}
47322inherits(MontCurve, Base);
47323module.exports = MontCurve;
47324
47325MontCurve.prototype.validate = function validate(point) {
47326 var x = point.normalize().x;
47327 var x2 = x.redSqr();
47328 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
47329 var y = rhs.redSqrt();
47330
47331 return y.redSqr().cmp(rhs) === 0;
47332};
47333
47334function Point(curve, x, z) {
47335 Base.BasePoint.call(this, curve, 'projective');
47336 if (x === null && z === null) {
47337 this.x = this.curve.one;
47338 this.z = this.curve.zero;
47339 } else {
47340 this.x = new bn(x, 16);
47341 this.z = new bn(z, 16);
47342 if (!this.x.red)
47343 this.x = this.x.toRed(this.curve.red);
47344 if (!this.z.red)
47345 this.z = this.z.toRed(this.curve.red);
47346 }
47347}
47348inherits(Point, Base.BasePoint);
47349
47350MontCurve.prototype.point = function point(x, z) {
47351 return new Point(this, x, z);
47352};
47353
47354MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
47355 return Point.fromJSON(this, obj);
47356};
47357
47358Point.prototype.precompute = function precompute() {
47359 // No-op
47360};
47361
47362Point.fromJSON = function fromJSON(curve, obj) {
47363 return new Point(curve, obj[0], obj[1] || curve.one);
47364};
47365
47366Point.prototype.inspect = function inspect() {
47367 if (this.isInfinity())
47368 return '<EC Point Infinity>';
47369 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
47370 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
47371};
47372
47373Point.prototype.isInfinity = function isInfinity() {
47374 // XXX This code assumes that zero is always zero in red
47375 return this.z.cmpn(0) === 0;
47376};
47377
47378Point.prototype.dbl = function dbl() {
47379 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
47380 // 2M + 2S + 4A
47381
47382 // A = X1 + Z1
47383 var a = this.x.redAdd(this.z);
47384 // AA = A^2
47385 var aa = a.redSqr();
47386 // B = X1 - Z1
47387 var b = this.x.redSub(this.z);
47388 // BB = B^2
47389 var bb = b.redSqr();
47390 // C = AA - BB
47391 var c = aa.redSub(bb);
47392 // X3 = AA * BB
47393 var nx = aa.redMul(bb);
47394 // Z3 = C * (BB + A24 * C)
47395 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
47396 return this.curve.point(nx, nz);
47397};
47398
47399Point.prototype.add = function add() {
47400 throw new Error('Not supported on Montgomery curve');
47401};
47402
47403Point.prototype.diffAdd = function diffAdd(p, diff) {
47404 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
47405 // 4M + 2S + 6A
47406
47407 // A = X2 + Z2
47408 var a = this.x.redAdd(this.z);
47409 // B = X2 - Z2
47410 var b = this.x.redSub(this.z);
47411 // C = X3 + Z3
47412 var c = p.x.redAdd(p.z);
47413 // D = X3 - Z3
47414 var d = p.x.redSub(p.z);
47415 // DA = D * A
47416 var da = d.redMul(a);
47417 // CB = C * B
47418 var cb = c.redMul(b);
47419 // X5 = Z1 * (DA + CB)^2
47420 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
47421 // Z5 = X1 * (DA - CB)^2
47422 var nz = diff.x.redMul(da.redISub(cb).redSqr());
47423 return this.curve.point(nx, nz);
47424};
47425
47426Point.prototype.mul = function mul(k) {
47427 var t = k.clone();
47428 var a = this; // (N / 2) * Q + Q
47429 var b = this.curve.point(null, null); // (N / 2) * Q
47430 var c = this; // Q
47431
47432 for (var bits = []; t.cmpn(0) !== 0; t.ishrn(1))
47433 bits.push(t.andln(1));
47434
47435 for (var i = bits.length - 1; i >= 0; i--) {
47436 if (bits[i] === 0) {
47437 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
47438 a = a.diffAdd(b, c);
47439 // N * Q = 2 * ((N / 2) * Q + Q))
47440 b = b.dbl();
47441 } else {
47442 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
47443 b = a.diffAdd(b, c);
47444 // N * Q + Q = 2 * ((N / 2) * Q + Q)
47445 a = a.dbl();
47446 }
47447 }
47448 return b;
47449};
47450
47451Point.prototype.mulAdd = function mulAdd() {
47452 throw new Error('Not supported on Montgomery curve');
47453};
47454
47455Point.prototype.normalize = function normalize() {
47456 this.x = this.x.redMul(this.z.redInvm());
47457 this.z = this.curve.one;
47458 return this;
47459};
47460
47461Point.prototype.getX = function getX() {
47462 // Normalize coordinates
47463 this.normalize();
47464
47465 return this.x.fromRed();
47466};
47467}, {"../curve":279,"bn.js":281,"inherits":149}],284: [function (exports, require, module, global) {'use strict';
47468
47469var curve = require('../curve');
47470var elliptic = require('../../elliptic');
47471var bn = require('bn.js');
47472var inherits = require('inherits');
47473var Base = curve.base;
47474
47475var assert = elliptic.utils.assert;
47476
47477function EdwardsCurve(conf) {
47478 // NOTE: Important as we are creating point in Base.call()
47479 this.twisted = (conf.a | 0) !== 1;
47480 this.mOneA = this.twisted && (conf.a | 0) === -1;
47481 this.extended = this.mOneA;
47482
47483 Base.call(this, 'edwards', conf);
47484
47485 this.a = new bn(conf.a, 16).mod(this.red.m).toRed(this.red);
47486 this.c = new bn(conf.c, 16).toRed(this.red);
47487 this.c2 = this.c.redSqr();
47488 this.d = new bn(conf.d, 16).toRed(this.red);
47489 this.dd = this.d.redAdd(this.d);
47490
47491 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
47492 this.oneC = (conf.c | 0) === 1;
47493}
47494inherits(EdwardsCurve, Base);
47495module.exports = EdwardsCurve;
47496
47497EdwardsCurve.prototype._mulA = function _mulA(num) {
47498 if (this.mOneA)
47499 return num.redNeg();
47500 else
47501 return this.a.redMul(num);
47502};
47503
47504EdwardsCurve.prototype._mulC = function _mulC(num) {
47505 if (this.oneC)
47506 return num;
47507 else
47508 return this.c.redMul(num);
47509};
47510
47511// Just for compatibility with Short curve
47512EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
47513 return this.point(x, y, z, t);
47514};
47515
47516EdwardsCurve.prototype.pointFromX = function pointFromX(odd, x) {
47517 x = new bn(x, 16);
47518 if (!x.red)
47519 x = x.toRed(this.red);
47520
47521 var x2 = x.redSqr();
47522 var rhs = this.c2.redSub(this.a.redMul(x2));
47523 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
47524
47525 var y = rhs.redMul(lhs.redInvm()).redSqrt();
47526 var isOdd = y.fromRed().isOdd();
47527 if (odd && !isOdd || !odd && isOdd)
47528 y = y.redNeg();
47529
47530 return this.point(x, y, curve.one);
47531};
47532
47533EdwardsCurve.prototype.validate = function validate(point) {
47534 if (point.isInfinity())
47535 return true;
47536
47537 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
47538 point.normalize();
47539
47540 var x2 = point.x.redSqr();
47541 var y2 = point.y.redSqr();
47542 var lhs = x2.redMul(this.a).redAdd(y2);
47543 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
47544
47545 return lhs.cmp(rhs) === 0;
47546};
47547
47548function Point(curve, x, y, z, t) {
47549 Base.BasePoint.call(this, curve, 'projective');
47550 if (x === null && y === null && z === null) {
47551 this.x = this.curve.zero;
47552 this.y = this.curve.one;
47553 this.z = this.curve.one;
47554 this.t = this.curve.zero;
47555 this.zOne = true;
47556 } else {
47557 this.x = new bn(x, 16);
47558 this.y = new bn(y, 16);
47559 this.z = z ? new bn(z, 16) : this.curve.one;
47560 this.t = t && new bn(t, 16);
47561 if (!this.x.red)
47562 this.x = this.x.toRed(this.curve.red);
47563 if (!this.y.red)
47564 this.y = this.y.toRed(this.curve.red);
47565 if (!this.z.red)
47566 this.z = this.z.toRed(this.curve.red);
47567 if (this.t && !this.t.red)
47568 this.t = this.t.toRed(this.curve.red);
47569 this.zOne = this.z === this.curve.one;
47570
47571 // Use extended coordinates
47572 if (this.curve.extended && !this.t) {
47573 this.t = this.x.redMul(this.y);
47574 if (!this.zOne)
47575 this.t = this.t.redMul(this.z.redInvm());
47576 }
47577 }
47578}
47579inherits(Point, Base.BasePoint);
47580
47581EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
47582 return Point.fromJSON(this, obj);
47583};
47584
47585EdwardsCurve.prototype.point = function point(x, y, z, t) {
47586 return new Point(this, x, y, z, t);
47587};
47588
47589Point.fromJSON = function fromJSON(curve, obj) {
47590 return new Point(curve, obj[0], obj[1], obj[2]);
47591};
47592
47593Point.prototype.inspect = function inspect() {
47594 if (this.isInfinity())
47595 return '<EC Point Infinity>';
47596 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
47597 ' y: ' + this.y.fromRed().toString(16, 2) +
47598 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
47599};
47600
47601Point.prototype.isInfinity = function isInfinity() {
47602 // XXX This code assumes that zero is always zero in red
47603 return this.x.cmpn(0) === 0 &&
47604 this.y.cmp(this.z) === 0;
47605};
47606
47607Point.prototype._extDbl = function _extDbl() {
47608 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
47609 // #doubling-dbl-2008-hwcd
47610 // 4M + 4S
47611
47612 // A = X1^2
47613 var a = this.x.redSqr();
47614 // B = Y1^2
47615 var b = this.y.redSqr();
47616 // C = 2 * Z1^2
47617 var c = this.z.redSqr();
47618 c = c.redIAdd(c);
47619 // D = a * A
47620 var d = this.curve._mulA(a);
47621 // E = (X1 + Y1)^2 - A - B
47622 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
47623 // G = D + B
47624 var g = d.redAdd(b);
47625 // F = G - C
47626 var f = g.redSub(c);
47627 // H = D - B
47628 var h = d.redSub(b);
47629 // X3 = E * F
47630 var nx = e.redMul(f);
47631 // Y3 = G * H
47632 var ny = g.redMul(h);
47633 // T3 = E * H
47634 var nt = e.redMul(h);
47635 // Z3 = F * G
47636 var nz = f.redMul(g);
47637 return this.curve.point(nx, ny, nz, nt);
47638};
47639
47640Point.prototype._projDbl = function _projDbl() {
47641 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
47642 // #doubling-dbl-2008-bbjlp
47643 // #doubling-dbl-2007-bl
47644 // and others
47645 // Generally 3M + 4S or 2M + 4S
47646
47647 // B = (X1 + Y1)^2
47648 var b = this.x.redAdd(this.y).redSqr();
47649 // C = X1^2
47650 var c = this.x.redSqr();
47651 // D = Y1^2
47652 var d = this.y.redSqr();
47653
47654 var nx;
47655 var ny;
47656 var nz;
47657 if (this.curve.twisted) {
47658 // E = a * C
47659 var e = this.curve._mulA(c);
47660 // F = E + D
47661 var f = e.redAdd(d);
47662 if (this.zOne) {
47663 // X3 = (B - C - D) * (F - 2)
47664 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
47665 // Y3 = F * (E - D)
47666 ny = f.redMul(e.redSub(d));
47667 // Z3 = F^2 - 2 * F
47668 nz = f.redSqr().redSub(f).redSub(f);
47669 } else {
47670 // H = Z1^2
47671 var h = this.z.redSqr();
47672 // J = F - 2 * H
47673 var j = f.redSub(h).redISub(h);
47674 // X3 = (B-C-D)*J
47675 nx = b.redSub(c).redISub(d).redMul(j);
47676 // Y3 = F * (E - D)
47677 ny = f.redMul(e.redSub(d));
47678 // Z3 = F * J
47679 nz = f.redMul(j);
47680 }
47681 } else {
47682 // E = C + D
47683 var e = c.redAdd(d);
47684 // H = (c * Z1)^2
47685 var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
47686 // J = E - 2 * H
47687 var j = e.redSub(h).redSub(h);
47688 // X3 = c * (B - E) * J
47689 nx = this.curve._mulC(b.redISub(e)).redMul(j);
47690 // Y3 = c * E * (C - D)
47691 ny = this.curve._mulC(e).redMul(c.redISub(d));
47692 // Z3 = E * J
47693 nz = e.redMul(j);
47694 }
47695 return this.curve.point(nx, ny, nz);
47696};
47697
47698Point.prototype.dbl = function dbl() {
47699 if (this.isInfinity())
47700 return this;
47701
47702 // Double in extended coordinates
47703 if (this.curve.extended)
47704 return this._extDbl();
47705 else
47706 return this._projDbl();
47707};
47708
47709Point.prototype._extAdd = function _extAdd(p) {
47710 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
47711 // #addition-add-2008-hwcd-3
47712 // 8M
47713
47714 // A = (Y1 - X1) * (Y2 - X2)
47715 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
47716 // B = (Y1 + X1) * (Y2 + X2)
47717 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
47718 // C = T1 * k * T2
47719 var c = this.t.redMul(this.curve.dd).redMul(p.t);
47720 // D = Z1 * 2 * Z2
47721 var d = this.z.redMul(p.z.redAdd(p.z));
47722 // E = B - A
47723 var e = b.redSub(a);
47724 // F = D - C
47725 var f = d.redSub(c);
47726 // G = D + C
47727 var g = d.redAdd(c);
47728 // H = B + A
47729 var h = b.redAdd(a);
47730 // X3 = E * F
47731 var nx = e.redMul(f);
47732 // Y3 = G * H
47733 var ny = g.redMul(h);
47734 // T3 = E * H
47735 var nt = e.redMul(h);
47736 // Z3 = F * G
47737 var nz = f.redMul(g);
47738 return this.curve.point(nx, ny, nz, nt);
47739};
47740
47741Point.prototype._projAdd = function _projAdd(p) {
47742 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
47743 // #addition-add-2008-bbjlp
47744 // #addition-add-2007-bl
47745 // 10M + 1S
47746
47747 // A = Z1 * Z2
47748 var a = this.z.redMul(p.z);
47749 // B = A^2
47750 var b = a.redSqr();
47751 // C = X1 * X2
47752 var c = this.x.redMul(p.x);
47753 // D = Y1 * Y2
47754 var d = this.y.redMul(p.y);
47755 // E = d * C * D
47756 var e = this.curve.d.redMul(c).redMul(d);
47757 // F = B - E
47758 var f = b.redSub(e);
47759 // G = B + E
47760 var g = b.redAdd(e);
47761 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
47762 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
47763 var nx = a.redMul(f).redMul(tmp);
47764 var ny;
47765 var nz;
47766 if (this.curve.twisted) {
47767 // Y3 = A * G * (D - a * C)
47768 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
47769 // Z3 = F * G
47770 nz = f.redMul(g);
47771 } else {
47772 // Y3 = A * G * (D - C)
47773 ny = a.redMul(g).redMul(d.redSub(c));
47774 // Z3 = c * F * G
47775 nz = this.curve._mulC(f).redMul(g);
47776 }
47777 return this.curve.point(nx, ny, nz);
47778};
47779
47780Point.prototype.add = function add(p) {
47781 if (this.isInfinity())
47782 return p;
47783 if (p.isInfinity())
47784 return this;
47785
47786 if (this.curve.extended)
47787 return this._extAdd(p);
47788 else
47789 return this._projAdd(p);
47790};
47791
47792Point.prototype.mul = function mul(k) {
47793 if (this._hasDoubles(k))
47794 return this.curve._fixedNafMul(this, k);
47795 else
47796 return this.curve._wnafMul(this, k);
47797};
47798
47799Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
47800 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2);
47801};
47802
47803Point.prototype.normalize = function normalize() {
47804 if (this.zOne)
47805 return this;
47806
47807 // Normalize coordinates
47808 var zi = this.z.redInvm();
47809 this.x = this.x.redMul(zi);
47810 this.y = this.y.redMul(zi);
47811 if (this.t)
47812 this.t = this.t.redMul(zi);
47813 this.z = this.curve.one;
47814 this.zOne = true;
47815 return this;
47816};
47817
47818Point.prototype.neg = function neg() {
47819 return this.curve.point(this.x.redNeg(),
47820 this.y,
47821 this.z,
47822 this.t && this.t.redNeg());
47823};
47824
47825Point.prototype.getX = function getX() {
47826 this.normalize();
47827 return this.x.fromRed();
47828};
47829
47830Point.prototype.getY = function getY() {
47831 this.normalize();
47832 return this.y.fromRed();
47833};
47834
47835// Compatibility with BaseCurve
47836Point.prototype.toP = Point.prototype.normalize;
47837Point.prototype.mixedAdd = Point.prototype.add;
47838}, {"../curve":279,"../../elliptic":268,"bn.js":281,"inherits":149}],285: [function (exports, require, module, global) {'use strict';
47839
47840var curves = exports;
47841
47842var hash = require('hash.js');
47843var elliptic = require('../elliptic');
47844
47845var assert = elliptic.utils.assert;
47846
47847function PresetCurve(options) {
47848 if (options.type === 'short')
47849 this.curve = new elliptic.curve.short(options);
47850 else if (options.type === 'edwards')
47851 this.curve = new elliptic.curve.edwards(options);
47852 else
47853 this.curve = new elliptic.curve.mont(options);
47854 this.g = this.curve.g;
47855 this.n = this.curve.n;
47856 this.hash = options.hash;
47857
47858 assert(this.g.validate(), 'Invalid curve');
47859 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
47860}
47861curves.PresetCurve = PresetCurve;
47862
47863function defineCurve(name, options) {
47864 Object.defineProperty(curves, name, {
47865 configurable: true,
47866 enumerable: true,
47867 get: function() {
47868 var curve = new PresetCurve(options);
47869 Object.defineProperty(curves, name, {
47870 configurable: true,
47871 enumerable: true,
47872 value: curve
47873 });
47874 return curve;
47875 }
47876 });
47877}
47878
47879defineCurve('p192', {
47880 type: 'short',
47881 prime: 'p192',
47882 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
47883 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
47884 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
47885 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
47886 hash: hash.sha256,
47887 gRed: false,
47888 g: [
47889 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
47890 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
47891 ]
47892});
47893
47894defineCurve('p224', {
47895 type: 'short',
47896 prime: 'p224',
47897 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
47898 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
47899 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
47900 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
47901 hash: hash.sha256,
47902 gRed: false,
47903 g: [
47904 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
47905 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
47906 ]
47907});
47908
47909defineCurve('p256', {
47910 type: 'short',
47911 prime: null,
47912 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
47913 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
47914 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
47915 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
47916 hash: hash.sha256,
47917 gRed: false,
47918 g: [
47919 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
47920 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
47921 ]
47922});
47923
47924defineCurve('curve25519', {
47925 type: 'mont',
47926 prime: 'p25519',
47927 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
47928 a: '76d06',
47929 b: '0',
47930 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
47931 hash: hash.sha256,
47932 gRed: false,
47933 g: [
47934 '9'
47935 ]
47936});
47937
47938defineCurve('ed25519', {
47939 type: 'edwards',
47940 prime: 'p25519',
47941 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
47942 a: '-1',
47943 c: '1',
47944 // -121665 * (121666^(-1)) (mod P)
47945 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
47946 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
47947 hash: hash.sha256,
47948 gRed: false,
47949 g: [
47950 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
47951
47952 // 4/5
47953 '6666666666666666666666666666666666666666666666666666666666666658'
47954 ]
47955});
47956
47957var pre;
47958try {
47959 pre = require('./precomputed/secp256k1');
47960} catch (e) {
47961 pre = undefined;
47962}
47963
47964defineCurve('secp256k1', {
47965 type: 'short',
47966 prime: 'k256',
47967 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
47968 a: '0',
47969 b: '7',
47970 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
47971 h: '1',
47972 hash: hash.sha256,
47973
47974 // Precomputed endomorphism
47975 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
47976 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
47977 basis: [
47978 {
47979 a: '3086d221a7d46bcde86c90e49284eb15',
47980 b: '-e4437ed6010e88286f547fa90abfe4c3'
47981 },
47982 {
47983 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
47984 b: '3086d221a7d46bcde86c90e49284eb15'
47985 }
47986 ],
47987
47988 gRed: false,
47989 g: [
47990 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
47991 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
47992 pre
47993 ]
47994});
47995}, {"hash.js":273,"../elliptic":268,"./precomputed/secp256k1":286}],286: [function (exports, require, module, global) {module.exports = {
47996 doubles: {
47997 step: 4,
47998 points: [
47999 [
48000 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
48001 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
48002 ],
48003 [
48004 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
48005 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
48006 ],
48007 [
48008 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
48009 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
48010 ],
48011 [
48012 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
48013 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
48014 ],
48015 [
48016 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
48017 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
48018 ],
48019 [
48020 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
48021 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
48022 ],
48023 [
48024 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
48025 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
48026 ],
48027 [
48028 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
48029 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
48030 ],
48031 [
48032 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
48033 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
48034 ],
48035 [
48036 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
48037 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
48038 ],
48039 [
48040 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
48041 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
48042 ],
48043 [
48044 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
48045 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
48046 ],
48047 [
48048 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
48049 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
48050 ],
48051 [
48052 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
48053 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
48054 ],
48055 [
48056 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
48057 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
48058 ],
48059 [
48060 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
48061 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
48062 ],
48063 [
48064 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
48065 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
48066 ],
48067 [
48068 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
48069 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
48070 ],
48071 [
48072 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
48073 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
48074 ],
48075 [
48076 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
48077 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
48078 ],
48079 [
48080 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
48081 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
48082 ],
48083 [
48084 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
48085 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
48086 ],
48087 [
48088 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
48089 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
48090 ],
48091 [
48092 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
48093 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
48094 ],
48095 [
48096 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
48097 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
48098 ],
48099 [
48100 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
48101 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
48102 ],
48103 [
48104 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
48105 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
48106 ],
48107 [
48108 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
48109 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
48110 ],
48111 [
48112 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
48113 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
48114 ],
48115 [
48116 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
48117 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
48118 ],
48119 [
48120 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
48121 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
48122 ],
48123 [
48124 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
48125 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
48126 ],
48127 [
48128 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
48129 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
48130 ],
48131 [
48132 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
48133 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
48134 ],
48135 [
48136 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
48137 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
48138 ],
48139 [
48140 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
48141 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
48142 ],
48143 [
48144 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
48145 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
48146 ],
48147 [
48148 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
48149 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
48150 ],
48151 [
48152 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
48153 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
48154 ],
48155 [
48156 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
48157 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
48158 ],
48159 [
48160 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
48161 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
48162 ],
48163 [
48164 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
48165 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
48166 ],
48167 [
48168 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
48169 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
48170 ],
48171 [
48172 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
48173 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
48174 ],
48175 [
48176 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
48177 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
48178 ],
48179 [
48180 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
48181 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
48182 ],
48183 [
48184 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
48185 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
48186 ],
48187 [
48188 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
48189 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
48190 ],
48191 [
48192 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
48193 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
48194 ],
48195 [
48196 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
48197 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
48198 ],
48199 [
48200 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
48201 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
48202 ],
48203 [
48204 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
48205 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
48206 ],
48207 [
48208 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
48209 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
48210 ],
48211 [
48212 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
48213 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
48214 ],
48215 [
48216 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
48217 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
48218 ],
48219 [
48220 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
48221 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
48222 ],
48223 [
48224 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
48225 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
48226 ],
48227 [
48228 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
48229 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
48230 ],
48231 [
48232 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
48233 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
48234 ],
48235 [
48236 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
48237 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
48238 ],
48239 [
48240 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
48241 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
48242 ],
48243 [
48244 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
48245 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
48246 ],
48247 [
48248 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
48249 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
48250 ],
48251 [
48252 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
48253 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
48254 ],
48255 [
48256 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
48257 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
48258 ]
48259 ]
48260 },
48261 naf: {
48262 wnd: 7,
48263 points: [
48264 [
48265 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
48266 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
48267 ],
48268 [
48269 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
48270 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
48271 ],
48272 [
48273 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
48274 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
48275 ],
48276 [
48277 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
48278 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
48279 ],
48280 [
48281 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
48282 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
48283 ],
48284 [
48285 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
48286 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
48287 ],
48288 [
48289 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
48290 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
48291 ],
48292 [
48293 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
48294 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
48295 ],
48296 [
48297 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
48298 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
48299 ],
48300 [
48301 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
48302 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
48303 ],
48304 [
48305 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
48306 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
48307 ],
48308 [
48309 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
48310 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
48311 ],
48312 [
48313 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
48314 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
48315 ],
48316 [
48317 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
48318 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
48319 ],
48320 [
48321 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
48322 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
48323 ],
48324 [
48325 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
48326 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
48327 ],
48328 [
48329 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
48330 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
48331 ],
48332 [
48333 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
48334 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
48335 ],
48336 [
48337 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
48338 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
48339 ],
48340 [
48341 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
48342 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
48343 ],
48344 [
48345 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
48346 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
48347 ],
48348 [
48349 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
48350 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
48351 ],
48352 [
48353 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
48354 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
48355 ],
48356 [
48357 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
48358 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
48359 ],
48360 [
48361 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
48362 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
48363 ],
48364 [
48365 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
48366 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
48367 ],
48368 [
48369 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
48370 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
48371 ],
48372 [
48373 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
48374 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
48375 ],
48376 [
48377 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
48378 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
48379 ],
48380 [
48381 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
48382 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
48383 ],
48384 [
48385 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
48386 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
48387 ],
48388 [
48389 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
48390 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
48391 ],
48392 [
48393 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
48394 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
48395 ],
48396 [
48397 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
48398 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
48399 ],
48400 [
48401 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
48402 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
48403 ],
48404 [
48405 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
48406 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
48407 ],
48408 [
48409 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
48410 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
48411 ],
48412 [
48413 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
48414 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
48415 ],
48416 [
48417 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
48418 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
48419 ],
48420 [
48421 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
48422 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
48423 ],
48424 [
48425 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
48426 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
48427 ],
48428 [
48429 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
48430 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
48431 ],
48432 [
48433 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
48434 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
48435 ],
48436 [
48437 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
48438 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
48439 ],
48440 [
48441 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
48442 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
48443 ],
48444 [
48445 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
48446 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
48447 ],
48448 [
48449 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
48450 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
48451 ],
48452 [
48453 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
48454 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
48455 ],
48456 [
48457 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
48458 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
48459 ],
48460 [
48461 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
48462 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
48463 ],
48464 [
48465 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
48466 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
48467 ],
48468 [
48469 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
48470 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
48471 ],
48472 [
48473 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
48474 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
48475 ],
48476 [
48477 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
48478 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
48479 ],
48480 [
48481 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
48482 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
48483 ],
48484 [
48485 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
48486 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
48487 ],
48488 [
48489 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
48490 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
48491 ],
48492 [
48493 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
48494 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
48495 ],
48496 [
48497 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
48498 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
48499 ],
48500 [
48501 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
48502 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
48503 ],
48504 [
48505 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
48506 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
48507 ],
48508 [
48509 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
48510 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
48511 ],
48512 [
48513 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
48514 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
48515 ],
48516 [
48517 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
48518 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
48519 ],
48520 [
48521 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
48522 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
48523 ],
48524 [
48525 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
48526 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
48527 ],
48528 [
48529 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
48530 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
48531 ],
48532 [
48533 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
48534 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
48535 ],
48536 [
48537 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
48538 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
48539 ],
48540 [
48541 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
48542 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
48543 ],
48544 [
48545 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
48546 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
48547 ],
48548 [
48549 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
48550 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
48551 ],
48552 [
48553 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
48554 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
48555 ],
48556 [
48557 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
48558 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
48559 ],
48560 [
48561 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
48562 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
48563 ],
48564 [
48565 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
48566 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
48567 ],
48568 [
48569 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
48570 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
48571 ],
48572 [
48573 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
48574 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
48575 ],
48576 [
48577 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
48578 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
48579 ],
48580 [
48581 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
48582 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
48583 ],
48584 [
48585 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
48586 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
48587 ],
48588 [
48589 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
48590 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
48591 ],
48592 [
48593 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
48594 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
48595 ],
48596 [
48597 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
48598 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
48599 ],
48600 [
48601 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
48602 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
48603 ],
48604 [
48605 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
48606 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
48607 ],
48608 [
48609 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
48610 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
48611 ],
48612 [
48613 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
48614 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
48615 ],
48616 [
48617 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
48618 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
48619 ],
48620 [
48621 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
48622 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
48623 ],
48624 [
48625 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
48626 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
48627 ],
48628 [
48629 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
48630 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
48631 ],
48632 [
48633 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
48634 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
48635 ],
48636 [
48637 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
48638 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
48639 ],
48640 [
48641 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
48642 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
48643 ],
48644 [
48645 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
48646 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
48647 ],
48648 [
48649 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
48650 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
48651 ],
48652 [
48653 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
48654 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
48655 ],
48656 [
48657 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
48658 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
48659 ],
48660 [
48661 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
48662 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
48663 ],
48664 [
48665 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
48666 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
48667 ],
48668 [
48669 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
48670 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
48671 ],
48672 [
48673 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
48674 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
48675 ],
48676 [
48677 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
48678 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
48679 ],
48680 [
48681 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
48682 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
48683 ],
48684 [
48685 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
48686 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
48687 ],
48688 [
48689 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
48690 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
48691 ],
48692 [
48693 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
48694 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
48695 ],
48696 [
48697 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
48698 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
48699 ],
48700 [
48701 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
48702 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
48703 ],
48704 [
48705 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
48706 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
48707 ],
48708 [
48709 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
48710 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
48711 ],
48712 [
48713 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
48714 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
48715 ],
48716 [
48717 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
48718 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
48719 ],
48720 [
48721 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
48722 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
48723 ],
48724 [
48725 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
48726 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
48727 ],
48728 [
48729 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
48730 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
48731 ],
48732 [
48733 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
48734 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
48735 ],
48736 [
48737 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
48738 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
48739 ],
48740 [
48741 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
48742 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
48743 ],
48744 [
48745 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
48746 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
48747 ],
48748 [
48749 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
48750 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
48751 ],
48752 [
48753 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
48754 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
48755 ],
48756 [
48757 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
48758 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
48759 ],
48760 [
48761 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
48762 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
48763 ],
48764 [
48765 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
48766 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
48767 ],
48768 [
48769 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
48770 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
48771 ]
48772 ]
48773 }
48774};
48775}, {}],287: [function (exports, require, module, global) {'use strict';
48776
48777var bn = require('bn.js');
48778var elliptic = require('../../elliptic');
48779var utils = elliptic.utils;
48780var assert = utils.assert;
48781
48782var KeyPair = require('./key');
48783var Signature = require('./signature');
48784
48785function EC(options) {
48786 if (!(this instanceof EC))
48787 return new EC(options);
48788
48789 // Shortcut `elliptic.ec(curve-name)`
48790 if (typeof options === 'string') {
48791 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
48792
48793 options = elliptic.curves[options];
48794 }
48795
48796 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
48797 if (options instanceof elliptic.curves.PresetCurve)
48798 options = { curve: options };
48799
48800 this.curve = options.curve.curve;
48801 this.n = this.curve.n;
48802 this.nh = this.n.shrn(1);
48803 this.g = this.curve.g;
48804
48805 // Point on curve
48806 this.g = options.curve.g;
48807 this.g.precompute(options.curve.n.bitLength() + 1);
48808
48809 // Hash for function for DRBG
48810 this.hash = options.hash || options.curve.hash;
48811}
48812module.exports = EC;
48813
48814EC.prototype.keyPair = function keyPair(options) {
48815 return new KeyPair(this, options);
48816};
48817
48818EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
48819 return KeyPair.fromPrivate(this, priv, enc);
48820};
48821
48822EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
48823 return KeyPair.fromPublic(this, pub, enc);
48824};
48825
48826EC.prototype.genKeyPair = function genKeyPair(options) {
48827 if (!options)
48828 options = {};
48829
48830 // Instantiate Hmac_DRBG
48831 var drbg = new elliptic.hmacDRBG({
48832 hash: this.hash,
48833 pers: options.pers,
48834 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
48835 nonce: this.n.toArray()
48836 });
48837
48838 var bytes = this.n.byteLength();
48839 var ns2 = this.n.sub(new bn(2));
48840 do {
48841 var priv = new bn(drbg.generate(bytes));
48842 if (priv.cmp(ns2) > 0)
48843 continue;
48844
48845 priv.iaddn(1);
48846 return this.keyFromPrivate(priv);
48847 } while (true);
48848};
48849
48850EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
48851 var delta = msg.byteLength() * 8 - this.n.bitLength();
48852 if (delta > 0)
48853 msg = msg.shrn(delta);
48854 if (!truncOnly && msg.cmp(this.n) >= 0)
48855 return msg.sub(this.n);
48856 else
48857 return msg;
48858};
48859
48860EC.prototype.sign = function sign(msg, key, enc, options) {
48861 if (typeof enc === 'object') {
48862 options = enc;
48863 enc = null;
48864 }
48865 if (!options)
48866 options = {};
48867
48868 key = this.keyFromPrivate(key, enc);
48869 msg = this._truncateToN(new bn(msg, 16));
48870
48871 // Zero-extend key to provide enough entropy
48872 var bytes = this.n.byteLength();
48873 var bkey = key.getPrivate().toArray();
48874 for (var i = bkey.length; i < 21; i++)
48875 bkey.unshift(0);
48876
48877 // Zero-extend nonce to have the same byte size as N
48878 var nonce = msg.toArray();
48879 for (var i = nonce.length; i < bytes; i++)
48880 nonce.unshift(0);
48881
48882 // Instantiate Hmac_DRBG
48883 var drbg = new elliptic.hmacDRBG({
48884 hash: this.hash,
48885 entropy: bkey,
48886 nonce: nonce
48887 });
48888
48889 // Number of bytes to generate
48890 var ns1 = this.n.sub(new bn(1));
48891 do {
48892 var k = new bn(drbg.generate(this.n.byteLength()));
48893 k = this._truncateToN(k, true);
48894 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
48895 continue;
48896
48897 var kp = this.g.mul(k);
48898 if (kp.isInfinity())
48899 continue;
48900
48901 var kpX = kp.getX();
48902 var r = kpX.mod(this.n);
48903 if (r.cmpn(0) === 0)
48904 continue;
48905
48906 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)).mod(this.n);
48907 if (s.cmpn(0) === 0)
48908 continue;
48909
48910 // Use complement of `s`, if it is > `n / 2`
48911 if (options.canonical && s.cmp(this.nh) > 0)
48912 s = this.n.sub(s);
48913
48914 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
48915 (kpX.cmp(r) !== 0 ? 2 : 0);
48916
48917 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
48918 } while (true);
48919};
48920
48921EC.prototype.verify = function verify(msg, signature, key, enc) {
48922 msg = this._truncateToN(new bn(msg, 16));
48923 key = this.keyFromPublic(key, enc);
48924 signature = new Signature(signature, 'hex');
48925
48926 // Perform primitive values validation
48927 var r = signature.r;
48928 var s = signature.s;
48929 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
48930 return false;
48931 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
48932 return false;
48933
48934 // Validate signature
48935 var sinv = s.invm(this.n);
48936 var u1 = sinv.mul(msg).mod(this.n);
48937 var u2 = sinv.mul(r).mod(this.n);
48938
48939 var p = this.g.mulAdd(u1, key.getPublic(), u2);
48940 if (p.isInfinity())
48941 return false;
48942
48943 return p.getX().mod(this.n).cmp(r) === 0;
48944};
48945
48946EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
48947 assert((3 & j) === j, 'The recovery param is more than two bits');
48948 signature = new Signature(signature, enc);
48949
48950 var n = this.n;
48951 var e = new bn(msg);
48952 var r = signature.r;
48953 var s = signature.s;
48954
48955 // A set LSB signifies that the y-coordinate is odd
48956 var isYOdd = j & 1;
48957 var isSecondKey = j >> 1;
48958 if (r.cmp(this.curve.p.mod(this.curve.n)) >= 0 && isSecondKey)
48959 throw new Error('Unable to find sencond key candinate');
48960
48961 // 1.1. Let x = r + jn.
48962 r = this.curve.pointFromX(isYOdd, r);
48963 var eNeg = e.neg().mod(n);
48964
48965 // 1.6.1 Compute Q = r^-1 (sR - eG)
48966 // Q = r^-1 (sR + -eG)
48967 var rInv = signature.r.invm(n);
48968 return r.mul(s).add(this.g.mul(eNeg)).mul(rInv);
48969};
48970
48971EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
48972 signature = new Signature(signature, enc);
48973 if (signature.recoveryParam !== null)
48974 return signature.recoveryParam;
48975
48976 for (var i = 0; i < 4; i++) {
48977 var Qprime = this.recoverPubKey(e, signature, i);
48978
48979 if (Qprime.eq(Q))
48980 return i;
48981 }
48982 throw new Error('Unable to find valid recovery factor');
48983};
48984}, {"bn.js":281,"../../elliptic":268,"./key":288,"./signature":289}],288: [function (exports, require, module, global) {'use strict';
48985
48986var bn = require('bn.js');
48987
48988var elliptic = require('../../elliptic');
48989var utils = elliptic.utils;
48990
48991function KeyPair(ec, options) {
48992 this.ec = ec;
48993 this.priv = null;
48994 this.pub = null;
48995
48996 // KeyPair(ec, { priv: ..., pub: ... })
48997 if (options.priv)
48998 this._importPrivate(options.priv, options.privEnc);
48999 if (options.pub)
49000 this._importPublic(options.pub, options.pubEnc);
49001}
49002module.exports = KeyPair;
49003
49004KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
49005 if (pub instanceof KeyPair)
49006 return pub;
49007
49008 return new KeyPair(ec, {
49009 pub: pub,
49010 pubEnc: enc
49011 });
49012};
49013
49014KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
49015 if (priv instanceof KeyPair)
49016 return priv;
49017
49018 return new KeyPair(ec, {
49019 priv: priv,
49020 privEnc: enc
49021 });
49022};
49023
49024KeyPair.prototype.validate = function validate() {
49025 var pub = this.getPublic();
49026
49027 if (pub.isInfinity())
49028 return { result: false, reason: 'Invalid public key' };
49029 if (!pub.validate())
49030 return { result: false, reason: 'Public key is not a point' };
49031 if (!pub.mul(this.ec.curve.n).isInfinity())
49032 return { result: false, reason: 'Public key * N != O' };
49033
49034 return { result: true, reason: null };
49035};
49036
49037KeyPair.prototype.getPublic = function getPublic(compact, enc) {
49038 if (!this.pub)
49039 this.pub = this.ec.g.mul(this.priv);
49040
49041 // compact is optional argument
49042 if (typeof compact === 'string') {
49043 enc = compact;
49044 compact = null;
49045 }
49046
49047 if (!enc)
49048 return this.pub;
49049
49050 var len = this.ec.curve.p.byteLength();
49051 var x = this.pub.getX().toArray();
49052
49053 for (var i = x.length; i < len; i++)
49054 x.unshift(0);
49055
49056 var res;
49057 if (this.ec.curve.type !== 'mont') {
49058 if (compact) {
49059 res = [ this.pub.getY().isEven() ? 0x02 : 0x03 ].concat(x);
49060 } else {
49061 var y = this.pub.getY().toArray();
49062 for (var i = y.length; i < len; i++)
49063 y.unshift(0);
49064 var res = [ 0x04 ].concat(x, y);
49065 }
49066 } else {
49067 res = x;
49068 }
49069
49070 return utils.encode(res, enc);
49071};
49072
49073KeyPair.prototype.getPrivate = function getPrivate(enc) {
49074 if (enc === 'hex')
49075 return this.priv.toString(16, 2);
49076 else
49077 return this.priv;
49078};
49079
49080KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
49081 this.priv = new bn(key, enc || 16);
49082
49083 // Ensure that the priv won't be bigger than n, otherwise we may fail
49084 // in fixed multiplication method
49085 this.priv = this.priv.mod(this.ec.curve.n);
49086};
49087
49088KeyPair.prototype._importPublic = function _importPublic(key, enc) {
49089 if (key.x || key.y) {
49090 this.pub = this.ec.curve.point(key.x, key.y);
49091 return;
49092 }
49093
49094 key = utils.toArray(key, enc);
49095 if (this.ec.curve.type !== 'mont')
49096 return this._importPublicShort(key);
49097 else
49098 return this._importPublicMont(key);
49099};
49100
49101KeyPair.prototype._importPublicShort = function _importPublicShort(key) {
49102 var len = this.ec.curve.p.byteLength();
49103 if (key[0] === 0x04 && key.length - 1 === 2 * len) {
49104 this.pub = this.ec.curve.point(
49105 key.slice(1, 1 + len),
49106 key.slice(1 + len, 1 + 2 * len));
49107 } else if ((key[0] === 0x02 || key[0] === 0x03) && key.length - 1 === len) {
49108 this.pub = this.ec.curve.pointFromX(key[0] === 0x03, key.slice(1, 1 + len));
49109 }
49110};
49111
49112KeyPair.prototype._importPublicMont = function _importPublicMont(key) {
49113 this.pub = this.ec.curve.point(key, 1);
49114};
49115
49116// ECDH
49117KeyPair.prototype.derive = function derive(pub) {
49118 return pub.mul(this.priv).getX();
49119};
49120
49121// ECDSA
49122KeyPair.prototype.sign = function sign(msg) {
49123 return this.ec.sign(msg, this);
49124};
49125
49126KeyPair.prototype.verify = function verify(msg, signature) {
49127 return this.ec.verify(msg, signature, this);
49128};
49129
49130KeyPair.prototype.inspect = function inspect() {
49131 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
49132 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
49133};
49134}, {"bn.js":281,"../../elliptic":268}],289: [function (exports, require, module, global) {'use strict';
49135
49136var bn = require('bn.js');
49137
49138var elliptic = require('../../elliptic');
49139var utils = elliptic.utils;
49140var assert = utils.assert;
49141
49142function Signature(options, enc) {
49143 if (options instanceof Signature)
49144 return options;
49145
49146 if (this._importDER(options, enc))
49147 return;
49148
49149 assert(options.r && options.s, 'Signature without r or s');
49150 this.r = new bn(options.r, 16);
49151 this.s = new bn(options.s, 16);
49152 if (options.recoveryParam !== null)
49153 this.recoveryParam = options.recoveryParam;
49154 else
49155 this.recoveryParam = null;
49156}
49157module.exports = Signature;
49158
49159Signature.prototype._importDER = function _importDER(data, enc) {
49160 data = utils.toArray(data, enc);
49161 if (data.length < 6 || data[0] !== 0x30 || data[2] !== 0x02)
49162 return false;
49163 var total = data[1];
49164 if (1 + total > data.length)
49165 return false;
49166 var rlen = data[3];
49167 // Short length notation
49168 if (rlen >= 0x80)
49169 return false;
49170 if (4 + rlen + 2 >= data.length)
49171 return false;
49172 if (data[4 + rlen] !== 0x02)
49173 return false;
49174 var slen = data[5 + rlen];
49175 // Short length notation
49176 if (slen >= 0x80)
49177 return false;
49178 if (4 + rlen + 2 + slen > data.length)
49179 return false;
49180
49181 this.r = new bn(data.slice(4, 4 + rlen));
49182 this.s = new bn(data.slice(4 + rlen + 2, 4 + rlen + 2 + slen));
49183 this.recoveryParam = null;
49184
49185 return true;
49186};
49187
49188Signature.prototype.toDER = function toDER(enc) {
49189 var r = this.r.toArray();
49190 var s = this.s.toArray();
49191
49192 // Pad values
49193 if (r[0] & 0x80)
49194 r = [ 0 ].concat(r);
49195 // Pad values
49196 if (s[0] & 0x80)
49197 s = [ 0 ].concat(s);
49198
49199 var total = r.length + s.length + 4;
49200 var res = [ 0x30, total, 0x02, r.length ];
49201 res = res.concat(r, [ 0x02, s.length ], s);
49202 return utils.encode(res, enc);
49203};
49204}, {"bn.js":281,"../../elliptic":268}],290: [function (exports, require, module, global) {exports.publicEncrypt = require('./publicEncrypt');
49205exports.privateDecrypt = require('./privateDecrypt');
49206
49207exports.privateEncrypt = function privateEncrypt(key, buf) {
49208 return exports.publicEncrypt(key, buf, true);
49209};
49210
49211exports.publicDecrypt = function publicDecrypt(key, buf) {
49212 return exports.privateDecrypt(key, buf, true);
49213};}, {"./publicEncrypt":291,"./privateDecrypt":334}],291: [function (exports, require, module, global) {var parseKeys = require('parse-asn1');
49214var randomBytes = require('randombytes');
49215var createHash = require('create-hash');
49216var mgf = require('./mgf');
49217var xor = require('./xor');
49218var bn = require('bn.js');
49219var withPublic = require('./withPublic');
49220var crt = require('browserify-rsa');
49221
49222var constants = {
49223 RSA_PKCS1_OAEP_PADDING: 4,
49224 RSA_PKCS1_PADDIN: 1,
49225 RSA_NO_PADDING: 3
49226};
49227
49228module.exports = function publicEncrypt(public_key, msg, reverse) {
49229 var padding;
49230 if (public_key.padding) {
49231 padding = public_key.padding;
49232 } else if (reverse) {
49233 padding = 1;
49234 } else {
49235 padding = 4;
49236 }
49237 var key = parseKeys(public_key);
49238 var paddedMsg;
49239 if (padding === 4) {
49240 paddedMsg = oaep(key, msg);
49241 } else if (padding === 1) {
49242 paddedMsg = pkcs1(key, msg, reverse);
49243 } else if (padding === 3) {
49244 paddedMsg = new bn(msg);
49245 if (paddedMsg.cmp(key.modulus) >= 0) {
49246 throw new Error('data too long for modulus');
49247 }
49248 } else {
49249 throw new Error('unknown padding');
49250 }
49251 if (reverse) {
49252 return crt(paddedMsg, key);
49253 } else {
49254 return withPublic(paddedMsg, key);
49255 }
49256};
49257
49258function oaep(key, msg){
49259 var k = key.modulus.byteLength();
49260 var mLen = msg.length;
49261 var iHash = createHash('sha1').update(new Buffer('')).digest();
49262 var hLen = iHash.length;
49263 var hLen2 = 2 * hLen;
49264 if (mLen > k - hLen2 - 2) {
49265 throw new Error('message too long');
49266 }
49267 var ps = new Buffer(k - mLen - hLen2 - 2);
49268 ps.fill(0);
49269 var dblen = k - hLen - 1;
49270 var seed = randomBytes(hLen);
49271 var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen));
49272 var maskedSeed = xor(seed, mgf(maskedDb, hLen));
49273 return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k));
49274}
49275function pkcs1(key, msg, reverse){
49276 var mLen = msg.length;
49277 var k = key.modulus.byteLength();
49278 if (mLen > k - 11) {
49279 throw new Error('message too long');
49280 }
49281 var ps;
49282 if (reverse) {
49283 ps = new Buffer(k - mLen - 3);
49284 ps.fill(0xff);
49285 } else {
49286 ps = nonZero(k - mLen - 3);
49287 }
49288 return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k));
49289}
49290function nonZero(len, crypto) {
49291 var out = new Buffer(len);
49292 var i = 0;
49293 var cache = randomBytes(len*2);
49294 var cur = 0;
49295 var num;
49296 while (i < len) {
49297 if (cur === cache.length) {
49298 cache = randomBytes(len*2);
49299 cur = 0;
49300 }
49301 num = cache[cur++];
49302 if (num) {
49303 out[i++] = num;
49304 }
49305 }
49306 return out;
49307}}, {"parse-asn1":292,"randombytes":147,"create-hash":148,"./mgf":330,"./xor":331,"bn.js":295,"./withPublic":332,"browserify-rsa":333}],292: [function (exports, require, module, global) {var asn1 = require('./asn1')
49308var aesid = require('./aesid.json')
49309var fixProc = require('./fixProc')
49310var ciphers = require('browserify-aes')
49311var compat = require('pbkdf2')
49312module.exports = parseKeys
49313
49314function parseKeys (buffer) {
49315 var password
49316 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
49317 password = buffer.passphrase
49318 buffer = buffer.key
49319 }
49320 if (typeof buffer === 'string') {
49321 buffer = new Buffer(buffer)
49322 }
49323
49324 var stripped = fixProc(buffer, password)
49325
49326 var type = stripped.tag
49327 var data = stripped.data
49328 var subtype, ndata
49329 switch (type) {
49330 case 'PUBLIC KEY':
49331 ndata = asn1.PublicKey.decode(data, 'der')
49332 subtype = ndata.algorithm.algorithm.join('.')
49333 switch (subtype) {
49334 case '1.2.840.113549.1.1.1':
49335 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
49336 case '1.2.840.10045.2.1':
49337 ndata.subjectPrivateKey = ndata.subjectPublicKey
49338 return {
49339 type: 'ec',
49340 data: ndata
49341 }
49342 case '1.2.840.10040.4.1':
49343 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
49344 return {
49345 type: 'dsa',
49346 data: ndata.algorithm.params
49347 }
49348 default: throw new Error('unknown key id ' + subtype)
49349 }
49350 throw new Error('unknown key type ' + type)
49351 case 'ENCRYPTED PRIVATE KEY':
49352 data = asn1.EncryptedPrivateKey.decode(data, 'der')
49353 data = decrypt(data, password)
49354 // falls through
49355 case 'PRIVATE KEY':
49356 ndata = asn1.PrivateKey.decode(data, 'der')
49357 subtype = ndata.algorithm.algorithm.join('.')
49358 switch (subtype) {
49359 case '1.2.840.113549.1.1.1':
49360 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
49361 case '1.2.840.10045.2.1':
49362 return {
49363 curve: ndata.algorithm.curve,
49364 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
49365 }
49366 case '1.2.840.10040.4.1':
49367 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
49368 return {
49369 type: 'dsa',
49370 params: ndata.algorithm.params
49371 }
49372 default: throw new Error('unknown key id ' + subtype)
49373 }
49374 throw new Error('unknown key type ' + type)
49375 case 'RSA PUBLIC KEY':
49376 return asn1.RSAPublicKey.decode(data, 'der')
49377 case 'RSA PRIVATE KEY':
49378 return asn1.RSAPrivateKey.decode(data, 'der')
49379 case 'DSA PRIVATE KEY':
49380 return {
49381 type: 'dsa',
49382 params: asn1.DSAPrivateKey.decode(data, 'der')
49383 }
49384 case 'EC PRIVATE KEY':
49385 data = asn1.ECPrivateKey.decode(data, 'der')
49386 return {
49387 curve: data.parameters.value,
49388 privateKey: data.privateKey
49389 }
49390 default: throw new Error('unknown key type ' + type)
49391 }
49392}
49393parseKeys.signature = asn1.signature
49394function decrypt (data, password) {
49395 var salt = data.algorithm.decrypt.kde.kdeparams.salt
49396 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
49397 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
49398 var iv = data.algorithm.decrypt.cipher.iv
49399 var cipherText = data.subjectPrivateKey
49400 var keylen = parseInt(algo.split('-')[1], 10) / 8
49401 var key = compat.pbkdf2Sync(password, salt, iters, keylen)
49402 var cipher = ciphers.createDecipheriv(algo, key, iv)
49403 var out = []
49404 out.push(cipher.update(cipherText))
49405 out.push(cipher.final())
49406 return Buffer.concat(out)
49407}
49408}, {"./asn1":293,"./aesid.json":310,"./fixProc":311,"browserify-aes":313,"pbkdf2":164}],293: [function (exports, require, module, global) {// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
49409// Fedor, you are amazing.
49410
49411var asn1 = require('asn1.js')
49412
49413var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
49414 this.seq().obj(
49415 this.key('version').int(),
49416 this.key('modulus').int(),
49417 this.key('publicExponent').int(),
49418 this.key('privateExponent').int(),
49419 this.key('prime1').int(),
49420 this.key('prime2').int(),
49421 this.key('exponent1').int(),
49422 this.key('exponent2').int(),
49423 this.key('coefficient').int()
49424 )
49425})
49426exports.RSAPrivateKey = RSAPrivateKey
49427
49428var RSAPublicKey = asn1.define('RSAPublicKey', function () {
49429 this.seq().obj(
49430 this.key('modulus').int(),
49431 this.key('publicExponent').int()
49432 )
49433})
49434exports.RSAPublicKey = RSAPublicKey
49435
49436var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
49437 this.seq().obj(
49438 this.key('algorithm').use(AlgorithmIdentifier),
49439 this.key('subjectPublicKey').bitstr()
49440 )
49441})
49442exports.PublicKey = PublicKey
49443
49444var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
49445 this.seq().obj(
49446 this.key('algorithm').objid(),
49447 this.key('none').null_().optional(),
49448 this.key('curve').objid().optional(),
49449 this.key('params').seq().obj(
49450 this.key('p').int(),
49451 this.key('q').int(),
49452 this.key('g').int()
49453 ).optional()
49454 )
49455})
49456
49457var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
49458 this.seq().obj(
49459 this.key('version').int(),
49460 this.key('algorithm').use(AlgorithmIdentifier),
49461 this.key('subjectPrivateKey').octstr()
49462 )
49463})
49464exports.PrivateKey = PrivateKeyInfo
49465var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
49466 this.seq().obj(
49467 this.key('algorithm').seq().obj(
49468 this.key('id').objid(),
49469 this.key('decrypt').seq().obj(
49470 this.key('kde').seq().obj(
49471 this.key('id').objid(),
49472 this.key('kdeparams').seq().obj(
49473 this.key('salt').octstr(),
49474 this.key('iters').int()
49475 )
49476 ),
49477 this.key('cipher').seq().obj(
49478 this.key('algo').objid(),
49479 this.key('iv').octstr()
49480 )
49481 )
49482 ),
49483 this.key('subjectPrivateKey').octstr()
49484 )
49485})
49486
49487exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
49488
49489var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
49490 this.seq().obj(
49491 this.key('version').int(),
49492 this.key('p').int(),
49493 this.key('q').int(),
49494 this.key('g').int(),
49495 this.key('pub_key').int(),
49496 this.key('priv_key').int()
49497 )
49498})
49499exports.DSAPrivateKey = DSAPrivateKey
49500
49501exports.DSAparam = asn1.define('DSAparam', function () {
49502 this.int()
49503})
49504var ECPrivateKey = asn1.define('ECPrivateKey', function () {
49505 this.seq().obj(
49506 this.key('version').int(),
49507 this.key('privateKey').octstr(),
49508 this.key('parameters').optional().explicit(0).use(ECParameters),
49509 this.key('publicKey').optional().explicit(1).bitstr()
49510 )
49511})
49512exports.ECPrivateKey = ECPrivateKey
49513var ECParameters = asn1.define('ECParameters', function () {
49514 this.choice({
49515 namedCurve: this.objid()
49516 })
49517})
49518
49519exports.signature = asn1.define('signature', function () {
49520 this.seq().obj(
49521 this.key('r').int(),
49522 this.key('s').int()
49523 )
49524})
49525}, {"asn1.js":294}],294: [function (exports, require, module, global) {var asn1 = exports;
49526
49527asn1.bignum = require('bn.js');
49528
49529asn1.define = require('./asn1/api').define;
49530asn1.base = require('./asn1/base');
49531asn1.constants = require('./asn1/constants');
49532asn1.decoders = require('./asn1/decoders');
49533asn1.encoders = require('./asn1/encoders');
49534}, {"bn.js":295,"./asn1/api":296,"./asn1/base":297,"./asn1/constants":302,"./asn1/decoders":304,"./asn1/encoders":307}],295: [function (exports, require, module, global) {(function (module, exports) {
49535
49536'use strict';
49537
49538// Utils
49539
49540function assert(val, msg) {
49541 if (!val)
49542 throw new Error(msg || 'Assertion failed');
49543}
49544
49545// Could use `inherits` module, but don't want to move from single file
49546// architecture yet.
49547function inherits(ctor, superCtor) {
49548 ctor.super_ = superCtor;
49549 var TempCtor = function () {};
49550 TempCtor.prototype = superCtor.prototype;
49551 ctor.prototype = new TempCtor();
49552 ctor.prototype.constructor = ctor;
49553}
49554
49555// BN
49556
49557function BN(number, base, endian) {
49558 // May be `new BN(bn)` ?
49559 if (number !== null &&
49560 typeof number === 'object' &&
49561 Array.isArray(number.words)) {
49562 return number;
49563 }
49564
49565 this.sign = false;
49566 this.words = null;
49567 this.length = 0;
49568
49569 // Reduction context
49570 this.red = null;
49571
49572 if (base === 'le' || base === 'be') {
49573 endian = base;
49574 base = 10;
49575 }
49576
49577 if (number !== null)
49578 this._init(number || 0, base || 10, endian || 'be');
49579}
49580if (typeof module === 'object')
49581 module.exports = BN;
49582else
49583 exports.BN = BN;
49584
49585BN.BN = BN;
49586BN.wordSize = 26;
49587
49588BN.prototype._init = function init(number, base, endian) {
49589 if (typeof number === 'number') {
49590 return this._initNumber(number, base, endian);
49591 } else if (typeof number === 'object') {
49592 return this._initArray(number, base, endian);
49593 }
49594 if (base === 'hex')
49595 base = 16;
49596 assert(base === (base | 0) && base >= 2 && base <= 36);
49597
49598 number = number.toString().replace(/\s+/g, '');
49599 var start = 0;
49600 if (number[0] === '-')
49601 start++;
49602
49603 if (base === 16)
49604 this._parseHex(number, start);
49605 else
49606 this._parseBase(number, base, start);
49607
49608 if (number[0] === '-')
49609 this.sign = true;
49610
49611 this.strip();
49612
49613 if (endian !== 'le')
49614 return;
49615
49616 this._initArray(this.toArray(), base, endian);
49617};
49618
49619BN.prototype._initNumber = function _initNumber(number, base, endian) {
49620 if (number < 0) {
49621 this.sign = true;
49622 number = -number;
49623 }
49624 if (number < 0x4000000) {
49625 this.words = [ number & 0x3ffffff ];
49626 this.length = 1;
49627 } else if (number < 0x10000000000000) {
49628 this.words = [
49629 number & 0x3ffffff,
49630 (number / 0x4000000) & 0x3ffffff
49631 ];
49632 this.length = 2;
49633 } else {
49634 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
49635 this.words = [
49636 number & 0x3ffffff,
49637 (number / 0x4000000) & 0x3ffffff,
49638 1
49639 ];
49640 this.length = 3;
49641 }
49642
49643 if (endian !== 'le')
49644 return;
49645
49646 // Reverse the bytes
49647 this._initArray(this.toArray(), base, endian);
49648};
49649
49650BN.prototype._initArray = function _initArray(number, base, endian) {
49651 // Perhaps a Uint8Array
49652 assert(typeof number.length === 'number');
49653 if (number.length <= 0) {
49654 this.words = [ 0 ];
49655 this.length = 1;
49656 return this;
49657 }
49658
49659 this.length = Math.ceil(number.length / 3);
49660 this.words = new Array(this.length);
49661 for (var i = 0; i < this.length; i++)
49662 this.words[i] = 0;
49663
49664 var off = 0;
49665 if (endian === 'be') {
49666 for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
49667 var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
49668 this.words[j] |= (w << off) & 0x3ffffff;
49669 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
49670 off += 24;
49671 if (off >= 26) {
49672 off -= 26;
49673 j++;
49674 }
49675 }
49676 } else if (endian === 'le') {
49677 for (var i = 0, j = 0; i < number.length; i += 3) {
49678 var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
49679 this.words[j] |= (w << off) & 0x3ffffff;
49680 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
49681 off += 24;
49682 if (off >= 26) {
49683 off -= 26;
49684 j++;
49685 }
49686 }
49687 }
49688 return this.strip();
49689};
49690
49691function parseHex(str, start, end) {
49692 var r = 0;
49693 var len = Math.min(str.length, end);
49694 for (var i = start; i < len; i++) {
49695 var c = str.charCodeAt(i) - 48;
49696
49697 r <<= 4;
49698
49699 // 'a' - 'f'
49700 if (c >= 49 && c <= 54)
49701 r |= c - 49 + 0xa;
49702
49703 // 'A' - 'F'
49704 else if (c >= 17 && c <= 22)
49705 r |= c - 17 + 0xa;
49706
49707 // '0' - '9'
49708 else
49709 r |= c & 0xf;
49710 }
49711 return r;
49712}
49713
49714BN.prototype._parseHex = function _parseHex(number, start) {
49715 // Create possibly bigger array to ensure that it fits the number
49716 this.length = Math.ceil((number.length - start) / 6);
49717 this.words = new Array(this.length);
49718 for (var i = 0; i < this.length; i++)
49719 this.words[i] = 0;
49720
49721 // Scan 24-bit chunks and add them to the number
49722 var off = 0;
49723 for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
49724 var w = parseHex(number, i, i + 6);
49725 this.words[j] |= (w << off) & 0x3ffffff;
49726 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
49727 off += 24;
49728 if (off >= 26) {
49729 off -= 26;
49730 j++;
49731 }
49732 }
49733 if (i + 6 !== start) {
49734 var w = parseHex(number, start, i + 6);
49735 this.words[j] |= (w << off) & 0x3ffffff;
49736 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
49737 }
49738 this.strip();
49739};
49740
49741function parseBase(str, start, end, mul) {
49742 var r = 0;
49743 var len = Math.min(str.length, end);
49744 for (var i = start; i < len; i++) {
49745 var c = str.charCodeAt(i) - 48;
49746
49747 r *= mul;
49748
49749 // 'a'
49750 if (c >= 49)
49751 r += c - 49 + 0xa;
49752
49753 // 'A'
49754 else if (c >= 17)
49755 r += c - 17 + 0xa;
49756
49757 // '0' - '9'
49758 else
49759 r += c;
49760 }
49761 return r;
49762}
49763
49764BN.prototype._parseBase = function _parseBase(number, base, start) {
49765 // Initialize as zero
49766 this.words = [ 0 ];
49767 this.length = 1;
49768
49769 // Find length of limb in base
49770 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
49771 limbLen++;
49772 limbLen--;
49773 limbPow = (limbPow / base) | 0;
49774
49775 var total = number.length - start;
49776 var mod = total % limbLen;
49777 var end = Math.min(total, total - mod) + start;
49778
49779 var word = 0;
49780 for (var i = start; i < end; i += limbLen) {
49781 word = parseBase(number, i, i + limbLen, base);
49782
49783 this.imuln(limbPow);
49784 if (this.words[0] + word < 0x4000000)
49785 this.words[0] += word;
49786 else
49787 this._iaddn(word);
49788 }
49789
49790 if (mod !== 0) {
49791 var pow = 1;
49792 var word = parseBase(number, i, number.length, base);
49793
49794 for (var i = 0; i < mod; i++)
49795 pow *= base;
49796 this.imuln(pow);
49797 if (this.words[0] + word < 0x4000000)
49798 this.words[0] += word;
49799 else
49800 this._iaddn(word);
49801 }
49802};
49803
49804BN.prototype.copy = function copy(dest) {
49805 dest.words = new Array(this.length);
49806 for (var i = 0; i < this.length; i++)
49807 dest.words[i] = this.words[i];
49808 dest.length = this.length;
49809 dest.sign = this.sign;
49810 dest.red = this.red;
49811};
49812
49813BN.prototype.clone = function clone() {
49814 var r = new BN(null);
49815 this.copy(r);
49816 return r;
49817};
49818
49819// Remove leading `0` from `this`
49820BN.prototype.strip = function strip() {
49821 while (this.length > 1 && this.words[this.length - 1] === 0)
49822 this.length--;
49823 return this._normSign();
49824};
49825
49826BN.prototype._normSign = function _normSign() {
49827 // -0 = 0
49828 if (this.length === 1 && this.words[0] === 0)
49829 this.sign = false;
49830 return this;
49831};
49832
49833BN.prototype.inspect = function inspect() {
49834 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
49835};
49836
49837/*
49838
49839var zeros = [];
49840var groupSizes = [];
49841var groupBases = [];
49842
49843var s = '';
49844var i = -1;
49845while (++i < BN.wordSize) {
49846 zeros[i] = s;
49847 s += '0';
49848}
49849groupSizes[0] = 0;
49850groupSizes[1] = 0;
49851groupBases[0] = 0;
49852groupBases[1] = 0;
49853var base = 2 - 1;
49854while (++base < 36 + 1) {
49855 var groupSize = 0;
49856 var groupBase = 1;
49857 while (groupBase < (1 << BN.wordSize) / base) {
49858 groupBase *= base;
49859 groupSize += 1;
49860 }
49861 groupSizes[base] = groupSize;
49862 groupBases[base] = groupBase;
49863}
49864
49865*/
49866
49867var zeros = [
49868 '',
49869 '0',
49870 '00',
49871 '000',
49872 '0000',
49873 '00000',
49874 '000000',
49875 '0000000',
49876 '00000000',
49877 '000000000',
49878 '0000000000',
49879 '00000000000',
49880 '000000000000',
49881 '0000000000000',
49882 '00000000000000',
49883 '000000000000000',
49884 '0000000000000000',
49885 '00000000000000000',
49886 '000000000000000000',
49887 '0000000000000000000',
49888 '00000000000000000000',
49889 '000000000000000000000',
49890 '0000000000000000000000',
49891 '00000000000000000000000',
49892 '000000000000000000000000',
49893 '0000000000000000000000000'
49894];
49895
49896var groupSizes = [
49897 0, 0,
49898 25, 16, 12, 11, 10, 9, 8,
49899 8, 7, 7, 7, 7, 6, 6,
49900 6, 6, 6, 6, 6, 5, 5,
49901 5, 5, 5, 5, 5, 5, 5,
49902 5, 5, 5, 5, 5, 5, 5
49903];
49904
49905var groupBases = [
49906 0, 0,
49907 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
49908 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
49909 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
49910 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
49911 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
49912];
49913
49914BN.prototype.toString = function toString(base, padding) {
49915 base = base || 10;
49916 if (base === 16 || base === 'hex') {
49917 var out = '';
49918 var off = 0;
49919 var padding = padding | 0 || 1;
49920 var carry = 0;
49921 for (var i = 0; i < this.length; i++) {
49922 var w = this.words[i];
49923 var word = (((w << off) | carry) & 0xffffff).toString(16);
49924 carry = (w >>> (24 - off)) & 0xffffff;
49925 if (carry !== 0 || i !== this.length - 1)
49926 out = zeros[6 - word.length] + word + out;
49927 else
49928 out = word + out;
49929 off += 2;
49930 if (off >= 26) {
49931 off -= 26;
49932 i--;
49933 }
49934 }
49935 if (carry !== 0)
49936 out = carry.toString(16) + out;
49937 while (out.length % padding !== 0)
49938 out = '0' + out;
49939 if (this.sign)
49940 out = '-' + out;
49941 return out;
49942 } else if (base === (base | 0) && base >= 2 && base <= 36) {
49943 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
49944 var groupSize = groupSizes[base];
49945 // var groupBase = Math.pow(base, groupSize);
49946 var groupBase = groupBases[base];
49947 var out = '';
49948 var c = this.clone();
49949 c.sign = false;
49950 while (c.cmpn(0) !== 0) {
49951 var r = c.modn(groupBase).toString(base);
49952 c = c.idivn(groupBase);
49953
49954 if (c.cmpn(0) !== 0)
49955 out = zeros[groupSize - r.length] + r + out;
49956 else
49957 out = r + out;
49958 }
49959 if (this.cmpn(0) === 0)
49960 out = '0' + out;
49961 if (this.sign)
49962 out = '-' + out;
49963 return out;
49964 } else {
49965 assert(false, 'Base should be between 2 and 36');
49966 }
49967};
49968
49969BN.prototype.toJSON = function toJSON() {
49970 return this.toString(16);
49971};
49972
49973BN.prototype.toArray = function toArray(endian) {
49974 this.strip();
49975 var res = new Array(this.byteLength());
49976 res[0] = 0;
49977
49978 var q = this.clone();
49979 if (endian !== 'le') {
49980 // Assume big-endian
49981 for (var i = 0; q.cmpn(0) !== 0; i++) {
49982 var b = q.andln(0xff);
49983 q.ishrn(8);
49984
49985 res[res.length - i - 1] = b;
49986 }
49987 } else {
49988 // Assume little-endian
49989 for (var i = 0; q.cmpn(0) !== 0; i++) {
49990 var b = q.andln(0xff);
49991 q.ishrn(8);
49992
49993 res[i] = b;
49994 }
49995 }
49996
49997 return res;
49998};
49999
50000if (Math.clz32) {
50001 BN.prototype._countBits = function _countBits(w) {
50002 return 32 - Math.clz32(w);
50003 };
50004} else {
50005 BN.prototype._countBits = function _countBits(w) {
50006 var t = w;
50007 var r = 0;
50008 if (t >= 0x1000) {
50009 r += 13;
50010 t >>>= 13;
50011 }
50012 if (t >= 0x40) {
50013 r += 7;
50014 t >>>= 7;
50015 }
50016 if (t >= 0x8) {
50017 r += 4;
50018 t >>>= 4;
50019 }
50020 if (t >= 0x02) {
50021 r += 2;
50022 t >>>= 2;
50023 }
50024 return r + t;
50025 };
50026}
50027
50028BN.prototype._zeroBits = function _zeroBits(w) {
50029 // Short-cut
50030 if (w === 0)
50031 return 26;
50032
50033 var t = w;
50034 var r = 0;
50035 if ((t & 0x1fff) === 0) {
50036 r += 13;
50037 t >>>= 13;
50038 }
50039 if ((t & 0x7f) === 0) {
50040 r += 7;
50041 t >>>= 7;
50042 }
50043 if ((t & 0xf) === 0) {
50044 r += 4;
50045 t >>>= 4;
50046 }
50047 if ((t & 0x3) === 0) {
50048 r += 2;
50049 t >>>= 2;
50050 }
50051 if ((t & 0x1) === 0)
50052 r++;
50053 return r;
50054};
50055
50056// Return number of used bits in a BN
50057BN.prototype.bitLength = function bitLength() {
50058 var hi = 0;
50059 var w = this.words[this.length - 1];
50060 var hi = this._countBits(w);
50061 return (this.length - 1) * 26 + hi;
50062};
50063
50064// Number of trailing zero bits
50065BN.prototype.zeroBits = function zeroBits() {
50066 if (this.cmpn(0) === 0)
50067 return 0;
50068
50069 var r = 0;
50070 for (var i = 0; i < this.length; i++) {
50071 var b = this._zeroBits(this.words[i]);
50072 r += b;
50073 if (b !== 26)
50074 break;
50075 }
50076 return r;
50077};
50078
50079BN.prototype.byteLength = function byteLength() {
50080 return Math.ceil(this.bitLength() / 8);
50081};
50082
50083// Return negative clone of `this`
50084BN.prototype.neg = function neg() {
50085 if (this.cmpn(0) === 0)
50086 return this.clone();
50087
50088 var r = this.clone();
50089 r.sign = !this.sign;
50090 return r;
50091};
50092
50093
50094// Or `num` with `this` in-place
50095BN.prototype.ior = function ior(num) {
50096 this.sign = this.sign || num.sign;
50097
50098 while (this.length < num.length)
50099 this.words[this.length++] = 0;
50100
50101 for (var i = 0; i < num.length; i++)
50102 this.words[i] = this.words[i] | num.words[i];
50103
50104 return this.strip();
50105};
50106
50107
50108// Or `num` with `this`
50109BN.prototype.or = function or(num) {
50110 if (this.length > num.length)
50111 return this.clone().ior(num);
50112 else
50113 return num.clone().ior(this);
50114};
50115
50116
50117// And `num` with `this` in-place
50118BN.prototype.iand = function iand(num) {
50119 this.sign = this.sign && num.sign;
50120
50121 // b = min-length(num, this)
50122 var b;
50123 if (this.length > num.length)
50124 b = num;
50125 else
50126 b = this;
50127
50128 for (var i = 0; i < b.length; i++)
50129 this.words[i] = this.words[i] & num.words[i];
50130
50131 this.length = b.length;
50132
50133 return this.strip();
50134};
50135
50136
50137// And `num` with `this`
50138BN.prototype.and = function and(num) {
50139 if (this.length > num.length)
50140 return this.clone().iand(num);
50141 else
50142 return num.clone().iand(this);
50143};
50144
50145
50146// Xor `num` with `this` in-place
50147BN.prototype.ixor = function ixor(num) {
50148 this.sign = this.sign || num.sign;
50149
50150 // a.length > b.length
50151 var a;
50152 var b;
50153 if (this.length > num.length) {
50154 a = this;
50155 b = num;
50156 } else {
50157 a = num;
50158 b = this;
50159 }
50160
50161 for (var i = 0; i < b.length; i++)
50162 this.words[i] = a.words[i] ^ b.words[i];
50163
50164 if (this !== a)
50165 for (; i < a.length; i++)
50166 this.words[i] = a.words[i];
50167
50168 this.length = a.length;
50169
50170 return this.strip();
50171};
50172
50173
50174// Xor `num` with `this`
50175BN.prototype.xor = function xor(num) {
50176 if (this.length > num.length)
50177 return this.clone().ixor(num);
50178 else
50179 return num.clone().ixor(this);
50180};
50181
50182
50183// Set `bit` of `this`
50184BN.prototype.setn = function setn(bit, val) {
50185 assert(typeof bit === 'number' && bit >= 0);
50186
50187 var off = (bit / 26) | 0;
50188 var wbit = bit % 26;
50189
50190 while (this.length <= off)
50191 this.words[this.length++] = 0;
50192
50193 if (val)
50194 this.words[off] = this.words[off] | (1 << wbit);
50195 else
50196 this.words[off] = this.words[off] & ~(1 << wbit);
50197
50198 return this.strip();
50199};
50200
50201
50202// Add `num` to `this` in-place
50203BN.prototype.iadd = function iadd(num) {
50204 // negative + positive
50205 if (this.sign && !num.sign) {
50206 this.sign = false;
50207 var r = this.isub(num);
50208 this.sign = !this.sign;
50209 return this._normSign();
50210
50211 // positive + negative
50212 } else if (!this.sign && num.sign) {
50213 num.sign = false;
50214 var r = this.isub(num);
50215 num.sign = true;
50216 return r._normSign();
50217 }
50218
50219 // a.length > b.length
50220 var a;
50221 var b;
50222 if (this.length > num.length) {
50223 a = this;
50224 b = num;
50225 } else {
50226 a = num;
50227 b = this;
50228 }
50229
50230 var carry = 0;
50231 for (var i = 0; i < b.length; i++) {
50232 var r = a.words[i] + b.words[i] + carry;
50233 this.words[i] = r & 0x3ffffff;
50234 carry = r >>> 26;
50235 }
50236 for (; carry !== 0 && i < a.length; i++) {
50237 var r = a.words[i] + carry;
50238 this.words[i] = r & 0x3ffffff;
50239 carry = r >>> 26;
50240 }
50241
50242 this.length = a.length;
50243 if (carry !== 0) {
50244 this.words[this.length] = carry;
50245 this.length++;
50246 // Copy the rest of the words
50247 } else if (a !== this) {
50248 for (; i < a.length; i++)
50249 this.words[i] = a.words[i];
50250 }
50251
50252 return this;
50253};
50254
50255// Add `num` to `this`
50256BN.prototype.add = function add(num) {
50257 if (num.sign && !this.sign) {
50258 num.sign = false;
50259 var res = this.sub(num);
50260 num.sign = true;
50261 return res;
50262 } else if (!num.sign && this.sign) {
50263 this.sign = false;
50264 var res = num.sub(this);
50265 this.sign = true;
50266 return res;
50267 }
50268
50269 if (this.length > num.length)
50270 return this.clone().iadd(num);
50271 else
50272 return num.clone().iadd(this);
50273};
50274
50275// Subtract `num` from `this` in-place
50276BN.prototype.isub = function isub(num) {
50277 // this - (-num) = this + num
50278 if (num.sign) {
50279 num.sign = false;
50280 var r = this.iadd(num);
50281 num.sign = true;
50282 return r._normSign();
50283
50284 // -this - num = -(this + num)
50285 } else if (this.sign) {
50286 this.sign = false;
50287 this.iadd(num);
50288 this.sign = true;
50289 return this._normSign();
50290 }
50291
50292 // At this point both numbers are positive
50293 var cmp = this.cmp(num);
50294
50295 // Optimization - zeroify
50296 if (cmp === 0) {
50297 this.sign = false;
50298 this.length = 1;
50299 this.words[0] = 0;
50300 return this;
50301 }
50302
50303 // a > b
50304 var a;
50305 var b;
50306 if (cmp > 0) {
50307 a = this;
50308 b = num;
50309 } else {
50310 a = num;
50311 b = this;
50312 }
50313
50314 var carry = 0;
50315 for (var i = 0; i < b.length; i++) {
50316 var r = a.words[i] - b.words[i] + carry;
50317 carry = r >> 26;
50318 this.words[i] = r & 0x3ffffff;
50319 }
50320 for (; carry !== 0 && i < a.length; i++) {
50321 var r = a.words[i] + carry;
50322 carry = r >> 26;
50323 this.words[i] = r & 0x3ffffff;
50324 }
50325
50326 // Copy rest of the words
50327 if (carry === 0 && i < a.length && a !== this)
50328 for (; i < a.length; i++)
50329 this.words[i] = a.words[i];
50330 this.length = Math.max(this.length, i);
50331
50332 if (a !== this)
50333 this.sign = true;
50334
50335 return this.strip();
50336};
50337
50338// Subtract `num` from `this`
50339BN.prototype.sub = function sub(num) {
50340 return this.clone().isub(num);
50341};
50342
50343/*
50344// NOTE: This could be potentionally used to generate loop-less multiplications
50345function _genCombMulTo(alen, blen) {
50346 var len = alen + blen - 1;
50347 var src = [
50348 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
50349 'mask = 0x3ffffff, shift = 0x4000000;',
50350 'out.length = ' + len + ';'
50351 ];
50352 for (var k = 0; k < len; k++) {
50353 var minJ = Math.max(0, k - alen + 1);
50354 var maxJ = Math.min(k, blen - 1);
50355
50356 for (var j = minJ; j <= maxJ; j++) {
50357 var i = k - j;
50358 var mul = 'a[' + i + '] * b[' + j + ']';
50359
50360 if (j === minJ) {
50361 src.push('w = ' + mul + ' + c;');
50362 src.push('c = (w / shift) | 0;');
50363 } else {
50364 src.push('w += ' + mul + ';');
50365 src.push('c += (w / shift) | 0;');
50366 }
50367 src.push('w &= mask;');
50368 }
50369 src.push('o[' + k + '] = w;');
50370 }
50371 src.push('if (c !== 0) {',
50372 ' o[' + k + '] = c;',
50373 ' out.length++;',
50374 '}',
50375 'return out;');
50376
50377 return src.join('\n');
50378}
50379*/
50380
50381BN.prototype._smallMulTo = function _smallMulTo(num, out) {
50382 out.sign = num.sign !== this.sign;
50383 out.length = this.length + num.length;
50384
50385 var carry = 0;
50386 for (var k = 0; k < out.length - 1; k++) {
50387 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
50388 // note that ncarry could be >= 0x3ffffff
50389 var ncarry = carry >>> 26;
50390 var rword = carry & 0x3ffffff;
50391 var maxJ = Math.min(k, num.length - 1);
50392 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
50393 var i = k - j;
50394 var a = this.words[i] | 0;
50395 var b = num.words[j] | 0;
50396 var r = a * b;
50397
50398 var lo = r & 0x3ffffff;
50399 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
50400 lo = (lo + rword) | 0;
50401 rword = lo & 0x3ffffff;
50402 ncarry = (ncarry + (lo >>> 26)) | 0;
50403 }
50404 out.words[k] = rword;
50405 carry = ncarry;
50406 }
50407 if (carry !== 0) {
50408 out.words[k] = carry;
50409 } else {
50410 out.length--;
50411 }
50412
50413 return out.strip();
50414};
50415
50416BN.prototype._bigMulTo = function _bigMulTo(num, out) {
50417 out.sign = num.sign !== this.sign;
50418 out.length = this.length + num.length;
50419
50420 var carry = 0;
50421 var hncarry = 0;
50422 for (var k = 0; k < out.length - 1; k++) {
50423 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
50424 // note that ncarry could be >= 0x3ffffff
50425 var ncarry = hncarry;
50426 hncarry = 0;
50427 var rword = carry & 0x3ffffff;
50428 var maxJ = Math.min(k, num.length - 1);
50429 for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
50430 var i = k - j;
50431 var a = this.words[i] | 0;
50432 var b = num.words[j] | 0;
50433 var r = a * b;
50434
50435 var lo = r & 0x3ffffff;
50436 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
50437 lo = (lo + rword) | 0;
50438 rword = lo & 0x3ffffff;
50439 ncarry = (ncarry + (lo >>> 26)) | 0;
50440
50441 hncarry += ncarry >>> 26;
50442 ncarry &= 0x3ffffff;
50443 }
50444 out.words[k] = rword;
50445 carry = ncarry;
50446 ncarry = hncarry;
50447 }
50448 if (carry !== 0) {
50449 out.words[k] = carry;
50450 } else {
50451 out.length--;
50452 }
50453
50454 return out.strip();
50455};
50456
50457BN.prototype.mulTo = function mulTo(num, out) {
50458 var res;
50459 if (this.length + num.length < 63)
50460 res = this._smallMulTo(num, out);
50461 else
50462 res = this._bigMulTo(num, out);
50463 return res;
50464};
50465
50466// Multiply `this` by `num`
50467BN.prototype.mul = function mul(num) {
50468 var out = new BN(null);
50469 out.words = new Array(this.length + num.length);
50470 return this.mulTo(num, out);
50471};
50472
50473// In-place Multiplication
50474BN.prototype.imul = function imul(num) {
50475 if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
50476 this.words[0] = 0;
50477 this.length = 1;
50478 return this;
50479 }
50480
50481 var tlen = this.length;
50482 var nlen = num.length;
50483
50484 this.sign = num.sign !== this.sign;
50485 this.length = this.length + num.length;
50486 this.words[this.length - 1] = 0;
50487
50488 for (var k = this.length - 2; k >= 0; k--) {
50489 // Sum all words with the same `i + j = k` and accumulate `carry`,
50490 // note that carry could be >= 0x3ffffff
50491 var carry = 0;
50492 var rword = 0;
50493 var maxJ = Math.min(k, nlen - 1);
50494 for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
50495 var i = k - j;
50496 var a = this.words[i];
50497 var b = num.words[j];
50498 var r = a * b;
50499
50500 var lo = r & 0x3ffffff;
50501 carry += (r / 0x4000000) | 0;
50502 lo += rword;
50503 rword = lo & 0x3ffffff;
50504 carry += lo >>> 26;
50505 }
50506 this.words[k] = rword;
50507 this.words[k + 1] += carry;
50508 carry = 0;
50509 }
50510
50511 // Propagate overflows
50512 var carry = 0;
50513 for (var i = 1; i < this.length; i++) {
50514 var w = this.words[i] + carry;
50515 this.words[i] = w & 0x3ffffff;
50516 carry = w >>> 26;
50517 }
50518
50519 return this.strip();
50520};
50521
50522BN.prototype.imuln = function imuln(num) {
50523 assert(typeof num === 'number');
50524
50525 // Carry
50526 var carry = 0;
50527 for (var i = 0; i < this.length; i++) {
50528 var w = this.words[i] * num;
50529 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
50530 carry >>= 26;
50531 carry += (w / 0x4000000) | 0;
50532 // NOTE: lo is 27bit maximum
50533 carry += lo >>> 26;
50534 this.words[i] = lo & 0x3ffffff;
50535 }
50536
50537 if (carry !== 0) {
50538 this.words[i] = carry;
50539 this.length++;
50540 }
50541
50542 return this;
50543};
50544
50545BN.prototype.muln = function muln(num) {
50546 return this.clone().imuln(num);
50547};
50548
50549// `this` * `this`
50550BN.prototype.sqr = function sqr() {
50551 return this.mul(this);
50552};
50553
50554// `this` * `this` in-place
50555BN.prototype.isqr = function isqr() {
50556 return this.mul(this);
50557};
50558
50559// Shift-left in-place
50560BN.prototype.ishln = function ishln(bits) {
50561 assert(typeof bits === 'number' && bits >= 0);
50562 var r = bits % 26;
50563 var s = (bits - r) / 26;
50564 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
50565
50566 if (r !== 0) {
50567 var carry = 0;
50568 for (var i = 0; i < this.length; i++) {
50569 var newCarry = this.words[i] & carryMask;
50570 var c = (this.words[i] - newCarry) << r;
50571 this.words[i] = c | carry;
50572 carry = newCarry >>> (26 - r);
50573 }
50574 if (carry) {
50575 this.words[i] = carry;
50576 this.length++;
50577 }
50578 }
50579
50580 if (s !== 0) {
50581 for (var i = this.length - 1; i >= 0; i--)
50582 this.words[i + s] = this.words[i];
50583 for (var i = 0; i < s; i++)
50584 this.words[i] = 0;
50585 this.length += s;
50586 }
50587
50588 return this.strip();
50589};
50590
50591// Shift-right in-place
50592// NOTE: `hint` is a lowest bit before trailing zeroes
50593// NOTE: if `extended` is present - it will be filled with destroyed bits
50594BN.prototype.ishrn = function ishrn(bits, hint, extended) {
50595 assert(typeof bits === 'number' && bits >= 0);
50596 var h;
50597 if (hint)
50598 h = (hint - (hint % 26)) / 26;
50599 else
50600 h = 0;
50601
50602 var r = bits % 26;
50603 var s = Math.min((bits - r) / 26, this.length);
50604 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
50605 var maskedWords = extended;
50606
50607 h -= s;
50608 h = Math.max(0, h);
50609
50610 // Extended mode, copy masked part
50611 if (maskedWords) {
50612 for (var i = 0; i < s; i++)
50613 maskedWords.words[i] = this.words[i];
50614 maskedWords.length = s;
50615 }
50616
50617 if (s === 0) {
50618 // No-op, we should not move anything at all
50619 } else if (this.length > s) {
50620 this.length -= s;
50621 for (var i = 0; i < this.length; i++)
50622 this.words[i] = this.words[i + s];
50623 } else {
50624 this.words[0] = 0;
50625 this.length = 1;
50626 }
50627
50628 var carry = 0;
50629 for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
50630 var word = this.words[i];
50631 this.words[i] = (carry << (26 - r)) | (word >>> r);
50632 carry = word & mask;
50633 }
50634
50635 // Push carried bits as a mask
50636 if (maskedWords && carry !== 0)
50637 maskedWords.words[maskedWords.length++] = carry;
50638
50639 if (this.length === 0) {
50640 this.words[0] = 0;
50641 this.length = 1;
50642 }
50643
50644 this.strip();
50645
50646 return this;
50647};
50648
50649// Shift-left
50650BN.prototype.shln = function shln(bits) {
50651 return this.clone().ishln(bits);
50652};
50653
50654// Shift-right
50655BN.prototype.shrn = function shrn(bits) {
50656 return this.clone().ishrn(bits);
50657};
50658
50659// Test if n bit is set
50660BN.prototype.testn = function testn(bit) {
50661 assert(typeof bit === 'number' && bit >= 0);
50662 var r = bit % 26;
50663 var s = (bit - r) / 26;
50664 var q = 1 << r;
50665
50666 // Fast case: bit is much higher than all existing words
50667 if (this.length <= s) {
50668 return false;
50669 }
50670
50671 // Check bit and return
50672 var w = this.words[s];
50673
50674 return !!(w & q);
50675};
50676
50677// Return only lowers bits of number (in-place)
50678BN.prototype.imaskn = function imaskn(bits) {
50679 assert(typeof bits === 'number' && bits >= 0);
50680 var r = bits % 26;
50681 var s = (bits - r) / 26;
50682
50683 assert(!this.sign, 'imaskn works only with positive numbers');
50684
50685 if (r !== 0)
50686 s++;
50687 this.length = Math.min(s, this.length);
50688
50689 if (r !== 0) {
50690 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
50691 this.words[this.length - 1] &= mask;
50692 }
50693
50694 return this.strip();
50695};
50696
50697// Return only lowers bits of number
50698BN.prototype.maskn = function maskn(bits) {
50699 return this.clone().imaskn(bits);
50700};
50701
50702// Add plain number `num` to `this`
50703BN.prototype.iaddn = function iaddn(num) {
50704 assert(typeof num === 'number');
50705 if (num < 0)
50706 return this.isubn(-num);
50707
50708 // Possible sign change
50709 if (this.sign) {
50710 if (this.length === 1 && this.words[0] < num) {
50711 this.words[0] = num - this.words[0];
50712 this.sign = false;
50713 return this;
50714 }
50715
50716 this.sign = false;
50717 this.isubn(num);
50718 this.sign = true;
50719 return this;
50720 }
50721
50722 // Add without checks
50723 return this._iaddn(num);
50724};
50725
50726BN.prototype._iaddn = function _iaddn(num) {
50727 this.words[0] += num;
50728
50729 // Carry
50730 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
50731 this.words[i] -= 0x4000000;
50732 if (i === this.length - 1)
50733 this.words[i + 1] = 1;
50734 else
50735 this.words[i + 1]++;
50736 }
50737 this.length = Math.max(this.length, i + 1);
50738
50739 return this;
50740};
50741
50742// Subtract plain number `num` from `this`
50743BN.prototype.isubn = function isubn(num) {
50744 assert(typeof num === 'number');
50745 if (num < 0)
50746 return this.iaddn(-num);
50747
50748 if (this.sign) {
50749 this.sign = false;
50750 this.iaddn(num);
50751 this.sign = true;
50752 return this;
50753 }
50754
50755 this.words[0] -= num;
50756
50757 // Carry
50758 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
50759 this.words[i] += 0x4000000;
50760 this.words[i + 1] -= 1;
50761 }
50762
50763 return this.strip();
50764};
50765
50766BN.prototype.addn = function addn(num) {
50767 return this.clone().iaddn(num);
50768};
50769
50770BN.prototype.subn = function subn(num) {
50771 return this.clone().isubn(num);
50772};
50773
50774BN.prototype.iabs = function iabs() {
50775 this.sign = false;
50776
50777 return this;
50778};
50779
50780BN.prototype.abs = function abs() {
50781 return this.clone().iabs();
50782};
50783
50784BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
50785 // Bigger storage is needed
50786 var len = num.length + shift;
50787 var i;
50788 if (this.words.length < len) {
50789 var t = new Array(len);
50790 for (var i = 0; i < this.length; i++)
50791 t[i] = this.words[i];
50792 this.words = t;
50793 } else {
50794 i = this.length;
50795 }
50796
50797 // Zeroify rest
50798 this.length = Math.max(this.length, len);
50799 for (; i < this.length; i++)
50800 this.words[i] = 0;
50801
50802 var carry = 0;
50803 for (var i = 0; i < num.length; i++) {
50804 var w = this.words[i + shift] + carry;
50805 var right = num.words[i] * mul;
50806 w -= right & 0x3ffffff;
50807 carry = (w >> 26) - ((right / 0x4000000) | 0);
50808 this.words[i + shift] = w & 0x3ffffff;
50809 }
50810 for (; i < this.length - shift; i++) {
50811 var w = this.words[i + shift] + carry;
50812 carry = w >> 26;
50813 this.words[i + shift] = w & 0x3ffffff;
50814 }
50815
50816 if (carry === 0)
50817 return this.strip();
50818
50819 // Subtraction overflow
50820 assert(carry === -1);
50821 carry = 0;
50822 for (var i = 0; i < this.length; i++) {
50823 var w = -this.words[i] + carry;
50824 carry = w >> 26;
50825 this.words[i] = w & 0x3ffffff;
50826 }
50827 this.sign = true;
50828
50829 return this.strip();
50830};
50831
50832BN.prototype._wordDiv = function _wordDiv(num, mode) {
50833 var shift = this.length - num.length;
50834
50835 var a = this.clone();
50836 var b = num;
50837
50838 // Normalize
50839 var bhi = b.words[b.length - 1];
50840 var bhiBits = this._countBits(bhi);
50841 shift = 26 - bhiBits;
50842 if (shift !== 0) {
50843 b = b.shln(shift);
50844 a.ishln(shift);
50845 bhi = b.words[b.length - 1];
50846 }
50847
50848 // Initialize quotient
50849 var m = a.length - b.length;
50850 var q;
50851
50852 if (mode !== 'mod') {
50853 q = new BN(null);
50854 q.length = m + 1;
50855 q.words = new Array(q.length);
50856 for (var i = 0; i < q.length; i++)
50857 q.words[i] = 0;
50858 }
50859
50860 var diff = a.clone()._ishlnsubmul(b, 1, m);
50861 if (!diff.sign) {
50862 a = diff;
50863 if (q)
50864 q.words[m] = 1;
50865 }
50866
50867 for (var j = m - 1; j >= 0; j--) {
50868 var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
50869
50870 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
50871 // (0x7ffffff)
50872 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
50873
50874 a._ishlnsubmul(b, qj, j);
50875 while (a.sign) {
50876 qj--;
50877 a.sign = false;
50878 a._ishlnsubmul(b, 1, j);
50879 if (a.cmpn(0) !== 0)
50880 a.sign = !a.sign;
50881 }
50882 if (q)
50883 q.words[j] = qj;
50884 }
50885 if (q)
50886 q.strip();
50887 a.strip();
50888
50889 // Denormalize
50890 if (mode !== 'div' && shift !== 0)
50891 a.ishrn(shift);
50892 return { div: q ? q : null, mod: a };
50893};
50894
50895BN.prototype.divmod = function divmod(num, mode) {
50896 assert(num.cmpn(0) !== 0);
50897
50898 if (this.sign && !num.sign) {
50899 var res = this.neg().divmod(num, mode);
50900 var div;
50901 var mod;
50902 if (mode !== 'mod')
50903 div = res.div.neg();
50904 if (mode !== 'div')
50905 mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod);
50906 return {
50907 div: div,
50908 mod: mod
50909 };
50910 } else if (!this.sign && num.sign) {
50911 var res = this.divmod(num.neg(), mode);
50912 var div;
50913 if (mode !== 'mod')
50914 div = res.div.neg();
50915 return { div: div, mod: res.mod };
50916 } else if (this.sign && num.sign) {
50917 return this.neg().divmod(num.neg(), mode);
50918 }
50919
50920 // Both numbers are positive at this point
50921
50922 // Strip both numbers to approximate shift value
50923 if (num.length > this.length || this.cmp(num) < 0)
50924 return { div: new BN(0), mod: this };
50925
50926 // Very short reduction
50927 if (num.length === 1) {
50928 if (mode === 'div')
50929 return { div: this.divn(num.words[0]), mod: null };
50930 else if (mode === 'mod')
50931 return { div: null, mod: new BN(this.modn(num.words[0])) };
50932 return {
50933 div: this.divn(num.words[0]),
50934 mod: new BN(this.modn(num.words[0]))
50935 };
50936 }
50937
50938 return this._wordDiv(num, mode);
50939};
50940
50941// Find `this` / `num`
50942BN.prototype.div = function div(num) {
50943 return this.divmod(num, 'div').div;
50944};
50945
50946// Find `this` % `num`
50947BN.prototype.mod = function mod(num) {
50948 return this.divmod(num, 'mod').mod;
50949};
50950
50951// Find Round(`this` / `num`)
50952BN.prototype.divRound = function divRound(num) {
50953 var dm = this.divmod(num);
50954
50955 // Fast case - exact division
50956 if (dm.mod.cmpn(0) === 0)
50957 return dm.div;
50958
50959 var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
50960
50961 var half = num.shrn(1);
50962 var r2 = num.andln(1);
50963 var cmp = mod.cmp(half);
50964
50965 // Round down
50966 if (cmp < 0 || r2 === 1 && cmp === 0)
50967 return dm.div;
50968
50969 // Round up
50970 return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
50971};
50972
50973BN.prototype.modn = function modn(num) {
50974 assert(num <= 0x3ffffff);
50975 var p = (1 << 26) % num;
50976
50977 var acc = 0;
50978 for (var i = this.length - 1; i >= 0; i--)
50979 acc = (p * acc + this.words[i]) % num;
50980
50981 return acc;
50982};
50983
50984// In-place division by number
50985BN.prototype.idivn = function idivn(num) {
50986 assert(num <= 0x3ffffff);
50987
50988 var carry = 0;
50989 for (var i = this.length - 1; i >= 0; i--) {
50990 var w = this.words[i] + carry * 0x4000000;
50991 this.words[i] = (w / num) | 0;
50992 carry = w % num;
50993 }
50994
50995 return this.strip();
50996};
50997
50998BN.prototype.divn = function divn(num) {
50999 return this.clone().idivn(num);
51000};
51001
51002BN.prototype.egcd = function egcd(p) {
51003 assert(!p.sign);
51004 assert(p.cmpn(0) !== 0);
51005
51006 var x = this;
51007 var y = p.clone();
51008
51009 if (x.sign)
51010 x = x.mod(p);
51011 else
51012 x = x.clone();
51013
51014 // A * x + B * y = x
51015 var A = new BN(1);
51016 var B = new BN(0);
51017
51018 // C * x + D * y = y
51019 var C = new BN(0);
51020 var D = new BN(1);
51021
51022 var g = 0;
51023
51024 while (x.isEven() && y.isEven()) {
51025 x.ishrn(1);
51026 y.ishrn(1);
51027 ++g;
51028 }
51029
51030 var yp = y.clone();
51031 var xp = x.clone();
51032
51033 while (x.cmpn(0) !== 0) {
51034 while (x.isEven()) {
51035 x.ishrn(1);
51036 if (A.isEven() && B.isEven()) {
51037 A.ishrn(1);
51038 B.ishrn(1);
51039 } else {
51040 A.iadd(yp).ishrn(1);
51041 B.isub(xp).ishrn(1);
51042 }
51043 }
51044
51045 while (y.isEven()) {
51046 y.ishrn(1);
51047 if (C.isEven() && D.isEven()) {
51048 C.ishrn(1);
51049 D.ishrn(1);
51050 } else {
51051 C.iadd(yp).ishrn(1);
51052 D.isub(xp).ishrn(1);
51053 }
51054 }
51055
51056 if (x.cmp(y) >= 0) {
51057 x.isub(y);
51058 A.isub(C);
51059 B.isub(D);
51060 } else {
51061 y.isub(x);
51062 C.isub(A);
51063 D.isub(B);
51064 }
51065 }
51066
51067 return {
51068 a: C,
51069 b: D,
51070 gcd: y.ishln(g)
51071 };
51072};
51073
51074// This is reduced incarnation of the binary EEA
51075// above, designated to invert members of the
51076// _prime_ fields F(p) at a maximal speed
51077BN.prototype._invmp = function _invmp(p) {
51078 assert(!p.sign);
51079 assert(p.cmpn(0) !== 0);
51080
51081 var a = this;
51082 var b = p.clone();
51083
51084 if (a.sign)
51085 a = a.mod(p);
51086 else
51087 a = a.clone();
51088
51089 var x1 = new BN(1);
51090 var x2 = new BN(0);
51091
51092 var delta = b.clone();
51093
51094 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
51095 while (a.isEven()) {
51096 a.ishrn(1);
51097 if (x1.isEven())
51098 x1.ishrn(1);
51099 else
51100 x1.iadd(delta).ishrn(1);
51101 }
51102 while (b.isEven()) {
51103 b.ishrn(1);
51104 if (x2.isEven())
51105 x2.ishrn(1);
51106 else
51107 x2.iadd(delta).ishrn(1);
51108 }
51109 if (a.cmp(b) >= 0) {
51110 a.isub(b);
51111 x1.isub(x2);
51112 } else {
51113 b.isub(a);
51114 x2.isub(x1);
51115 }
51116 }
51117 if (a.cmpn(1) === 0)
51118 return x1;
51119 else
51120 return x2;
51121};
51122
51123BN.prototype.gcd = function gcd(num) {
51124 if (this.cmpn(0) === 0)
51125 return num.clone();
51126 if (num.cmpn(0) === 0)
51127 return this.clone();
51128
51129 var a = this.clone();
51130 var b = num.clone();
51131 a.sign = false;
51132 b.sign = false;
51133
51134 // Remove common factor of two
51135 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
51136 a.ishrn(1);
51137 b.ishrn(1);
51138 }
51139
51140 do {
51141 while (a.isEven())
51142 a.ishrn(1);
51143 while (b.isEven())
51144 b.ishrn(1);
51145
51146 var r = a.cmp(b);
51147 if (r < 0) {
51148 // Swap `a` and `b` to make `a` always bigger than `b`
51149 var t = a;
51150 a = b;
51151 b = t;
51152 } else if (r === 0 || b.cmpn(1) === 0) {
51153 break;
51154 }
51155
51156 a.isub(b);
51157 } while (true);
51158
51159 return b.ishln(shift);
51160};
51161
51162// Invert number in the field F(num)
51163BN.prototype.invm = function invm(num) {
51164 return this.egcd(num).a.mod(num);
51165};
51166
51167BN.prototype.isEven = function isEven() {
51168 return (this.words[0] & 1) === 0;
51169};
51170
51171BN.prototype.isOdd = function isOdd() {
51172 return (this.words[0] & 1) === 1;
51173};
51174
51175// And first word and num
51176BN.prototype.andln = function andln(num) {
51177 return this.words[0] & num;
51178};
51179
51180// Increment at the bit position in-line
51181BN.prototype.bincn = function bincn(bit) {
51182 assert(typeof bit === 'number');
51183 var r = bit % 26;
51184 var s = (bit - r) / 26;
51185 var q = 1 << r;
51186
51187 // Fast case: bit is much higher than all existing words
51188 if (this.length <= s) {
51189 for (var i = this.length; i < s + 1; i++)
51190 this.words[i] = 0;
51191 this.words[s] |= q;
51192 this.length = s + 1;
51193 return this;
51194 }
51195
51196 // Add bit and propagate, if needed
51197 var carry = q;
51198 for (var i = s; carry !== 0 && i < this.length; i++) {
51199 var w = this.words[i];
51200 w += carry;
51201 carry = w >>> 26;
51202 w &= 0x3ffffff;
51203 this.words[i] = w;
51204 }
51205 if (carry !== 0) {
51206 this.words[i] = carry;
51207 this.length++;
51208 }
51209 return this;
51210};
51211
51212BN.prototype.cmpn = function cmpn(num) {
51213 var sign = num < 0;
51214 if (sign)
51215 num = -num;
51216
51217 if (this.sign && !sign)
51218 return -1;
51219 else if (!this.sign && sign)
51220 return 1;
51221
51222 num &= 0x3ffffff;
51223 this.strip();
51224
51225 var res;
51226 if (this.length > 1) {
51227 res = 1;
51228 } else {
51229 var w = this.words[0];
51230 res = w === num ? 0 : w < num ? -1 : 1;
51231 }
51232 if (this.sign)
51233 res = -res;
51234 return res;
51235};
51236
51237// Compare two numbers and return:
51238// 1 - if `this` > `num`
51239// 0 - if `this` == `num`
51240// -1 - if `this` < `num`
51241BN.prototype.cmp = function cmp(num) {
51242 if (this.sign && !num.sign)
51243 return -1;
51244 else if (!this.sign && num.sign)
51245 return 1;
51246
51247 var res = this.ucmp(num);
51248 if (this.sign)
51249 return -res;
51250 else
51251 return res;
51252};
51253
51254// Unsigned comparison
51255BN.prototype.ucmp = function ucmp(num) {
51256 // At this point both numbers have the same sign
51257 if (this.length > num.length)
51258 return 1;
51259 else if (this.length < num.length)
51260 return -1;
51261
51262 var res = 0;
51263 for (var i = this.length - 1; i >= 0; i--) {
51264 var a = this.words[i];
51265 var b = num.words[i];
51266
51267 if (a === b)
51268 continue;
51269 if (a < b)
51270 res = -1;
51271 else if (a > b)
51272 res = 1;
51273 break;
51274 }
51275 return res;
51276};
51277
51278//
51279// A reduce context, could be using montgomery or something better, depending
51280// on the `m` itself.
51281//
51282BN.red = function red(num) {
51283 return new Red(num);
51284};
51285
51286BN.prototype.toRed = function toRed(ctx) {
51287 assert(!this.red, 'Already a number in reduction context');
51288 assert(!this.sign, 'red works only with positives');
51289 return ctx.convertTo(this)._forceRed(ctx);
51290};
51291
51292BN.prototype.fromRed = function fromRed() {
51293 assert(this.red, 'fromRed works only with numbers in reduction context');
51294 return this.red.convertFrom(this);
51295};
51296
51297BN.prototype._forceRed = function _forceRed(ctx) {
51298 this.red = ctx;
51299 return this;
51300};
51301
51302BN.prototype.forceRed = function forceRed(ctx) {
51303 assert(!this.red, 'Already a number in reduction context');
51304 return this._forceRed(ctx);
51305};
51306
51307BN.prototype.redAdd = function redAdd(num) {
51308 assert(this.red, 'redAdd works only with red numbers');
51309 return this.red.add(this, num);
51310};
51311
51312BN.prototype.redIAdd = function redIAdd(num) {
51313 assert(this.red, 'redIAdd works only with red numbers');
51314 return this.red.iadd(this, num);
51315};
51316
51317BN.prototype.redSub = function redSub(num) {
51318 assert(this.red, 'redSub works only with red numbers');
51319 return this.red.sub(this, num);
51320};
51321
51322BN.prototype.redISub = function redISub(num) {
51323 assert(this.red, 'redISub works only with red numbers');
51324 return this.red.isub(this, num);
51325};
51326
51327BN.prototype.redShl = function redShl(num) {
51328 assert(this.red, 'redShl works only with red numbers');
51329 return this.red.shl(this, num);
51330};
51331
51332BN.prototype.redMul = function redMul(num) {
51333 assert(this.red, 'redMul works only with red numbers');
51334 this.red._verify2(this, num);
51335 return this.red.mul(this, num);
51336};
51337
51338BN.prototype.redIMul = function redIMul(num) {
51339 assert(this.red, 'redMul works only with red numbers');
51340 this.red._verify2(this, num);
51341 return this.red.imul(this, num);
51342};
51343
51344BN.prototype.redSqr = function redSqr() {
51345 assert(this.red, 'redSqr works only with red numbers');
51346 this.red._verify1(this);
51347 return this.red.sqr(this);
51348};
51349
51350BN.prototype.redISqr = function redISqr() {
51351 assert(this.red, 'redISqr works only with red numbers');
51352 this.red._verify1(this);
51353 return this.red.isqr(this);
51354};
51355
51356// Square root over p
51357BN.prototype.redSqrt = function redSqrt() {
51358 assert(this.red, 'redSqrt works only with red numbers');
51359 this.red._verify1(this);
51360 return this.red.sqrt(this);
51361};
51362
51363BN.prototype.redInvm = function redInvm() {
51364 assert(this.red, 'redInvm works only with red numbers');
51365 this.red._verify1(this);
51366 return this.red.invm(this);
51367};
51368
51369// Return negative clone of `this` % `red modulo`
51370BN.prototype.redNeg = function redNeg() {
51371 assert(this.red, 'redNeg works only with red numbers');
51372 this.red._verify1(this);
51373 return this.red.neg(this);
51374};
51375
51376BN.prototype.redPow = function redPow(num) {
51377 assert(this.red && !num.red, 'redPow(normalNum)');
51378 this.red._verify1(this);
51379 return this.red.pow(this, num);
51380};
51381
51382// Prime numbers with efficient reduction
51383var primes = {
51384 k256: null,
51385 p224: null,
51386 p192: null,
51387 p25519: null
51388};
51389
51390// Pseudo-Mersenne prime
51391function MPrime(name, p) {
51392 // P = 2 ^ N - K
51393 this.name = name;
51394 this.p = new BN(p, 16);
51395 this.n = this.p.bitLength();
51396 this.k = new BN(1).ishln(this.n).isub(this.p);
51397
51398 this.tmp = this._tmp();
51399}
51400
51401MPrime.prototype._tmp = function _tmp() {
51402 var tmp = new BN(null);
51403 tmp.words = new Array(Math.ceil(this.n / 13));
51404 return tmp;
51405};
51406
51407MPrime.prototype.ireduce = function ireduce(num) {
51408 // Assumes that `num` is less than `P^2`
51409 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
51410 var r = num;
51411 var rlen;
51412
51413 do {
51414 this.split(r, this.tmp);
51415 r = this.imulK(r);
51416 r = r.iadd(this.tmp);
51417 rlen = r.bitLength();
51418 } while (rlen > this.n);
51419
51420 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
51421 if (cmp === 0) {
51422 r.words[0] = 0;
51423 r.length = 1;
51424 } else if (cmp > 0) {
51425 r.isub(this.p);
51426 } else {
51427 r.strip();
51428 }
51429
51430 return r;
51431};
51432
51433MPrime.prototype.split = function split(input, out) {
51434 input.ishrn(this.n, 0, out);
51435};
51436
51437MPrime.prototype.imulK = function imulK(num) {
51438 return num.imul(this.k);
51439};
51440
51441function K256() {
51442 MPrime.call(
51443 this,
51444 'k256',
51445 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
51446}
51447inherits(K256, MPrime);
51448
51449K256.prototype.split = function split(input, output) {
51450 // 256 = 9 * 26 + 22
51451 var mask = 0x3fffff;
51452
51453 var outLen = Math.min(input.length, 9);
51454 for (var i = 0; i < outLen; i++)
51455 output.words[i] = input.words[i];
51456 output.length = outLen;
51457
51458 if (input.length <= 9) {
51459 input.words[0] = 0;
51460 input.length = 1;
51461 return;
51462 }
51463
51464 // Shift by 9 limbs
51465 var prev = input.words[9];
51466 output.words[output.length++] = prev & mask;
51467
51468 for (var i = 10; i < input.length; i++) {
51469 var next = input.words[i];
51470 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
51471 prev = next;
51472 }
51473 input.words[i - 10] = prev >>> 22;
51474 input.length -= 9;
51475};
51476
51477K256.prototype.imulK = function imulK(num) {
51478 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
51479 num.words[num.length] = 0;
51480 num.words[num.length + 1] = 0;
51481 num.length += 2;
51482
51483 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
51484 var hi;
51485 var lo = 0;
51486 for (var i = 0; i < num.length; i++) {
51487 var w = num.words[i];
51488 hi = w * 0x40;
51489 lo += w * 0x3d1;
51490 hi += (lo / 0x4000000) | 0;
51491 lo &= 0x3ffffff;
51492
51493 num.words[i] = lo;
51494
51495 lo = hi;
51496 }
51497
51498 // Fast length reduction
51499 if (num.words[num.length - 1] === 0) {
51500 num.length--;
51501 if (num.words[num.length - 1] === 0)
51502 num.length--;
51503 }
51504 return num;
51505};
51506
51507function P224() {
51508 MPrime.call(
51509 this,
51510 'p224',
51511 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
51512}
51513inherits(P224, MPrime);
51514
51515function P192() {
51516 MPrime.call(
51517 this,
51518 'p192',
51519 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
51520}
51521inherits(P192, MPrime);
51522
51523function P25519() {
51524 // 2 ^ 255 - 19
51525 MPrime.call(
51526 this,
51527 '25519',
51528 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
51529}
51530inherits(P25519, MPrime);
51531
51532P25519.prototype.imulK = function imulK(num) {
51533 // K = 0x13
51534 var carry = 0;
51535 for (var i = 0; i < num.length; i++) {
51536 var hi = num.words[i] * 0x13 + carry;
51537 var lo = hi & 0x3ffffff;
51538 hi >>>= 26;
51539
51540 num.words[i] = lo;
51541 carry = hi;
51542 }
51543 if (carry !== 0)
51544 num.words[num.length++] = carry;
51545 return num;
51546};
51547
51548// Exported mostly for testing purposes, use plain name instead
51549BN._prime = function prime(name) {
51550 // Cached version of prime
51551 if (primes[name])
51552 return primes[name];
51553
51554 var prime;
51555 if (name === 'k256')
51556 prime = new K256();
51557 else if (name === 'p224')
51558 prime = new P224();
51559 else if (name === 'p192')
51560 prime = new P192();
51561 else if (name === 'p25519')
51562 prime = new P25519();
51563 else
51564 throw new Error('Unknown prime ' + name);
51565 primes[name] = prime;
51566
51567 return prime;
51568};
51569
51570//
51571// Base reduction engine
51572//
51573function Red(m) {
51574 if (typeof m === 'string') {
51575 var prime = BN._prime(m);
51576 this.m = prime.p;
51577 this.prime = prime;
51578 } else {
51579 this.m = m;
51580 this.prime = null;
51581 }
51582}
51583
51584Red.prototype._verify1 = function _verify1(a) {
51585 assert(!a.sign, 'red works only with positives');
51586 assert(a.red, 'red works only with red numbers');
51587};
51588
51589Red.prototype._verify2 = function _verify2(a, b) {
51590 assert(!a.sign && !b.sign, 'red works only with positives');
51591 assert(a.red && a.red === b.red,
51592 'red works only with red numbers');
51593};
51594
51595Red.prototype.imod = function imod(a) {
51596 if (this.prime)
51597 return this.prime.ireduce(a)._forceRed(this);
51598 return a.mod(this.m)._forceRed(this);
51599};
51600
51601Red.prototype.neg = function neg(a) {
51602 var r = a.clone();
51603 r.sign = !r.sign;
51604 return r.iadd(this.m)._forceRed(this);
51605};
51606
51607Red.prototype.add = function add(a, b) {
51608 this._verify2(a, b);
51609
51610 var res = a.add(b);
51611 if (res.cmp(this.m) >= 0)
51612 res.isub(this.m);
51613 return res._forceRed(this);
51614};
51615
51616Red.prototype.iadd = function iadd(a, b) {
51617 this._verify2(a, b);
51618
51619 var res = a.iadd(b);
51620 if (res.cmp(this.m) >= 0)
51621 res.isub(this.m);
51622 return res;
51623};
51624
51625Red.prototype.sub = function sub(a, b) {
51626 this._verify2(a, b);
51627
51628 var res = a.sub(b);
51629 if (res.cmpn(0) < 0)
51630 res.iadd(this.m);
51631 return res._forceRed(this);
51632};
51633
51634Red.prototype.isub = function isub(a, b) {
51635 this._verify2(a, b);
51636
51637 var res = a.isub(b);
51638 if (res.cmpn(0) < 0)
51639 res.iadd(this.m);
51640 return res;
51641};
51642
51643Red.prototype.shl = function shl(a, num) {
51644 this._verify1(a);
51645 return this.imod(a.shln(num));
51646};
51647
51648Red.prototype.imul = function imul(a, b) {
51649 this._verify2(a, b);
51650 return this.imod(a.imul(b));
51651};
51652
51653Red.prototype.mul = function mul(a, b) {
51654 this._verify2(a, b);
51655 return this.imod(a.mul(b));
51656};
51657
51658Red.prototype.isqr = function isqr(a) {
51659 return this.imul(a, a);
51660};
51661
51662Red.prototype.sqr = function sqr(a) {
51663 return this.mul(a, a);
51664};
51665
51666Red.prototype.sqrt = function sqrt(a) {
51667 if (a.cmpn(0) === 0)
51668 return a.clone();
51669
51670 var mod3 = this.m.andln(3);
51671 assert(mod3 % 2 === 1);
51672
51673 // Fast case
51674 if (mod3 === 3) {
51675 var pow = this.m.add(new BN(1)).ishrn(2);
51676 var r = this.pow(a, pow);
51677 return r;
51678 }
51679
51680 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
51681 //
51682 // Find Q and S, that Q * 2 ^ S = (P - 1)
51683 var q = this.m.subn(1);
51684 var s = 0;
51685 while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
51686 s++;
51687 q.ishrn(1);
51688 }
51689 assert(q.cmpn(0) !== 0);
51690
51691 var one = new BN(1).toRed(this);
51692 var nOne = one.redNeg();
51693
51694 // Find quadratic non-residue
51695 // NOTE: Max is such because of generalized Riemann hypothesis.
51696 var lpow = this.m.subn(1).ishrn(1);
51697 var z = this.m.bitLength();
51698 z = new BN(2 * z * z).toRed(this);
51699 while (this.pow(z, lpow).cmp(nOne) !== 0)
51700 z.redIAdd(nOne);
51701
51702 var c = this.pow(z, q);
51703 var r = this.pow(a, q.addn(1).ishrn(1));
51704 var t = this.pow(a, q);
51705 var m = s;
51706 while (t.cmp(one) !== 0) {
51707 var tmp = t;
51708 for (var i = 0; tmp.cmp(one) !== 0; i++)
51709 tmp = tmp.redSqr();
51710 assert(i < m);
51711 var b = this.pow(c, new BN(1).ishln(m - i - 1));
51712
51713 r = r.redMul(b);
51714 c = b.redSqr();
51715 t = t.redMul(c);
51716 m = i;
51717 }
51718
51719 return r;
51720};
51721
51722Red.prototype.invm = function invm(a) {
51723 var inv = a._invmp(this.m);
51724 if (inv.sign) {
51725 inv.sign = false;
51726 return this.imod(inv).redNeg();
51727 } else {
51728 return this.imod(inv);
51729 }
51730};
51731
51732Red.prototype.pow = function pow(a, num) {
51733 var w = [];
51734
51735 if (num.cmpn(0) === 0)
51736 return new BN(1);
51737
51738 var q = num.clone();
51739
51740 while (q.cmpn(0) !== 0) {
51741 w.push(q.andln(1));
51742 q.ishrn(1);
51743 }
51744
51745 // Skip leading zeroes
51746 var res = a;
51747 for (var i = 0; i < w.length; i++, res = this.sqr(res))
51748 if (w[i] !== 0)
51749 break;
51750
51751 if (++i < w.length) {
51752 for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
51753 if (w[i] === 0)
51754 continue;
51755 res = this.mul(res, q);
51756 }
51757 }
51758
51759 return res;
51760};
51761
51762Red.prototype.convertTo = function convertTo(num) {
51763 var r = num.mod(this.m);
51764 if (r === num)
51765 return r.clone();
51766 else
51767 return r;
51768};
51769
51770Red.prototype.convertFrom = function convertFrom(num) {
51771 var res = num.clone();
51772 res.red = null;
51773 return res;
51774};
51775
51776//
51777// Montgomery method engine
51778//
51779
51780BN.mont = function mont(num) {
51781 return new Mont(num);
51782};
51783
51784function Mont(m) {
51785 Red.call(this, m);
51786
51787 this.shift = this.m.bitLength();
51788 if (this.shift % 26 !== 0)
51789 this.shift += 26 - (this.shift % 26);
51790 this.r = new BN(1).ishln(this.shift);
51791 this.r2 = this.imod(this.r.sqr());
51792 this.rinv = this.r._invmp(this.m);
51793
51794 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
51795 this.minv.sign = true;
51796 this.minv = this.minv.mod(this.r);
51797}
51798inherits(Mont, Red);
51799
51800Mont.prototype.convertTo = function convertTo(num) {
51801 return this.imod(num.shln(this.shift));
51802};
51803
51804Mont.prototype.convertFrom = function convertFrom(num) {
51805 var r = this.imod(num.mul(this.rinv));
51806 r.red = null;
51807 return r;
51808};
51809
51810Mont.prototype.imul = function imul(a, b) {
51811 if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
51812 a.words[0] = 0;
51813 a.length = 1;
51814 return a;
51815 }
51816
51817 var t = a.imul(b);
51818 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
51819 var u = t.isub(c).ishrn(this.shift);
51820 var res = u;
51821 if (u.cmp(this.m) >= 0)
51822 res = u.isub(this.m);
51823 else if (u.cmpn(0) < 0)
51824 res = u.iadd(this.m);
51825
51826 return res._forceRed(this);
51827};
51828
51829Mont.prototype.mul = function mul(a, b) {
51830 if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
51831 return new BN(0)._forceRed(this);
51832
51833 var t = a.mul(b);
51834 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
51835 var u = t.isub(c).ishrn(this.shift);
51836 var res = u;
51837 if (u.cmp(this.m) >= 0)
51838 res = u.isub(this.m);
51839 else if (u.cmpn(0) < 0)
51840 res = u.iadd(this.m);
51841
51842 return res._forceRed(this);
51843};
51844
51845Mont.prototype.invm = function invm(a) {
51846 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
51847 var res = this.imod(a._invmp(this.m).mul(this.r2));
51848 return res._forceRed(this);
51849};
51850
51851})(typeof module === 'undefined' || module, this);
51852}, {}],296: [function (exports, require, module, global) {var asn1 = require('../asn1');
51853var inherits = require('inherits');
51854
51855var api = exports;
51856
51857api.define = function define(name, body) {
51858 return new Entity(name, body);
51859};
51860
51861function Entity(name, body) {
51862 this.name = name;
51863 this.body = body;
51864
51865 this.decoders = {};
51866 this.encoders = {};
51867};
51868
51869Entity.prototype._createNamed = function createNamed(base) {
51870 var named;
51871 try {
51872 named = require('vm').runInThisContext(
51873 '(function ' + this.name + '(entity) {\n' +
51874 ' this._initNamed(entity);\n' +
51875 '})'
51876 );
51877 } catch (e) {
51878 named = function (entity) {
51879 this._initNamed(entity);
51880 };
51881 }
51882 inherits(named, base);
51883 named.prototype._initNamed = function initnamed(entity) {
51884 base.call(this, entity);
51885 };
51886
51887 return new named(this);
51888};
51889
51890Entity.prototype._getDecoder = function _getDecoder(enc) {
51891 // Lazily create decoder
51892 if (!this.decoders.hasOwnProperty(enc))
51893 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
51894 return this.decoders[enc];
51895};
51896
51897Entity.prototype.decode = function decode(data, enc, options) {
51898 return this._getDecoder(enc).decode(data, options);
51899};
51900
51901Entity.prototype._getEncoder = function _getEncoder(enc) {
51902 // Lazily create encoder
51903 if (!this.encoders.hasOwnProperty(enc))
51904 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
51905 return this.encoders[enc];
51906};
51907
51908Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
51909 return this._getEncoder(enc).encode(data, reporter);
51910};
51911}, {"../asn1":294,"inherits":149,"vm":231}],297: [function (exports, require, module, global) {var base = exports;
51912
51913base.Reporter = require('./reporter').Reporter;
51914base.DecoderBuffer = require('./buffer').DecoderBuffer;
51915base.EncoderBuffer = require('./buffer').EncoderBuffer;
51916base.Node = require('./node');
51917}, {"./reporter":298,"./buffer":299,"./node":300}],298: [function (exports, require, module, global) {var inherits = require('inherits');
51918
51919function Reporter(options) {
51920 this._reporterState = {
51921 obj: null,
51922 path: [],
51923 options: options || {},
51924 errors: []
51925 };
51926}
51927exports.Reporter = Reporter;
51928
51929Reporter.prototype.isError = function isError(obj) {
51930 return obj instanceof ReporterError;
51931};
51932
51933Reporter.prototype.save = function save() {
51934 var state = this._reporterState;
51935
51936 return { obj: state.obj, pathLen: state.path.length };
51937};
51938
51939Reporter.prototype.restore = function restore(data) {
51940 var state = this._reporterState;
51941
51942 state.obj = data.obj;
51943 state.path = state.path.slice(0, data.pathLen);
51944};
51945
51946Reporter.prototype.enterKey = function enterKey(key) {
51947 return this._reporterState.path.push(key);
51948};
51949
51950Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
51951 var state = this._reporterState;
51952
51953 state.path = state.path.slice(0, index - 1);
51954 if (state.obj !== null)
51955 state.obj[key] = value;
51956};
51957
51958Reporter.prototype.enterObject = function enterObject() {
51959 var state = this._reporterState;
51960
51961 var prev = state.obj;
51962 state.obj = {};
51963 return prev;
51964};
51965
51966Reporter.prototype.leaveObject = function leaveObject(prev) {
51967 var state = this._reporterState;
51968
51969 var now = state.obj;
51970 state.obj = prev;
51971 return now;
51972};
51973
51974Reporter.prototype.error = function error(msg) {
51975 var err;
51976 var state = this._reporterState;
51977
51978 var inherited = msg instanceof ReporterError;
51979 if (inherited) {
51980 err = msg;
51981 } else {
51982 err = new ReporterError(state.path.map(function(elem) {
51983 return '[' + JSON.stringify(elem) + ']';
51984 }).join(''), msg.message || msg, msg.stack);
51985 }
51986
51987 if (!state.options.partial)
51988 throw err;
51989
51990 if (!inherited)
51991 state.errors.push(err);
51992
51993 return err;
51994};
51995
51996Reporter.prototype.wrapResult = function wrapResult(result) {
51997 var state = this._reporterState;
51998 if (!state.options.partial)
51999 return result;
52000
52001 return {
52002 result: this.isError(result) ? null : result,
52003 errors: state.errors
52004 };
52005};
52006
52007function ReporterError(path, msg) {
52008 this.path = path;
52009 this.rethrow(msg);
52010};
52011inherits(ReporterError, Error);
52012
52013ReporterError.prototype.rethrow = function rethrow(msg) {
52014 this.message = msg + ' at: ' + (this.path || '(shallow)');
52015 Error.captureStackTrace(this, ReporterError);
52016
52017 return this;
52018};
52019}, {"inherits":149}],299: [function (exports, require, module, global) {var inherits = require('inherits');
52020var Reporter = require('../base').Reporter;
52021var Buffer = require('buffer').Buffer;
52022
52023function DecoderBuffer(base, options) {
52024 Reporter.call(this, options);
52025 if (!Buffer.isBuffer(base)) {
52026 this.error('Input not Buffer');
52027 return;
52028 }
52029
52030 this.base = base;
52031 this.offset = 0;
52032 this.length = base.length;
52033}
52034inherits(DecoderBuffer, Reporter);
52035exports.DecoderBuffer = DecoderBuffer;
52036
52037DecoderBuffer.prototype.save = function save() {
52038 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
52039};
52040
52041DecoderBuffer.prototype.restore = function restore(save) {
52042 // Return skipped data
52043 var res = new DecoderBuffer(this.base);
52044 res.offset = save.offset;
52045 res.length = this.offset;
52046
52047 this.offset = save.offset;
52048 Reporter.prototype.restore.call(this, save.reporter);
52049
52050 return res;
52051};
52052
52053DecoderBuffer.prototype.isEmpty = function isEmpty() {
52054 return this.offset === this.length;
52055};
52056
52057DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
52058 if (this.offset + 1 <= this.length)
52059 return this.base.readUInt8(this.offset++, true);
52060 else
52061 return this.error(fail || 'DecoderBuffer overrun');
52062}
52063
52064DecoderBuffer.prototype.skip = function skip(bytes, fail) {
52065 if (!(this.offset + bytes <= this.length))
52066 return this.error(fail || 'DecoderBuffer overrun');
52067
52068 var res = new DecoderBuffer(this.base);
52069
52070 // Share reporter state
52071 res._reporterState = this._reporterState;
52072
52073 res.offset = this.offset;
52074 res.length = this.offset + bytes;
52075 this.offset += bytes;
52076 return res;
52077}
52078
52079DecoderBuffer.prototype.raw = function raw(save) {
52080 return this.base.slice(save ? save.offset : this.offset, this.length);
52081}
52082
52083function EncoderBuffer(value, reporter) {
52084 if (Array.isArray(value)) {
52085 this.length = 0;
52086 this.value = value.map(function(item) {
52087 if (!(item instanceof EncoderBuffer))
52088 item = new EncoderBuffer(item, reporter);
52089 this.length += item.length;
52090 return item;
52091 }, this);
52092 } else if (typeof value === 'number') {
52093 if (!(0 <= value && value <= 0xff))
52094 return reporter.error('non-byte EncoderBuffer value');
52095 this.value = value;
52096 this.length = 1;
52097 } else if (typeof value === 'string') {
52098 this.value = value;
52099 this.length = Buffer.byteLength(value);
52100 } else if (Buffer.isBuffer(value)) {
52101 this.value = value;
52102 this.length = value.length;
52103 } else {
52104 return reporter.error('Unsupported type: ' + typeof value);
52105 }
52106}
52107exports.EncoderBuffer = EncoderBuffer;
52108
52109EncoderBuffer.prototype.join = function join(out, offset) {
52110 if (!out)
52111 out = new Buffer(this.length);
52112 if (!offset)
52113 offset = 0;
52114
52115 if (this.length === 0)
52116 return out;
52117
52118 if (Array.isArray(this.value)) {
52119 this.value.forEach(function(item) {
52120 item.join(out, offset);
52121 offset += item.length;
52122 });
52123 } else {
52124 if (typeof this.value === 'number')
52125 out[offset] = this.value;
52126 else if (typeof this.value === 'string')
52127 out.write(this.value, offset);
52128 else if (Buffer.isBuffer(this.value))
52129 this.value.copy(out, offset);
52130 offset += this.length;
52131 }
52132
52133 return out;
52134};
52135}, {"inherits":149,"../base":297,"buffer":29}],300: [function (exports, require, module, global) {var Reporter = require('../base').Reporter;
52136var EncoderBuffer = require('../base').EncoderBuffer;
52137var assert = require('minimalistic-assert');
52138
52139// Supported tags
52140var tags = [
52141 'seq', 'seqof', 'set', 'setof', 'octstr', 'bitstr', 'objid', 'bool',
52142 'gentime', 'utctime', 'null_', 'enum', 'int', 'ia5str', 'utf8str'
52143];
52144
52145// Public methods list
52146var methods = [
52147 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
52148 'any'
52149].concat(tags);
52150
52151// Overrided methods list
52152var overrided = [
52153 '_peekTag', '_decodeTag', '_use',
52154 '_decodeStr', '_decodeObjid', '_decodeTime',
52155 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
52156
52157 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
52158 '_encodeNull', '_encodeInt', '_encodeBool'
52159];
52160
52161function Node(enc, parent) {
52162 var state = {};
52163 this._baseState = state;
52164
52165 state.enc = enc;
52166
52167 state.parent = parent || null;
52168 state.children = null;
52169
52170 // State
52171 state.tag = null;
52172 state.args = null;
52173 state.reverseArgs = null;
52174 state.choice = null;
52175 state.optional = false;
52176 state.any = false;
52177 state.obj = false;
52178 state.use = null;
52179 state.useDecoder = null;
52180 state.key = null;
52181 state['default'] = null;
52182 state.explicit = null;
52183 state.implicit = null;
52184
52185 // Should create new instance on each method
52186 if (!state.parent) {
52187 state.children = [];
52188 this._wrap();
52189 }
52190}
52191module.exports = Node;
52192
52193var stateProps = [
52194 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
52195 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
52196 'implicit'
52197];
52198
52199Node.prototype.clone = function clone() {
52200 var state = this._baseState;
52201 var cstate = {};
52202 stateProps.forEach(function(prop) {
52203 cstate[prop] = state[prop];
52204 });
52205 var res = new this.constructor(cstate.parent);
52206 res._baseState = cstate;
52207 return res;
52208};
52209
52210Node.prototype._wrap = function wrap() {
52211 var state = this._baseState;
52212 methods.forEach(function(method) {
52213 this[method] = function _wrappedMethod() {
52214 var clone = new this.constructor(this);
52215 state.children.push(clone);
52216 return clone[method].apply(clone, arguments);
52217 };
52218 }, this);
52219};
52220
52221Node.prototype._init = function init(body) {
52222 var state = this._baseState;
52223
52224 assert(state.parent === null);
52225 body.call(this);
52226
52227 // Filter children
52228 state.children = state.children.filter(function(child) {
52229 return child._baseState.parent === this;
52230 }, this);
52231 assert.equal(state.children.length, 1, 'Root node can have only one child');
52232};
52233
52234Node.prototype._useArgs = function useArgs(args) {
52235 var state = this._baseState;
52236
52237 // Filter children and args
52238 var children = args.filter(function(arg) {
52239 return arg instanceof this.constructor;
52240 }, this);
52241 args = args.filter(function(arg) {
52242 return !(arg instanceof this.constructor);
52243 }, this);
52244
52245 if (children.length !== 0) {
52246 assert(state.children === null);
52247 state.children = children;
52248
52249 // Replace parent to maintain backward link
52250 children.forEach(function(child) {
52251 child._baseState.parent = this;
52252 }, this);
52253 }
52254 if (args.length !== 0) {
52255 assert(state.args === null);
52256 state.args = args;
52257 state.reverseArgs = args.map(function(arg) {
52258 if (typeof arg !== 'object' || arg.constructor !== Object)
52259 return arg;
52260
52261 var res = {};
52262 Object.keys(arg).forEach(function(key) {
52263 if (key == (key | 0))
52264 key |= 0;
52265 var value = arg[key];
52266 res[value] = key;
52267 });
52268 return res;
52269 });
52270 }
52271};
52272
52273//
52274// Overrided methods
52275//
52276
52277overrided.forEach(function(method) {
52278 Node.prototype[method] = function _overrided() {
52279 var state = this._baseState;
52280 throw new Error(method + ' not implemented for encoding: ' + state.enc);
52281 };
52282});
52283
52284//
52285// Public methods
52286//
52287
52288tags.forEach(function(tag) {
52289 Node.prototype[tag] = function _tagMethod() {
52290 var state = this._baseState;
52291 var args = Array.prototype.slice.call(arguments);
52292
52293 assert(state.tag === null);
52294 state.tag = tag;
52295
52296 this._useArgs(args);
52297
52298 return this;
52299 };
52300});
52301
52302Node.prototype.use = function use(item) {
52303 var state = this._baseState;
52304
52305 assert(state.use === null);
52306 state.use = item;
52307
52308 return this;
52309};
52310
52311Node.prototype.optional = function optional() {
52312 var state = this._baseState;
52313
52314 state.optional = true;
52315
52316 return this;
52317};
52318
52319Node.prototype.def = function def(val) {
52320 var state = this._baseState;
52321
52322 assert(state['default'] === null);
52323 state['default'] = val;
52324 state.optional = true;
52325
52326 return this;
52327};
52328
52329Node.prototype.explicit = function explicit(num) {
52330 var state = this._baseState;
52331
52332 assert(state.explicit === null && state.implicit === null);
52333 state.explicit = num;
52334
52335 return this;
52336};
52337
52338Node.prototype.implicit = function implicit(num) {
52339 var state = this._baseState;
52340
52341 assert(state.explicit === null && state.implicit === null);
52342 state.implicit = num;
52343
52344 return this;
52345};
52346
52347Node.prototype.obj = function obj() {
52348 var state = this._baseState;
52349 var args = Array.prototype.slice.call(arguments);
52350
52351 state.obj = true;
52352
52353 if (args.length !== 0)
52354 this._useArgs(args);
52355
52356 return this;
52357};
52358
52359Node.prototype.key = function key(newKey) {
52360 var state = this._baseState;
52361
52362 assert(state.key === null);
52363 state.key = newKey;
52364
52365 return this;
52366};
52367
52368Node.prototype.any = function any() {
52369 var state = this._baseState;
52370
52371 state.any = true;
52372
52373 return this;
52374};
52375
52376Node.prototype.choice = function choice(obj) {
52377 var state = this._baseState;
52378
52379 assert(state.choice === null);
52380 state.choice = obj;
52381 this._useArgs(Object.keys(obj).map(function(key) {
52382 return obj[key];
52383 }));
52384
52385 return this;
52386};
52387
52388//
52389// Decoding
52390//
52391
52392Node.prototype._decode = function decode(input) {
52393 var state = this._baseState;
52394
52395 // Decode root node
52396 if (state.parent === null)
52397 return input.wrapResult(state.children[0]._decode(input));
52398
52399 var result = state['default'];
52400 var present = true;
52401
52402 var prevKey;
52403 if (state.key !== null)
52404 prevKey = input.enterKey(state.key);
52405
52406 // Check if tag is there
52407 if (state.optional) {
52408 var tag = null;
52409 if (state.explicit !== null)
52410 tag = state.explicit;
52411 else if (state.implicit !== null)
52412 tag = state.implicit;
52413 else if (state.tag !== null)
52414 tag = state.tag;
52415
52416 if (tag === null && !state.any) {
52417 // Trial and Error
52418 var save = input.save();
52419 try {
52420 if (state.choice === null)
52421 this._decodeGeneric(state.tag, input);
52422 else
52423 this._decodeChoice(input);
52424 present = true;
52425 } catch (e) {
52426 present = false;
52427 }
52428 input.restore(save);
52429 } else {
52430 present = this._peekTag(input, tag, state.any);
52431
52432 if (input.isError(present))
52433 return present;
52434 }
52435 }
52436
52437 // Push object on stack
52438 var prevObj;
52439 if (state.obj && present)
52440 prevObj = input.enterObject();
52441
52442 if (present) {
52443 // Unwrap explicit values
52444 if (state.explicit !== null) {
52445 var explicit = this._decodeTag(input, state.explicit);
52446 if (input.isError(explicit))
52447 return explicit;
52448 input = explicit;
52449 }
52450
52451 // Unwrap implicit and normal values
52452 if (state.use === null && state.choice === null) {
52453 if (state.any)
52454 var save = input.save();
52455 var body = this._decodeTag(
52456 input,
52457 state.implicit !== null ? state.implicit : state.tag,
52458 state.any
52459 );
52460 if (input.isError(body))
52461 return body;
52462
52463 if (state.any)
52464 result = input.raw(save);
52465 else
52466 input = body;
52467 }
52468
52469 // Select proper method for tag
52470 if (state.any)
52471 result = result;
52472 else if (state.choice === null)
52473 result = this._decodeGeneric(state.tag, input);
52474 else
52475 result = this._decodeChoice(input);
52476
52477 if (input.isError(result))
52478 return result;
52479
52480 // Decode children
52481 if (!state.any && state.choice === null && state.children !== null) {
52482 var fail = state.children.some(function decodeChildren(child) {
52483 // NOTE: We are ignoring errors here, to let parser continue with other
52484 // parts of encoded data
52485 child._decode(input);
52486 });
52487 if (fail)
52488 return err;
52489 }
52490 }
52491
52492 // Pop object
52493 if (state.obj && present)
52494 result = input.leaveObject(prevObj);
52495
52496 // Set key
52497 if (state.key !== null && (result !== null || present === true))
52498 input.leaveKey(prevKey, state.key, result);
52499
52500 return result;
52501};
52502
52503Node.prototype._decodeGeneric = function decodeGeneric(tag, input) {
52504 var state = this._baseState;
52505
52506 if (tag === 'seq' || tag === 'set')
52507 return null;
52508 if (tag === 'seqof' || tag === 'setof')
52509 return this._decodeList(input, tag, state.args[0]);
52510 else if (tag === 'octstr' || tag === 'bitstr')
52511 return this._decodeStr(input, tag);
52512 else if (tag === 'ia5str' || tag === 'utf8str')
52513 return this._decodeStr(input, tag);
52514 else if (tag === 'objid' && state.args)
52515 return this._decodeObjid(input, state.args[0], state.args[1]);
52516 else if (tag === 'objid')
52517 return this._decodeObjid(input, null, null);
52518 else if (tag === 'gentime' || tag === 'utctime')
52519 return this._decodeTime(input, tag);
52520 else if (tag === 'null_')
52521 return this._decodeNull(input);
52522 else if (tag === 'bool')
52523 return this._decodeBool(input);
52524 else if (tag === 'int' || tag === 'enum')
52525 return this._decodeInt(input, state.args && state.args[0]);
52526 else if (state.use !== null)
52527 return this._getUse(state.use, input._reporterState.obj)._decode(input);
52528 else
52529 return input.error('unknown tag: ' + tag);
52530
52531 return null;
52532};
52533
52534Node.prototype._getUse = function _getUse(entity, obj) {
52535
52536 var state = this._baseState;
52537 // Create altered use decoder if implicit is set
52538 state.useDecoder = this._use(entity, obj);
52539 assert(state.useDecoder._baseState.parent === null);
52540 state.useDecoder = state.useDecoder._baseState.children[0];
52541 if (state.implicit !== state.useDecoder._baseState.implicit) {
52542 state.useDecoder = state.useDecoder.clone();
52543 state.useDecoder._baseState.implicit = state.implicit;
52544 }
52545 return state.useDecoder;
52546};
52547
52548Node.prototype._decodeChoice = function decodeChoice(input) {
52549 var state = this._baseState;
52550 var result = null;
52551 var match = false;
52552
52553 Object.keys(state.choice).some(function(key) {
52554 var save = input.save();
52555 var node = state.choice[key];
52556 try {
52557 var value = node._decode(input);
52558 if (input.isError(value))
52559 return false;
52560
52561 result = { type: key, value: value };
52562 match = true;
52563 } catch (e) {
52564 input.restore(save);
52565 return false;
52566 }
52567 return true;
52568 }, this);
52569
52570 if (!match)
52571 return input.error('Choice not matched');
52572
52573 return result;
52574};
52575
52576//
52577// Encoding
52578//
52579
52580Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
52581 return new EncoderBuffer(data, this.reporter);
52582};
52583
52584Node.prototype._encode = function encode(data, reporter, parent) {
52585 var state = this._baseState;
52586 if (state['default'] !== null && state['default'] === data)
52587 return;
52588
52589 var result = this._encodeValue(data, reporter, parent);
52590 if (result === undefined)
52591 return;
52592
52593 if (this._skipDefault(result, reporter, parent))
52594 return;
52595
52596 return result;
52597};
52598
52599Node.prototype._encodeValue = function encode(data, reporter, parent) {
52600 var state = this._baseState;
52601
52602 // Decode root node
52603 if (state.parent === null)
52604 return state.children[0]._encode(data, reporter || new Reporter());
52605
52606 var result = null;
52607 var present = true;
52608
52609 // Set reporter to share it with a child class
52610 this.reporter = reporter;
52611
52612 // Check if data is there
52613 if (state.optional && data === undefined) {
52614 if (state['default'] !== null)
52615 data = state['default']
52616 else
52617 return;
52618 }
52619
52620 // For error reporting
52621 var prevKey;
52622
52623 // Encode children first
52624 var content = null;
52625 var primitive = false;
52626 if (state.any) {
52627 // Anything that was given is translated to buffer
52628 result = this._createEncoderBuffer(data);
52629 } else if (state.choice) {
52630 result = this._encodeChoice(data, reporter);
52631 } else if (state.children) {
52632 content = state.children.map(function(child) {
52633 if (child._baseState.tag === 'null_')
52634 return child._encode(null, reporter, data);
52635
52636 if (child._baseState.key === null)
52637 return reporter.error('Child should have a key');
52638 var prevKey = reporter.enterKey(child._baseState.key);
52639
52640 if (typeof data !== 'object')
52641 return reporter.error('Child expected, but input is not object');
52642
52643 var res = child._encode(data[child._baseState.key], reporter, data);
52644 reporter.leaveKey(prevKey);
52645
52646 return res;
52647 }, this).filter(function(child) {
52648 return child;
52649 });
52650
52651 content = this._createEncoderBuffer(content);
52652 } else {
52653 if (state.tag === 'seqof' || state.tag === 'setof') {
52654 // TODO(indutny): this should be thrown on DSL level
52655 if (!(state.args && state.args.length === 1))
52656 return reporter.error('Too many args for : ' + state.tag);
52657
52658 if (!Array.isArray(data))
52659 return reporter.error('seqof/setof, but data is not Array');
52660
52661 var child = this.clone();
52662 child._baseState.implicit = null;
52663 content = this._createEncoderBuffer(data.map(function(item) {
52664 var state = this._baseState;
52665
52666 return this._getUse(state.args[0], data)._encode(item, reporter);
52667 }, child));
52668 } else if (state.use !== null) {
52669 result = this._getUse(state.use, parent)._encode(data, reporter);
52670 } else {
52671 content = this._encodePrimitive(state.tag, data);
52672 primitive = true;
52673 }
52674 }
52675
52676 // Encode data itself
52677 var result;
52678 if (!state.any && state.choice === null) {
52679 var tag = state.implicit !== null ? state.implicit : state.tag;
52680 var cls = state.implicit === null ? 'universal' : 'context';
52681
52682 if (tag === null) {
52683 if (state.use === null)
52684 reporter.error('Tag could be ommited only for .use()');
52685 } else {
52686 if (state.use === null)
52687 result = this._encodeComposite(tag, primitive, cls, content);
52688 }
52689 }
52690
52691 // Wrap in explicit
52692 if (state.explicit !== null)
52693 result = this._encodeComposite(state.explicit, false, 'context', result);
52694
52695 return result;
52696};
52697
52698Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
52699 var state = this._baseState;
52700
52701 var node = state.choice[data.type];
52702 if (!node) {
52703 assert(
52704 false,
52705 data.type + ' not found in ' +
52706 JSON.stringify(Object.keys(state.choice)));
52707 }
52708 return node._encode(data.value, reporter);
52709};
52710
52711Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
52712 var state = this._baseState;
52713
52714 if (tag === 'octstr' || tag === 'bitstr' || tag === 'ia5str')
52715 return this._encodeStr(data, tag);
52716 else if (tag === 'utf8str')
52717 return this._encodeStr(data, tag);
52718 else if (tag === 'objid' && state.args)
52719 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
52720 else if (tag === 'objid')
52721 return this._encodeObjid(data, null, null);
52722 else if (tag === 'gentime' || tag === 'utctime')
52723 return this._encodeTime(data, tag);
52724 else if (tag === 'null_')
52725 return this._encodeNull();
52726 else if (tag === 'int' || tag === 'enum')
52727 return this._encodeInt(data, state.args && state.reverseArgs[0]);
52728 else if (tag === 'bool')
52729 return this._encodeBool(data);
52730 else
52731 throw new Error('Unsupported tag: ' + tag);
52732};
52733}, {"../base":297,"minimalistic-assert":301}],301: [function (exports, require, module, global) {module.exports = assert;
52734
52735function assert(val, msg) {
52736 if (!val)
52737 throw new Error(msg || 'Assertion failed');
52738}
52739
52740assert.equal = function assertEqual(l, r, msg) {
52741 if (l != r)
52742 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
52743};
52744}, {}],302: [function (exports, require, module, global) {var constants = exports;
52745
52746// Helper
52747constants._reverse = function reverse(map) {
52748 var res = {};
52749
52750 Object.keys(map).forEach(function(key) {
52751 // Convert key to integer if it is stringified
52752 if ((key | 0) == key)
52753 key = key | 0;
52754
52755 var value = map[key];
52756 res[value] = key;
52757 });
52758
52759 return res;
52760};
52761
52762constants.der = require('./der');
52763}, {"./der":303}],303: [function (exports, require, module, global) {var constants = require('../constants');
52764
52765exports.tagClass = {
52766 0: 'universal',
52767 1: 'application',
52768 2: 'context',
52769 3: 'private'
52770};
52771exports.tagClassByName = constants._reverse(exports.tagClass);
52772
52773exports.tag = {
52774 0x00: 'end',
52775 0x01: 'bool',
52776 0x02: 'int',
52777 0x03: 'bitstr',
52778 0x04: 'octstr',
52779 0x05: 'null_',
52780 0x06: 'objid',
52781 0x07: 'objDesc',
52782 0x08: 'external',
52783 0x09: 'real',
52784 0x0a: 'enum',
52785 0x0b: 'embed',
52786 0x0c: 'utf8str',
52787 0x0d: 'relativeOid',
52788 0x10: 'seq',
52789 0x11: 'set',
52790 0x12: 'numstr',
52791 0x13: 'printstr',
52792 0x14: 't61str',
52793 0x15: 'videostr',
52794 0x16: 'ia5str',
52795 0x17: 'utctime',
52796 0x18: 'gentime',
52797 0x19: 'graphstr',
52798 0x1a: 'iso646str',
52799 0x1b: 'genstr',
52800 0x1c: 'unistr',
52801 0x1d: 'charstr',
52802 0x1e: 'bmpstr'
52803};
52804exports.tagByName = constants._reverse(exports.tag);
52805}, {"../constants":302}],304: [function (exports, require, module, global) {var decoders = exports;
52806
52807decoders.der = require('./der');
52808decoders.pem = require('./pem');
52809}, {"./der":305,"./pem":306}],305: [function (exports, require, module, global) {var inherits = require('inherits');
52810
52811var asn1 = require('../../asn1');
52812var base = asn1.base;
52813var bignum = asn1.bignum;
52814
52815// Import DER constants
52816var der = asn1.constants.der;
52817
52818function DERDecoder(entity) {
52819 this.enc = 'der';
52820 this.name = entity.name;
52821 this.entity = entity;
52822
52823 // Construct base tree
52824 this.tree = new DERNode();
52825 this.tree._init(entity.body);
52826};
52827module.exports = DERDecoder;
52828
52829DERDecoder.prototype.decode = function decode(data, options) {
52830 if (!(data instanceof base.DecoderBuffer))
52831 data = new base.DecoderBuffer(data, options);
52832
52833 return this.tree._decode(data, options);
52834};
52835
52836// Tree methods
52837
52838function DERNode(parent) {
52839 base.Node.call(this, 'der', parent);
52840}
52841inherits(DERNode, base.Node);
52842
52843DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
52844 if (buffer.isEmpty())
52845 return false;
52846
52847 var state = buffer.save();
52848 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
52849 if (buffer.isError(decodedTag))
52850 return decodedTag;
52851
52852 buffer.restore(state);
52853
52854 return decodedTag.tag === tag || decodedTag.tagStr === tag || any;
52855};
52856
52857DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
52858 var decodedTag = derDecodeTag(buffer,
52859 'Failed to decode tag of "' + tag + '"');
52860 if (buffer.isError(decodedTag))
52861 return decodedTag;
52862
52863 var len = derDecodeLen(buffer,
52864 decodedTag.primitive,
52865 'Failed to get length of "' + tag + '"');
52866
52867 // Failure
52868 if (buffer.isError(len))
52869 return len;
52870
52871 if (!any &&
52872 decodedTag.tag !== tag &&
52873 decodedTag.tagStr !== tag &&
52874 decodedTag.tagStr + 'of' !== tag) {
52875 return buffer.error('Failed to match tag: "' + tag + '"');
52876 }
52877
52878 if (decodedTag.primitive || len !== null)
52879 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
52880
52881 // Indefinite length... find END tag
52882 var state = buffer.save();
52883 var res = this._skipUntilEnd(
52884 buffer,
52885 'Failed to skip indefinite length body: "' + this.tag + '"');
52886 if (buffer.isError(res))
52887 return res;
52888
52889 len = buffer.offset - state.offset;
52890 buffer.restore(state);
52891 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
52892};
52893
52894DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
52895 while (true) {
52896 var tag = derDecodeTag(buffer, fail);
52897 if (buffer.isError(tag))
52898 return tag;
52899 var len = derDecodeLen(buffer, tag.primitive, fail);
52900 if (buffer.isError(len))
52901 return len;
52902
52903 var res;
52904 if (tag.primitive || len !== null)
52905 res = buffer.skip(len)
52906 else
52907 res = this._skipUntilEnd(buffer, fail);
52908
52909 // Failure
52910 if (buffer.isError(res))
52911 return res;
52912
52913 if (tag.tagStr === 'end')
52914 break;
52915 }
52916};
52917
52918DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder) {
52919 var result = [];
52920 while (!buffer.isEmpty()) {
52921 var possibleEnd = this._peekTag(buffer, 'end');
52922 if (buffer.isError(possibleEnd))
52923 return possibleEnd;
52924
52925 var res = decoder.decode(buffer, 'der');
52926 if (buffer.isError(res) && possibleEnd)
52927 break;
52928 result.push(res);
52929 }
52930 return result;
52931};
52932
52933DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
52934 if (tag === 'octstr') {
52935 return buffer.raw();
52936 } else if (tag === 'bitstr') {
52937 var unused = buffer.readUInt8();
52938 if (buffer.isError(unused))
52939 return unused;
52940
52941 return { unused: unused, data: buffer.raw() };
52942 } else if (tag === 'ia5str' || tag === 'utf8str') {
52943 return buffer.raw().toString();
52944 } else {
52945 return this.error('Decoding of string type: ' + tag + ' unsupported');
52946 }
52947};
52948
52949DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
52950 var identifiers = [];
52951 var ident = 0;
52952 while (!buffer.isEmpty()) {
52953 var subident = buffer.readUInt8();
52954 ident <<= 7;
52955 ident |= subident & 0x7f;
52956 if ((subident & 0x80) === 0) {
52957 identifiers.push(ident);
52958 ident = 0;
52959 }
52960 }
52961 if (subident & 0x80)
52962 identifiers.push(ident);
52963
52964 var first = (identifiers[0] / 40) | 0;
52965 var second = identifiers[0] % 40;
52966
52967 if (relative)
52968 result = identifiers;
52969 else
52970 result = [first, second].concat(identifiers.slice(1));
52971
52972 if (values)
52973 result = values[result.join(' ')];
52974
52975 return result;
52976};
52977
52978DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
52979 var str = buffer.raw().toString();
52980 if (tag === 'gentime') {
52981 var year = str.slice(0, 4) | 0;
52982 var mon = str.slice(4, 6) | 0;
52983 var day = str.slice(6, 8) | 0;
52984 var hour = str.slice(8, 10) | 0;
52985 var min = str.slice(10, 12) | 0;
52986 var sec = str.slice(12, 14) | 0;
52987 } else if (tag === 'utctime') {
52988 var year = str.slice(0, 2) | 0;
52989 var mon = str.slice(2, 4) | 0;
52990 var day = str.slice(4, 6) | 0;
52991 var hour = str.slice(6, 8) | 0;
52992 var min = str.slice(8, 10) | 0;
52993 var sec = str.slice(10, 12) | 0;
52994 if (year < 70)
52995 year = 2000 + year;
52996 else
52997 year = 1900 + year;
52998 } else {
52999 return this.error('Decoding ' + tag + ' time is not supported yet');
53000 }
53001
53002 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
53003};
53004
53005DERNode.prototype._decodeNull = function decodeNull(buffer) {
53006 return null;
53007};
53008
53009DERNode.prototype._decodeBool = function decodeBool(buffer) {
53010 var res = buffer.readUInt8();
53011 if (buffer.isError(res))
53012 return res;
53013 else
53014 return res !== 0;
53015};
53016
53017DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
53018 // Bigint, return as it is (assume big endian)
53019 var raw = buffer.raw();
53020 var res = new bignum(raw);
53021
53022 if (values)
53023 res = values[res.toString(10)] || res;
53024
53025 return res;
53026};
53027
53028DERNode.prototype._use = function use(entity, obj) {
53029 if (typeof entity === 'function')
53030 entity = entity(obj);
53031 return entity._getDecoder('der').tree;
53032};
53033
53034// Utility methods
53035
53036function derDecodeTag(buf, fail) {
53037 var tag = buf.readUInt8(fail);
53038 if (buf.isError(tag))
53039 return tag;
53040
53041 var cls = der.tagClass[tag >> 6];
53042 var primitive = (tag & 0x20) === 0;
53043
53044 // Multi-octet tag - load
53045 if ((tag & 0x1f) === 0x1f) {
53046 var oct = tag;
53047 tag = 0;
53048 while ((oct & 0x80) === 0x80) {
53049 oct = buf.readUInt8(fail);
53050 if (buf.isError(oct))
53051 return oct;
53052
53053 tag <<= 7;
53054 tag |= oct & 0x7f;
53055 }
53056 } else {
53057 tag &= 0x1f;
53058 }
53059 var tagStr = der.tag[tag];
53060
53061 return {
53062 cls: cls,
53063 primitive: primitive,
53064 tag: tag,
53065 tagStr: tagStr
53066 };
53067}
53068
53069function derDecodeLen(buf, primitive, fail) {
53070 var len = buf.readUInt8(fail);
53071 if (buf.isError(len))
53072 return len;
53073
53074 // Indefinite form
53075 if (!primitive && len === 0x80)
53076 return null;
53077
53078 // Definite form
53079 if ((len & 0x80) === 0) {
53080 // Short form
53081 return len;
53082 }
53083
53084 // Long form
53085 var num = len & 0x7f;
53086 if (num >= 4)
53087 return buf.error('length octect is too long');
53088
53089 len = 0;
53090 for (var i = 0; i < num; i++) {
53091 len <<= 8;
53092 var j = buf.readUInt8(fail);
53093 if (buf.isError(j))
53094 return j;
53095 len |= j;
53096 }
53097
53098 return len;
53099}
53100}, {"inherits":149,"../../asn1":294}],306: [function (exports, require, module, global) {var inherits = require('inherits');
53101var Buffer = require('buffer').Buffer;
53102
53103var asn1 = require('../../asn1');
53104var DERDecoder = require('./der');
53105
53106function PEMDecoder(entity) {
53107 DERDecoder.call(this, entity);
53108 this.enc = 'pem';
53109};
53110inherits(PEMDecoder, DERDecoder);
53111module.exports = PEMDecoder;
53112
53113PEMDecoder.prototype.decode = function decode(data, options) {
53114 var lines = data.toString().split(/[\r\n]+/g);
53115
53116 var label = options.label.toUpperCase();
53117
53118 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
53119 var start = -1;
53120 var end = -1;
53121 for (var i = 0; i < lines.length; i++) {
53122 var match = lines[i].match(re);
53123 if (match === null)
53124 continue;
53125
53126 if (match[2] !== label)
53127 continue;
53128
53129 if (start === -1) {
53130 if (match[1] !== 'BEGIN')
53131 break;
53132 start = i;
53133 } else {
53134 if (match[1] !== 'END')
53135 break;
53136 end = i;
53137 break;
53138 }
53139 }
53140 if (start === -1 || end === -1)
53141 throw new Error('PEM section not found for: ' + label);
53142
53143 var base64 = lines.slice(start + 1, end).join('');
53144 // Remove excessive symbols
53145 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
53146
53147 var input = new Buffer(base64, 'base64');
53148 return DERDecoder.prototype.decode.call(this, input, options);
53149};
53150}, {"inherits":149,"buffer":29,"../../asn1":294,"./der":305}],307: [function (exports, require, module, global) {var encoders = exports;
53151
53152encoders.der = require('./der');
53153encoders.pem = require('./pem');
53154}, {"./der":308,"./pem":309}],308: [function (exports, require, module, global) {var inherits = require('inherits');
53155var Buffer = require('buffer').Buffer;
53156
53157var asn1 = require('../../asn1');
53158var base = asn1.base;
53159var bignum = asn1.bignum;
53160
53161// Import DER constants
53162var der = asn1.constants.der;
53163
53164function DEREncoder(entity) {
53165 this.enc = 'der';
53166 this.name = entity.name;
53167 this.entity = entity;
53168
53169 // Construct base tree
53170 this.tree = new DERNode();
53171 this.tree._init(entity.body);
53172};
53173module.exports = DEREncoder;
53174
53175DEREncoder.prototype.encode = function encode(data, reporter) {
53176 return this.tree._encode(data, reporter).join();
53177};
53178
53179// Tree methods
53180
53181function DERNode(parent) {
53182 base.Node.call(this, 'der', parent);
53183}
53184inherits(DERNode, base.Node);
53185
53186DERNode.prototype._encodeComposite = function encodeComposite(tag,
53187 primitive,
53188 cls,
53189 content) {
53190 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
53191
53192 // Short form
53193 if (content.length < 0x80) {
53194 var header = new Buffer(2);
53195 header[0] = encodedTag;
53196 header[1] = content.length;
53197 return this._createEncoderBuffer([ header, content ]);
53198 }
53199
53200 // Long form
53201 // Count octets required to store length
53202 var lenOctets = 1;
53203 for (var i = content.length; i >= 0x100; i >>= 8)
53204 lenOctets++;
53205
53206 var header = new Buffer(1 + 1 + lenOctets);
53207 header[0] = encodedTag;
53208 header[1] = 0x80 | lenOctets;
53209
53210 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
53211 header[i] = j & 0xff;
53212
53213 return this._createEncoderBuffer([ header, content ]);
53214};
53215
53216DERNode.prototype._encodeStr = function encodeStr(str, tag) {
53217 if (tag === 'octstr')
53218 return this._createEncoderBuffer(str);
53219 else if (tag === 'bitstr')
53220 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
53221 else if (tag === 'ia5str' || tag === 'utf8str')
53222 return this._createEncoderBuffer(str);
53223 return this.reporter.error('Encoding of string type: ' + tag +
53224 ' unsupported');
53225};
53226
53227DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
53228 if (typeof id === 'string') {
53229 if (!values)
53230 return this.reporter.error('string objid given, but no values map found');
53231 if (!values.hasOwnProperty(id))
53232 return this.reporter.error('objid not found in values map');
53233 id = values[id].split(/[\s\.]+/g);
53234 for (var i = 0; i < id.length; i++)
53235 id[i] |= 0;
53236 } else if (Array.isArray(id)) {
53237 id = id.slice();
53238 for (var i = 0; i < id.length; i++)
53239 id[i] |= 0;
53240 }
53241
53242 if (!Array.isArray(id)) {
53243 return this.reporter.error('objid() should be either array or string, ' +
53244 'got: ' + JSON.stringify(id));
53245 }
53246
53247 if (!relative) {
53248 if (id[1] >= 40)
53249 return this.reporter.error('Second objid identifier OOB');
53250 id.splice(0, 2, id[0] * 40 + id[1]);
53251 }
53252
53253 // Count number of octets
53254 var size = 0;
53255 for (var i = 0; i < id.length; i++) {
53256 var ident = id[i];
53257 for (size++; ident >= 0x80; ident >>= 7)
53258 size++;
53259 }
53260
53261 var objid = new Buffer(size);
53262 var offset = objid.length - 1;
53263 for (var i = id.length - 1; i >= 0; i--) {
53264 var ident = id[i];
53265 objid[offset--] = ident & 0x7f;
53266 while ((ident >>= 7) > 0)
53267 objid[offset--] = 0x80 | (ident & 0x7f);
53268 }
53269
53270 return this._createEncoderBuffer(objid);
53271};
53272
53273function two(num) {
53274 if (num < 10)
53275 return '0' + num;
53276 else
53277 return num;
53278}
53279
53280DERNode.prototype._encodeTime = function encodeTime(time, tag) {
53281 var str;
53282 var date = new Date(time);
53283
53284 if (tag === 'gentime') {
53285 str = [
53286 two(date.getFullYear()),
53287 two(date.getUTCMonth() + 1),
53288 two(date.getUTCDate()),
53289 two(date.getUTCHours()),
53290 two(date.getUTCMinutes()),
53291 two(date.getUTCSeconds()),
53292 'Z'
53293 ].join('');
53294 } else if (tag === 'utctime') {
53295 str = [
53296 two(date.getFullYear() % 100),
53297 two(date.getUTCMonth() + 1),
53298 two(date.getUTCDate()),
53299 two(date.getUTCHours()),
53300 two(date.getUTCMinutes()),
53301 two(date.getUTCSeconds()),
53302 'Z'
53303 ].join('');
53304 } else {
53305 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
53306 }
53307
53308 return this._encodeStr(str, 'octstr');
53309};
53310
53311DERNode.prototype._encodeNull = function encodeNull() {
53312 return this._createEncoderBuffer('');
53313};
53314
53315DERNode.prototype._encodeInt = function encodeInt(num, values) {
53316 if (typeof num === 'string') {
53317 if (!values)
53318 return this.reporter.error('String int or enum given, but no values map');
53319 if (!values.hasOwnProperty(num)) {
53320 return this.reporter.error('Values map doesn\'t contain: ' +
53321 JSON.stringify(num));
53322 }
53323 num = values[num];
53324 }
53325
53326 // Bignum, assume big endian
53327 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
53328 var numArray = num.toArray();
53329 if (num.sign === false && numArray[0] & 0x80) {
53330 numArray.unshift(0);
53331 }
53332 num = new Buffer(numArray);
53333 }
53334
53335 if (Buffer.isBuffer(num)) {
53336 var size = num.length;
53337 if (num.length === 0)
53338 size++;
53339
53340 var out = new Buffer(size);
53341 num.copy(out);
53342 if (num.length === 0)
53343 out[0] = 0
53344 return this._createEncoderBuffer(out);
53345 }
53346
53347 if (num < 0x80)
53348 return this._createEncoderBuffer(num);
53349
53350 if (num < 0x100)
53351 return this._createEncoderBuffer([0, num]);
53352
53353 var size = 1;
53354 for (var i = num; i >= 0x100; i >>= 8)
53355 size++;
53356
53357 var out = new Array(size);
53358 for (var i = out.length - 1; i >= 0; i--) {
53359 out[i] = num & 0xff;
53360 num >>= 8;
53361 }
53362 if(out[0] & 0x80) {
53363 out.unshift(0);
53364 }
53365
53366 return this._createEncoderBuffer(new Buffer(out));
53367};
53368
53369DERNode.prototype._encodeBool = function encodeBool(value) {
53370 return this._createEncoderBuffer(value ? 0xff : 0);
53371};
53372
53373DERNode.prototype._use = function use(entity, obj) {
53374 if (typeof entity === 'function')
53375 entity = entity(obj);
53376 return entity._getEncoder('der').tree;
53377};
53378
53379DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
53380 var state = this._baseState;
53381 var i;
53382 if (state['default'] === null)
53383 return false;
53384
53385 var data = dataBuffer.join();
53386 if (state.defaultBuffer === undefined)
53387 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
53388
53389 if (data.length !== state.defaultBuffer.length)
53390 return false;
53391
53392 for (i=0; i < data.length; i++)
53393 if (data[i] !== state.defaultBuffer[i])
53394 return false;
53395
53396 return true;
53397};
53398
53399// Utility methods
53400
53401function encodeTag(tag, primitive, cls, reporter) {
53402 var res;
53403
53404 if (tag === 'seqof')
53405 tag = 'seq';
53406 else if (tag === 'setof')
53407 tag = 'set';
53408
53409 if (der.tagByName.hasOwnProperty(tag))
53410 res = der.tagByName[tag];
53411 else if (typeof tag === 'number' && (tag | 0) === tag)
53412 res = tag;
53413 else
53414 return reporter.error('Unknown tag: ' + tag);
53415
53416 if (res >= 0x1f)
53417 return reporter.error('Multi-octet tag encoding unsupported');
53418
53419 if (!primitive)
53420 res |= 0x20;
53421
53422 res |= (der.tagClassByName[cls || 'universal'] << 6);
53423
53424 return res;
53425}
53426}, {"inherits":149,"buffer":29,"../../asn1":294}],309: [function (exports, require, module, global) {var inherits = require('inherits');
53427var Buffer = require('buffer').Buffer;
53428
53429var asn1 = require('../../asn1');
53430var DEREncoder = require('./der');
53431
53432function PEMEncoder(entity) {
53433 DEREncoder.call(this, entity);
53434 this.enc = 'pem';
53435};
53436inherits(PEMEncoder, DEREncoder);
53437module.exports = PEMEncoder;
53438
53439PEMEncoder.prototype.encode = function encode(data, options) {
53440 var buf = DEREncoder.prototype.encode.call(this, data);
53441
53442 var p = buf.toString('base64');
53443 var out = [ '-----BEGIN ' + options.label + '-----' ];
53444 for (var i = 0; i < p.length; i += 64)
53445 out.push(p.slice(i, i + 64));
53446 out.push('-----END ' + options.label + '-----');
53447 return out.join('\n');
53448};
53449}, {"inherits":149,"buffer":29,"../../asn1":294,"./der":308}],310: [function (exports, require, module, global) {module.exports = {"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
53450"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
53451"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
53452"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
53453"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
53454"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
53455"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
53456"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
53457"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
53458"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
53459"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
53460"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
53461}}, {}],311: [function (exports, require, module, global) {// adapted from https://github.com/apatil/pemstrip
53462var findProc = /Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\r?\n\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n/m
53463var startRegex = /^-----BEGIN (.*) KEY-----\r?\n/m
53464var fullRegex = /^-----BEGIN (.*) KEY-----\r?\n([0-9A-z\n\r\+\/\=]+)\r?\n-----END \1 KEY-----$/m
53465var evp = require('evp_bytestokey')
53466var ciphers = require('browserify-aes')
53467module.exports = function (okey, password) {
53468 var key = okey.toString()
53469 var match = key.match(findProc)
53470 var decrypted
53471 if (!match) {
53472 var match2 = key.match(fullRegex)
53473 decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64')
53474 } else {
53475 var suite = 'aes' + match[1]
53476 var iv = new Buffer(match[2], 'hex')
53477 var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64')
53478 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
53479 var out = []
53480 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
53481 out.push(cipher.update(cipherText))
53482 out.push(cipher.final())
53483 decrypted = Buffer.concat(out)
53484 }
53485 var tag = key.match(startRegex)[1] + ' KEY'
53486 return {
53487 tag: tag,
53488 data: decrypted
53489 }
53490}
53491}, {"evp_bytestokey":312,"browserify-aes":313}],312: [function (exports, require, module, global) {var md5 = require('create-hash/md5')
53492module.exports = EVP_BytesToKey
53493function EVP_BytesToKey (password, salt, keyLen, ivLen) {
53494 if (!Buffer.isBuffer(password)) {
53495 password = new Buffer(password, 'binary')
53496 }
53497 if (salt && !Buffer.isBuffer(salt)) {
53498 salt = new Buffer(salt, 'binary')
53499 }
53500 keyLen = keyLen / 8
53501 ivLen = ivLen || 0
53502 var ki = 0
53503 var ii = 0
53504 var key = new Buffer(keyLen)
53505 var iv = new Buffer(ivLen)
53506 var addmd = 0
53507 var md_buf
53508 var i
53509 var bufs = []
53510 while (true) {
53511 if (addmd++ > 0) {
53512 bufs.push(md_buf)
53513 }
53514 bufs.push(password)
53515 if (salt) {
53516 bufs.push(salt)
53517 }
53518 md_buf = md5(Buffer.concat(bufs))
53519 bufs = []
53520 i = 0
53521 if (keyLen > 0) {
53522 while (true) {
53523 if (keyLen === 0) {
53524 break
53525 }
53526 if (i === md_buf.length) {
53527 break
53528 }
53529 key[ki++] = md_buf[i]
53530 keyLen--
53531 i++
53532 }
53533 }
53534 if (ivLen > 0 && i !== md_buf.length) {
53535 while (true) {
53536 if (ivLen === 0) {
53537 break
53538 }
53539 if (i === md_buf.length) {
53540 break
53541 }
53542 iv[ii++] = md_buf[i]
53543 ivLen--
53544 i++
53545 }
53546 }
53547 if (keyLen === 0 && ivLen === 0) {
53548 break
53549 }
53550 }
53551 for (i = 0; i < md_buf.length; i++) {
53552 md_buf[i] = 0
53553 }
53554 return {
53555 key: key,
53556 iv: iv
53557 }
53558}
53559}, {"create-hash/md5":150}],313: [function (exports, require, module, global) {var ciphers = require('./encrypter')
53560exports.createCipher = exports.Cipher = ciphers.createCipher
53561exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
53562var deciphers = require('./decrypter')
53563exports.createDecipher = exports.Decipher = deciphers.createDecipher
53564exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
53565var modes = require('./modes')
53566function getCiphers () {
53567 return Object.keys(modes)
53568}
53569exports.listCiphers = exports.getCiphers = getCiphers
53570}, {"./encrypter":314,"./decrypter":329,"./modes":317}],314: [function (exports, require, module, global) {var aes = require('./aes')
53571var Transform = require('cipher-base')
53572var inherits = require('inherits')
53573var modes = require('./modes')
53574var ebtk = require('evp_bytestokey')
53575var StreamCipher = require('./streamCipher')
53576var AuthCipher = require('./authCipher')
53577inherits(Cipher, Transform)
53578function Cipher (mode, key, iv) {
53579 if (!(this instanceof Cipher)) {
53580 return new Cipher(mode, key, iv)
53581 }
53582 Transform.call(this)
53583 this._cache = new Splitter()
53584 this._cipher = new aes.AES(key)
53585 this._prev = new Buffer(iv.length)
53586 iv.copy(this._prev)
53587 this._mode = mode
53588 this._autopadding = true
53589}
53590Cipher.prototype._update = function (data) {
53591 this._cache.add(data)
53592 var chunk
53593 var thing
53594 var out = []
53595 while ((chunk = this._cache.get())) {
53596 thing = this._mode.encrypt(this, chunk)
53597 out.push(thing)
53598 }
53599 return Buffer.concat(out)
53600}
53601Cipher.prototype._final = function () {
53602 var chunk = this._cache.flush()
53603 if (this._autopadding) {
53604 chunk = this._mode.encrypt(this, chunk)
53605 this._cipher.scrub()
53606 return chunk
53607 } else if (chunk.toString('hex') !== '10101010101010101010101010101010') {
53608 this._cipher.scrub()
53609 throw new Error('data not multiple of block length')
53610 }
53611}
53612Cipher.prototype.setAutoPadding = function (setTo) {
53613 this._autopadding = !!setTo
53614}
53615
53616function Splitter () {
53617 if (!(this instanceof Splitter)) {
53618 return new Splitter()
53619 }
53620 this.cache = new Buffer('')
53621}
53622Splitter.prototype.add = function (data) {
53623 this.cache = Buffer.concat([this.cache, data])
53624}
53625
53626Splitter.prototype.get = function () {
53627 if (this.cache.length > 15) {
53628 var out = this.cache.slice(0, 16)
53629 this.cache = this.cache.slice(16)
53630 return out
53631 }
53632 return null
53633}
53634Splitter.prototype.flush = function () {
53635 var len = 16 - this.cache.length
53636 var padBuff = new Buffer(len)
53637
53638 var i = -1
53639 while (++i < len) {
53640 padBuff.writeUInt8(len, i)
53641 }
53642 var out = Buffer.concat([this.cache, padBuff])
53643 return out
53644}
53645var modelist = {
53646 ECB: require('./modes/ecb'),
53647 CBC: require('./modes/cbc'),
53648 CFB: require('./modes/cfb'),
53649 CFB8: require('./modes/cfb8'),
53650 CFB1: require('./modes/cfb1'),
53651 OFB: require('./modes/ofb'),
53652 CTR: require('./modes/ctr'),
53653 GCM: require('./modes/ctr')
53654}
53655
53656function createCipheriv (suite, password, iv) {
53657 var config = modes[suite.toLowerCase()]
53658 if (!config) {
53659 throw new TypeError('invalid suite type')
53660 }
53661 if (typeof iv === 'string') {
53662 iv = new Buffer(iv)
53663 }
53664 if (typeof password === 'string') {
53665 password = new Buffer(password)
53666 }
53667 if (password.length !== config.key / 8) {
53668 throw new TypeError('invalid key length ' + password.length)
53669 }
53670 if (iv.length !== config.iv) {
53671 throw new TypeError('invalid iv length ' + iv.length)
53672 }
53673 if (config.type === 'stream') {
53674 return new StreamCipher(modelist[config.mode], password, iv)
53675 } else if (config.type === 'auth') {
53676 return new AuthCipher(modelist[config.mode], password, iv)
53677 }
53678 return new Cipher(modelist[config.mode], password, iv)
53679}
53680function createCipher (suite, password) {
53681 var config = modes[suite.toLowerCase()]
53682 if (!config) {
53683 throw new TypeError('invalid suite type')
53684 }
53685 var keys = ebtk(password, false, config.key, config.iv)
53686 return createCipheriv(suite, keys.key, keys.iv)
53687}
53688
53689exports.createCipheriv = createCipheriv
53690exports.createCipher = createCipher
53691}, {"./aes":315,"cipher-base":316,"inherits":149,"./modes":317,"evp_bytestokey":312,"./streamCipher":318,"./authCipher":319,"./modes/ecb":322,"./modes/cbc":323,"./modes/cfb":324,"./modes/cfb8":325,"./modes/cfb1":326,"./modes/ofb":327,"./modes/ctr":328}],315: [function (exports, require, module, global) {// based on the aes implimentation in triple sec
53692// https://github.com/keybase/triplesec
53693
53694// which is in turn based on the one from crypto-js
53695// https://code.google.com/p/crypto-js/
53696
53697var uint_max = Math.pow(2, 32)
53698function fixup_uint32 (x) {
53699 var ret, x_pos
53700 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
53701 return ret
53702}
53703function scrub_vec (v) {
53704 for (var i = 0; i < v.length; v++) {
53705 v[i] = 0
53706 }
53707 return false
53708}
53709
53710function Global () {
53711 this.SBOX = []
53712 this.INV_SBOX = []
53713 this.SUB_MIX = [[], [], [], []]
53714 this.INV_SUB_MIX = [[], [], [], []]
53715 this.init()
53716 this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
53717}
53718
53719Global.prototype.init = function () {
53720 var d, i, sx, t, x, x2, x4, x8, xi, _i
53721 d = (function () {
53722 var _i, _results
53723 _results = []
53724 for (i = _i = 0; _i < 256; i = ++_i) {
53725 if (i < 128) {
53726 _results.push(i << 1)
53727 } else {
53728 _results.push((i << 1) ^ 0x11b)
53729 }
53730 }
53731 return _results
53732 })()
53733 x = 0
53734 xi = 0
53735 for (i = _i = 0; _i < 256; i = ++_i) {
53736 sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
53737 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
53738 this.SBOX[x] = sx
53739 this.INV_SBOX[sx] = x
53740 x2 = d[x]
53741 x4 = d[x2]
53742 x8 = d[x4]
53743 t = (d[sx] * 0x101) ^ (sx * 0x1010100)
53744 this.SUB_MIX[0][x] = (t << 24) | (t >>> 8)
53745 this.SUB_MIX[1][x] = (t << 16) | (t >>> 16)
53746 this.SUB_MIX[2][x] = (t << 8) | (t >>> 24)
53747 this.SUB_MIX[3][x] = t
53748 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
53749 this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
53750 this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
53751 this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
53752 this.INV_SUB_MIX[3][sx] = t
53753 if (x === 0) {
53754 x = xi = 1
53755 } else {
53756 x = x2 ^ d[d[d[x8 ^ x2]]]
53757 xi ^= d[d[xi]]
53758 }
53759 }
53760 return true
53761}
53762
53763var G = new Global()
53764
53765AES.blockSize = 4 * 4
53766
53767AES.prototype.blockSize = AES.blockSize
53768
53769AES.keySize = 256 / 8
53770
53771AES.prototype.keySize = AES.keySize
53772
53773function bufferToArray (buf) {
53774 var len = buf.length / 4
53775 var out = new Array(len)
53776 var i = -1
53777 while (++i < len) {
53778 out[i] = buf.readUInt32BE(i * 4)
53779 }
53780 return out
53781}
53782function AES (key) {
53783 this._key = bufferToArray(key)
53784 this._doReset()
53785}
53786
53787AES.prototype._doReset = function () {
53788 var invKsRow, keySize, keyWords, ksRow, ksRows, t
53789 keyWords = this._key
53790 keySize = keyWords.length
53791 this._nRounds = keySize + 6
53792 ksRows = (this._nRounds + 1) * 4
53793 this._keySchedule = []
53794 for (ksRow = 0; ksRow < ksRows; ksRow++) {
53795 this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t)
53796 }
53797 this._invKeySchedule = []
53798 for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
53799 ksRow = ksRows - invKsRow
53800 t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)]
53801 this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]]
53802 }
53803 return true
53804}
53805
53806AES.prototype.encryptBlock = function (M) {
53807 M = bufferToArray(new Buffer(M))
53808 var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX)
53809 var buf = new Buffer(16)
53810 buf.writeUInt32BE(out[0], 0)
53811 buf.writeUInt32BE(out[1], 4)
53812 buf.writeUInt32BE(out[2], 8)
53813 buf.writeUInt32BE(out[3], 12)
53814 return buf
53815}
53816
53817AES.prototype.decryptBlock = function (M) {
53818 M = bufferToArray(new Buffer(M))
53819 var temp = [M[3], M[1]]
53820 M[1] = temp[0]
53821 M[3] = temp[1]
53822 var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX)
53823 var buf = new Buffer(16)
53824 buf.writeUInt32BE(out[0], 0)
53825 buf.writeUInt32BE(out[3], 4)
53826 buf.writeUInt32BE(out[2], 8)
53827 buf.writeUInt32BE(out[1], 12)
53828 return buf
53829}
53830
53831AES.prototype.scrub = function () {
53832 scrub_vec(this._keySchedule)
53833 scrub_vec(this._invKeySchedule)
53834 scrub_vec(this._key)
53835}
53836
53837AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) {
53838 var ksRow, s0, s1, s2, s3, t0, t1, t2, t3
53839
53840 s0 = M[0] ^ keySchedule[0]
53841 s1 = M[1] ^ keySchedule[1]
53842 s2 = M[2] ^ keySchedule[2]
53843 s3 = M[3] ^ keySchedule[3]
53844 ksRow = 4
53845 for (var round = 1; round < this._nRounds; round++) {
53846 t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
53847 t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
53848 t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
53849 t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
53850 s0 = t0
53851 s1 = t1
53852 s2 = t2
53853 s3 = t3
53854 }
53855 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
53856 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
53857 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
53858 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
53859 return [
53860 fixup_uint32(t0),
53861 fixup_uint32(t1),
53862 fixup_uint32(t2),
53863 fixup_uint32(t3)
53864 ]
53865}
53866
53867exports.AES = AES
53868}, {}],316: [function (exports, require, module, global) {var Transform = require('stream').Transform
53869var inherits = require('inherits')
53870var StringDecoder = require('string_decoder').StringDecoder
53871module.exports = CipherBase
53872inherits(CipherBase, Transform)
53873function CipherBase (hashMode) {
53874 Transform.call(this)
53875 this.hashMode = typeof hashMode === 'string'
53876 if (this.hashMode) {
53877 this[hashMode] = this._finalOrDigest
53878 } else {
53879 this.final = this._finalOrDigest
53880 }
53881 this._decoder = null
53882 this._encoding = null
53883}
53884CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
53885 if (typeof data === 'string') {
53886 data = new Buffer(data, inputEnc)
53887 }
53888 var outData = this._update(data)
53889 if (this.hashMode) {
53890 return this
53891 }
53892 if (outputEnc) {
53893 outData = this._toString(outData, outputEnc)
53894 }
53895 return outData
53896}
53897
53898CipherBase.prototype.setAutoPadding = function () {}
53899
53900CipherBase.prototype.getAuthTag = function () {
53901 throw new Error('trying to get auth tag in unsupported state')
53902}
53903
53904CipherBase.prototype.setAuthTag = function () {
53905 throw new Error('trying to set auth tag in unsupported state')
53906}
53907
53908CipherBase.prototype.setAAD = function () {
53909 throw new Error('trying to set aad in unsupported state')
53910}
53911
53912CipherBase.prototype._transform = function (data, _, next) {
53913 var err
53914 try {
53915 if (this.hashMode) {
53916 this._update(data)
53917 } else {
53918 this.push(this._update(data))
53919 }
53920 } catch (e) {
53921 err = e
53922 } finally {
53923 next(err)
53924 }
53925}
53926CipherBase.prototype._flush = function (done) {
53927 var err
53928 try {
53929 this.push(this._final())
53930 } catch (e) {
53931 err = e
53932 } finally {
53933 done(err)
53934 }
53935}
53936CipherBase.prototype._finalOrDigest = function (outputEnc) {
53937 var outData = this._final() || new Buffer('')
53938 if (outputEnc) {
53939 outData = this._toString(outData, outputEnc, true)
53940 }
53941 return outData
53942}
53943
53944CipherBase.prototype._toString = function (value, enc, final) {
53945 if (!this._decoder) {
53946 this._decoder = new StringDecoder(enc)
53947 this._encoding = enc
53948 }
53949 if (this._encoding !== enc) {
53950 throw new Error('can\'t switch encodings')
53951 }
53952 var out = this._decoder.write(value)
53953 if (final) {
53954 out += this._decoder.end()
53955 }
53956 return out
53957}
53958}, {"stream":52,"inherits":149,"string_decoder":62}],317: [function (exports, require, module, global) {exports['aes-128-ecb'] = {
53959 cipher: 'AES',
53960 key: 128,
53961 iv: 0,
53962 mode: 'ECB',
53963 type: 'block'
53964}
53965exports['aes-192-ecb'] = {
53966 cipher: 'AES',
53967 key: 192,
53968 iv: 0,
53969 mode: 'ECB',
53970 type: 'block'
53971}
53972exports['aes-256-ecb'] = {
53973 cipher: 'AES',
53974 key: 256,
53975 iv: 0,
53976 mode: 'ECB',
53977 type: 'block'
53978}
53979exports['aes-128-cbc'] = {
53980 cipher: 'AES',
53981 key: 128,
53982 iv: 16,
53983 mode: 'CBC',
53984 type: 'block'
53985}
53986exports['aes-192-cbc'] = {
53987 cipher: 'AES',
53988 key: 192,
53989 iv: 16,
53990 mode: 'CBC',
53991 type: 'block'
53992}
53993exports['aes-256-cbc'] = {
53994 cipher: 'AES',
53995 key: 256,
53996 iv: 16,
53997 mode: 'CBC',
53998 type: 'block'
53999}
54000exports['aes128'] = exports['aes-128-cbc']
54001exports['aes192'] = exports['aes-192-cbc']
54002exports['aes256'] = exports['aes-256-cbc']
54003exports['aes-128-cfb'] = {
54004 cipher: 'AES',
54005 key: 128,
54006 iv: 16,
54007 mode: 'CFB',
54008 type: 'stream'
54009}
54010exports['aes-192-cfb'] = {
54011 cipher: 'AES',
54012 key: 192,
54013 iv: 16,
54014 mode: 'CFB',
54015 type: 'stream'
54016}
54017exports['aes-256-cfb'] = {
54018 cipher: 'AES',
54019 key: 256,
54020 iv: 16,
54021 mode: 'CFB',
54022 type: 'stream'
54023}
54024exports['aes-128-cfb8'] = {
54025 cipher: 'AES',
54026 key: 128,
54027 iv: 16,
54028 mode: 'CFB8',
54029 type: 'stream'
54030}
54031exports['aes-192-cfb8'] = {
54032 cipher: 'AES',
54033 key: 192,
54034 iv: 16,
54035 mode: 'CFB8',
54036 type: 'stream'
54037}
54038exports['aes-256-cfb8'] = {
54039 cipher: 'AES',
54040 key: 256,
54041 iv: 16,
54042 mode: 'CFB8',
54043 type: 'stream'
54044}
54045exports['aes-128-cfb1'] = {
54046 cipher: 'AES',
54047 key: 128,
54048 iv: 16,
54049 mode: 'CFB1',
54050 type: 'stream'
54051}
54052exports['aes-192-cfb1'] = {
54053 cipher: 'AES',
54054 key: 192,
54055 iv: 16,
54056 mode: 'CFB1',
54057 type: 'stream'
54058}
54059exports['aes-256-cfb1'] = {
54060 cipher: 'AES',
54061 key: 256,
54062 iv: 16,
54063 mode: 'CFB1',
54064 type: 'stream'
54065}
54066exports['aes-128-ofb'] = {
54067 cipher: 'AES',
54068 key: 128,
54069 iv: 16,
54070 mode: 'OFB',
54071 type: 'stream'
54072}
54073exports['aes-192-ofb'] = {
54074 cipher: 'AES',
54075 key: 192,
54076 iv: 16,
54077 mode: 'OFB',
54078 type: 'stream'
54079}
54080exports['aes-256-ofb'] = {
54081 cipher: 'AES',
54082 key: 256,
54083 iv: 16,
54084 mode: 'OFB',
54085 type: 'stream'
54086}
54087exports['aes-128-ctr'] = {
54088 cipher: 'AES',
54089 key: 128,
54090 iv: 16,
54091 mode: 'CTR',
54092 type: 'stream'
54093}
54094exports['aes-192-ctr'] = {
54095 cipher: 'AES',
54096 key: 192,
54097 iv: 16,
54098 mode: 'CTR',
54099 type: 'stream'
54100}
54101exports['aes-256-ctr'] = {
54102 cipher: 'AES',
54103 key: 256,
54104 iv: 16,
54105 mode: 'CTR',
54106 type: 'stream'
54107}
54108exports['aes-128-gcm'] = {
54109 cipher: 'AES',
54110 key: 128,
54111 iv: 12,
54112 mode: 'GCM',
54113 type: 'auth'
54114}
54115exports['aes-192-gcm'] = {
54116 cipher: 'AES',
54117 key: 192,
54118 iv: 12,
54119 mode: 'GCM',
54120 type: 'auth'
54121}
54122exports['aes-256-gcm'] = {
54123 cipher: 'AES',
54124 key: 256,
54125 iv: 12,
54126 mode: 'GCM',
54127 type: 'auth'
54128}
54129}, {}],318: [function (exports, require, module, global) {var aes = require('./aes')
54130var Transform = require('cipher-base')
54131var inherits = require('inherits')
54132
54133inherits(StreamCipher, Transform)
54134module.exports = StreamCipher
54135function StreamCipher (mode, key, iv, decrypt) {
54136 if (!(this instanceof StreamCipher)) {
54137 return new StreamCipher(mode, key, iv)
54138 }
54139 Transform.call(this)
54140 this._cipher = new aes.AES(key)
54141 this._prev = new Buffer(iv.length)
54142 this._cache = new Buffer('')
54143 this._secCache = new Buffer('')
54144 this._decrypt = decrypt
54145 iv.copy(this._prev)
54146 this._mode = mode
54147}
54148StreamCipher.prototype._update = function (chunk) {
54149 return this._mode.encrypt(this, chunk, this._decrypt)
54150}
54151StreamCipher.prototype._final = function () {
54152 this._cipher.scrub()
54153}
54154}, {"./aes":315,"cipher-base":316,"inherits":149}],319: [function (exports, require, module, global) {var aes = require('./aes')
54155var Transform = require('cipher-base')
54156var inherits = require('inherits')
54157var GHASH = require('./ghash')
54158var xor = require('buffer-xor')
54159inherits(StreamCipher, Transform)
54160module.exports = StreamCipher
54161
54162function StreamCipher (mode, key, iv, decrypt) {
54163 if (!(this instanceof StreamCipher)) {
54164 return new StreamCipher(mode, key, iv)
54165 }
54166 Transform.call(this)
54167 this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])])
54168 iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])])
54169 this._cipher = new aes.AES(key)
54170 this._prev = new Buffer(iv.length)
54171 this._cache = new Buffer('')
54172 this._secCache = new Buffer('')
54173 this._decrypt = decrypt
54174 this._alen = 0
54175 this._len = 0
54176 iv.copy(this._prev)
54177 this._mode = mode
54178 var h = new Buffer(4)
54179 h.fill(0)
54180 this._ghash = new GHASH(this._cipher.encryptBlock(h))
54181 this._authTag = null
54182 this._called = false
54183}
54184StreamCipher.prototype._update = function (chunk) {
54185 if (!this._called && this._alen) {
54186 var rump = 16 - (this._alen % 16)
54187 if (rump < 16) {
54188 rump = new Buffer(rump)
54189 rump.fill(0)
54190 this._ghash.update(rump)
54191 }
54192 }
54193 this._called = true
54194 var out = this._mode.encrypt(this, chunk)
54195 if (this._decrypt) {
54196 this._ghash.update(chunk)
54197 } else {
54198 this._ghash.update(out)
54199 }
54200 this._len += chunk.length
54201 return out
54202}
54203StreamCipher.prototype._final = function () {
54204 if (this._decrypt && !this._authTag) {
54205 throw new Error('Unsupported state or unable to authenticate data')
54206 }
54207 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
54208 if (this._decrypt) {
54209 if (xorTest(tag, this._authTag)) {
54210 throw new Error('Unsupported state or unable to authenticate data')
54211 }
54212 } else {
54213 this._authTag = tag
54214 }
54215 this._cipher.scrub()
54216}
54217StreamCipher.prototype.getAuthTag = function getAuthTag () {
54218 if (!this._decrypt && Buffer.isBuffer(this._authTag)) {
54219 return this._authTag
54220 } else {
54221 throw new Error('Attempting to get auth tag in unsupported state')
54222 }
54223}
54224StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
54225 if (this._decrypt) {
54226 this._authTag = tag
54227 } else {
54228 throw new Error('Attempting to set auth tag in unsupported state')
54229 }
54230}
54231StreamCipher.prototype.setAAD = function setAAD (buf) {
54232 if (!this._called) {
54233 this._ghash.update(buf)
54234 this._alen += buf.length
54235 } else {
54236 throw new Error('Attempting to set AAD in unsupported state')
54237 }
54238}
54239function xorTest (a, b) {
54240 var out = 0
54241 if (a.length !== b.length) {
54242 out++
54243 }
54244 var len = Math.min(a.length, b.length)
54245 var i = -1
54246 while (++i < len) {
54247 out += (a[i] ^ b[i])
54248 }
54249 return out
54250}
54251}, {"./aes":315,"cipher-base":316,"inherits":149,"./ghash":320,"buffer-xor":321}],320: [function (exports, require, module, global) {var zeros = new Buffer(16)
54252zeros.fill(0)
54253module.exports = GHASH
54254function GHASH (key) {
54255 this.h = key
54256 this.state = new Buffer(16)
54257 this.state.fill(0)
54258 this.cache = new Buffer('')
54259}
54260// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
54261// by Juho Vähä-Herttua
54262GHASH.prototype.ghash = function (block) {
54263 var i = -1
54264 while (++i < block.length) {
54265 this.state[i] ^= block[i]
54266 }
54267 this._multiply()
54268}
54269
54270GHASH.prototype._multiply = function () {
54271 var Vi = toArray(this.h)
54272 var Zi = [0, 0, 0, 0]
54273 var j, xi, lsb_Vi
54274 var i = -1
54275 while (++i < 128) {
54276 xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0
54277 if (xi) {
54278 // Z_i+1 = Z_i ^ V_i
54279 Zi = xor(Zi, Vi)
54280 }
54281
54282 // Store the value of LSB(V_i)
54283 lsb_Vi = (Vi[3] & 1) !== 0
54284
54285 // V_i+1 = V_i >> 1
54286 for (j = 3; j > 0; j--) {
54287 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
54288 }
54289 Vi[0] = Vi[0] >>> 1
54290
54291 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
54292 if (lsb_Vi) {
54293 Vi[0] = Vi[0] ^ (0xe1 << 24)
54294 }
54295 }
54296 this.state = fromArray(Zi)
54297}
54298GHASH.prototype.update = function (buf) {
54299 this.cache = Buffer.concat([this.cache, buf])
54300 var chunk
54301 while (this.cache.length >= 16) {
54302 chunk = this.cache.slice(0, 16)
54303 this.cache = this.cache.slice(16)
54304 this.ghash(chunk)
54305 }
54306}
54307GHASH.prototype.final = function (abl, bl) {
54308 if (this.cache.length) {
54309 this.ghash(Buffer.concat([this.cache, zeros], 16))
54310 }
54311 this.ghash(fromArray([
54312 0, abl,
54313 0, bl
54314 ]))
54315 return this.state
54316}
54317
54318function toArray (buf) {
54319 return [
54320 buf.readUInt32BE(0),
54321 buf.readUInt32BE(4),
54322 buf.readUInt32BE(8),
54323 buf.readUInt32BE(12)
54324 ]
54325}
54326function fromArray (out) {
54327 out = out.map(fixup_uint32)
54328 var buf = new Buffer(16)
54329 buf.writeUInt32BE(out[0], 0)
54330 buf.writeUInt32BE(out[1], 4)
54331 buf.writeUInt32BE(out[2], 8)
54332 buf.writeUInt32BE(out[3], 12)
54333 return buf
54334}
54335var uint_max = Math.pow(2, 32)
54336function fixup_uint32 (x) {
54337 var ret, x_pos
54338 ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
54339 return ret
54340}
54341function xor (a, b) {
54342 return [
54343 a[0] ^ b[0],
54344 a[1] ^ b[1],
54345 a[2] ^ b[2],
54346 a[3] ^ b[3]
54347 ]
54348}
54349}, {}],321: [function (exports, require, module, global) {module.exports = function xor (a, b) {
54350 var length = Math.min(a.length, b.length)
54351 var buffer = new Buffer(length)
54352
54353 for (var i = 0; i < length; ++i) {
54354 buffer[i] = a[i] ^ b[i]
54355 }
54356
54357 return buffer
54358}
54359}, {}],322: [function (exports, require, module, global) {exports.encrypt = function (self, block) {
54360 return self._cipher.encryptBlock(block)
54361}
54362exports.decrypt = function (self, block) {
54363 return self._cipher.decryptBlock(block)
54364}
54365}, {}],323: [function (exports, require, module, global) {var xor = require('buffer-xor')
54366
54367exports.encrypt = function (self, block) {
54368 var data = xor(block, self._prev)
54369
54370 self._prev = self._cipher.encryptBlock(data)
54371 return self._prev
54372}
54373
54374exports.decrypt = function (self, block) {
54375 var pad = self._prev
54376
54377 self._prev = block
54378 var out = self._cipher.decryptBlock(block)
54379
54380 return xor(out, pad)
54381}
54382}, {"buffer-xor":321}],324: [function (exports, require, module, global) {var xor = require('buffer-xor')
54383
54384exports.encrypt = function (self, data, decrypt) {
54385 var out = new Buffer('')
54386 var len
54387
54388 while (data.length) {
54389 if (self._cache.length === 0) {
54390 self._cache = self._cipher.encryptBlock(self._prev)
54391 self._prev = new Buffer('')
54392 }
54393
54394 if (self._cache.length <= data.length) {
54395 len = self._cache.length
54396 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
54397 data = data.slice(len)
54398 } else {
54399 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
54400 break
54401 }
54402 }
54403
54404 return out
54405}
54406function encryptStart (self, data, decrypt) {
54407 var len = data.length
54408 var out = xor(data, self._cache)
54409 self._cache = self._cache.slice(len)
54410 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
54411 return out
54412}
54413}, {"buffer-xor":321}],325: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
54414 var pad = self._cipher.encryptBlock(self._prev)
54415 var out = pad[0] ^ byteParam
54416 self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])])
54417 return out
54418}
54419exports.encrypt = function (self, chunk, decrypt) {
54420 var len = chunk.length
54421 var out = new Buffer(len)
54422 var i = -1
54423 while (++i < len) {
54424 out[i] = encryptByte(self, chunk[i], decrypt)
54425 }
54426 return out
54427}
54428}, {}],326: [function (exports, require, module, global) {function encryptByte (self, byteParam, decrypt) {
54429 var pad
54430 var i = -1
54431 var len = 8
54432 var out = 0
54433 var bit, value
54434 while (++i < len) {
54435 pad = self._cipher.encryptBlock(self._prev)
54436 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
54437 value = pad[0] ^ bit
54438 out += ((value & 0x80) >> (i % 8))
54439 self._prev = shiftIn(self._prev, decrypt ? bit : value)
54440 }
54441 return out
54442}
54443exports.encrypt = function (self, chunk, decrypt) {
54444 var len = chunk.length
54445 var out = new Buffer(len)
54446 var i = -1
54447 while (++i < len) {
54448 out[i] = encryptByte(self, chunk[i], decrypt)
54449 }
54450 return out
54451}
54452function shiftIn (buffer, value) {
54453 var len = buffer.length
54454 var i = -1
54455 var out = new Buffer(buffer.length)
54456 buffer = Buffer.concat([buffer, new Buffer([value])])
54457 while (++i < len) {
54458 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
54459 }
54460 return out
54461}
54462}, {}],327: [function (exports, require, module, global) {var xor = require('buffer-xor')
54463
54464function getBlock (self) {
54465 self._prev = self._cipher.encryptBlock(self._prev)
54466 return self._prev
54467}
54468
54469exports.encrypt = function (self, chunk) {
54470 while (self._cache.length < chunk.length) {
54471 self._cache = Buffer.concat([self._cache, getBlock(self)])
54472 }
54473
54474 var pad = self._cache.slice(0, chunk.length)
54475 self._cache = self._cache.slice(chunk.length)
54476 return xor(chunk, pad)
54477}
54478}, {"buffer-xor":321}],328: [function (exports, require, module, global) {var xor = require('buffer-xor')
54479
54480function incr32 (iv) {
54481 var len = iv.length
54482 var item
54483 while (len--) {
54484 item = iv.readUInt8(len)
54485 if (item === 255) {
54486 iv.writeUInt8(0, len)
54487 } else {
54488 item++
54489 iv.writeUInt8(item, len)
54490 break
54491 }
54492 }
54493}
54494
54495function getBlock (self) {
54496 var out = self._cipher.encryptBlock(self._prev)
54497 incr32(self._prev)
54498 return out
54499}
54500
54501exports.encrypt = function (self, chunk) {
54502 while (self._cache.length < chunk.length) {
54503 self._cache = Buffer.concat([self._cache, getBlock(self)])
54504 }
54505 var pad = self._cache.slice(0, chunk.length)
54506 self._cache = self._cache.slice(chunk.length)
54507 return xor(chunk, pad)
54508}
54509}, {"buffer-xor":321}],329: [function (exports, require, module, global) {var aes = require('./aes')
54510var Transform = require('cipher-base')
54511var inherits = require('inherits')
54512var modes = require('./modes')
54513var StreamCipher = require('./streamCipher')
54514var AuthCipher = require('./authCipher')
54515var ebtk = require('evp_bytestokey')
54516
54517inherits(Decipher, Transform)
54518function Decipher (mode, key, iv) {
54519 if (!(this instanceof Decipher)) {
54520 return new Decipher(mode, key, iv)
54521 }
54522 Transform.call(this)
54523 this._cache = new Splitter()
54524 this._last = void 0
54525 this._cipher = new aes.AES(key)
54526 this._prev = new Buffer(iv.length)
54527 iv.copy(this._prev)
54528 this._mode = mode
54529 this._autopadding = true
54530}
54531Decipher.prototype._update = function (data) {
54532 this._cache.add(data)
54533 var chunk
54534 var thing
54535 var out = []
54536 while ((chunk = this._cache.get(this._autopadding))) {
54537 thing = this._mode.decrypt(this, chunk)
54538 out.push(thing)
54539 }
54540 return Buffer.concat(out)
54541}
54542Decipher.prototype._final = function () {
54543 var chunk = this._cache.flush()
54544 if (this._autopadding) {
54545 return unpad(this._mode.decrypt(this, chunk))
54546 } else if (chunk) {
54547 throw new Error('data not multiple of block length')
54548 }
54549}
54550Decipher.prototype.setAutoPadding = function (setTo) {
54551 this._autopadding = !!setTo
54552}
54553function Splitter () {
54554 if (!(this instanceof Splitter)) {
54555 return new Splitter()
54556 }
54557 this.cache = new Buffer('')
54558}
54559Splitter.prototype.add = function (data) {
54560 this.cache = Buffer.concat([this.cache, data])
54561}
54562
54563Splitter.prototype.get = function (autoPadding) {
54564 var out
54565 if (autoPadding) {
54566 if (this.cache.length > 16) {
54567 out = this.cache.slice(0, 16)
54568 this.cache = this.cache.slice(16)
54569 return out
54570 }
54571 } else {
54572 if (this.cache.length >= 16) {
54573 out = this.cache.slice(0, 16)
54574 this.cache = this.cache.slice(16)
54575 return out
54576 }
54577 }
54578 return null
54579}
54580Splitter.prototype.flush = function () {
54581 if (this.cache.length) {
54582 return this.cache
54583 }
54584}
54585function unpad (last) {
54586 var padded = last[15]
54587 var i = -1
54588 while (++i < padded) {
54589 if (last[(i + (16 - padded))] !== padded) {
54590 throw new Error('unable to decrypt data')
54591 }
54592 }
54593 if (padded === 16) {
54594 return
54595 }
54596 return last.slice(0, 16 - padded)
54597}
54598
54599var modelist = {
54600 ECB: require('./modes/ecb'),
54601 CBC: require('./modes/cbc'),
54602 CFB: require('./modes/cfb'),
54603 CFB8: require('./modes/cfb8'),
54604 CFB1: require('./modes/cfb1'),
54605 OFB: require('./modes/ofb'),
54606 CTR: require('./modes/ctr'),
54607 GCM: require('./modes/ctr')
54608}
54609
54610function createDecipheriv (suite, password, iv) {
54611 var config = modes[suite.toLowerCase()]
54612 if (!config) {
54613 throw new TypeError('invalid suite type')
54614 }
54615 if (typeof iv === 'string') {
54616 iv = new Buffer(iv)
54617 }
54618 if (typeof password === 'string') {
54619 password = new Buffer(password)
54620 }
54621 if (password.length !== config.key / 8) {
54622 throw new TypeError('invalid key length ' + password.length)
54623 }
54624 if (iv.length !== config.iv) {
54625 throw new TypeError('invalid iv length ' + iv.length)
54626 }
54627 if (config.type === 'stream') {
54628 return new StreamCipher(modelist[config.mode], password, iv, true)
54629 } else if (config.type === 'auth') {
54630 return new AuthCipher(modelist[config.mode], password, iv, true)
54631 }
54632 return new Decipher(modelist[config.mode], password, iv)
54633}
54634
54635function createDecipher (suite, password) {
54636 var config = modes[suite.toLowerCase()]
54637 if (!config) {
54638 throw new TypeError('invalid suite type')
54639 }
54640 var keys = ebtk(password, false, config.key, config.iv)
54641 return createDecipheriv(suite, keys.key, keys.iv)
54642}
54643exports.createDecipher = createDecipher
54644exports.createDecipheriv = createDecipheriv
54645}, {"./aes":315,"cipher-base":316,"inherits":149,"./modes":317,"./streamCipher":318,"./authCipher":319,"evp_bytestokey":312,"./modes/ecb":322,"./modes/cbc":323,"./modes/cfb":324,"./modes/cfb8":325,"./modes/cfb1":326,"./modes/ofb":327,"./modes/ctr":328}],330: [function (exports, require, module, global) {var createHash = require('create-hash');
54646module.exports = function (seed, len) {
54647 var t = new Buffer('');
54648 var i = 0, c;
54649 while (t.length < len) {
54650 c = i2ops(i++);
54651 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
54652 }
54653 return t.slice(0, len);
54654};
54655
54656function i2ops(c) {
54657 var out = new Buffer(4);
54658 out.writeUInt32BE(c,0);
54659 return out;
54660}}, {"create-hash":148}],331: [function (exports, require, module, global) {module.exports = function xor(a, b) {
54661 var len = a.length;
54662 var i = -1;
54663 while (++i < len) {
54664 a[i] ^= b[i];
54665 }
54666 return a
54667};}, {}],332: [function (exports, require, module, global) {var bn = require('bn.js');
54668function withPublic(paddedMsg, key) {
54669 return new Buffer(paddedMsg
54670 .toRed(bn.mont(key.modulus))
54671 .redPow(new bn(key.publicExponent))
54672 .fromRed()
54673 .toArray());
54674}
54675
54676module.exports = withPublic;}, {"bn.js":295}],333: [function (exports, require, module, global) {var bn = require('bn.js');
54677var randomBytes = require('randombytes');
54678module.exports = crt;
54679function blind(priv) {
54680 var r = getr(priv);
54681 var blinder = r.toRed(bn.mont(priv.modulus))
54682 .redPow(new bn(priv.publicExponent)).fromRed();
54683 return {
54684 blinder: blinder,
54685 unblinder:r.invm(priv.modulus)
54686 };
54687}
54688function crt(msg, priv) {
54689 var blinds = blind(priv);
54690 var len = priv.modulus.byteLength();
54691 var mod = bn.mont(priv.modulus);
54692 var blinded = new bn(msg).mul(blinds.blinder).mod(priv.modulus);
54693 var c1 = blinded.toRed(bn.mont(priv.prime1));
54694 var c2 = blinded.toRed(bn.mont(priv.prime2));
54695 var qinv = priv.coefficient;
54696 var p = priv.prime1;
54697 var q = priv.prime2;
54698 var m1 = c1.redPow(priv.exponent1);
54699 var m2 = c2.redPow(priv.exponent2);
54700 m1 = m1.fromRed();
54701 m2 = m2.fromRed();
54702 var h = m1.isub(m2).imul(qinv).mod(p);
54703 h.imul(q);
54704 m2.iadd(h);
54705 var out = new Buffer(m2.imul(blinds.unblinder).mod(priv.modulus).toArray());
54706 if (out.length < len) {
54707 var prefix = new Buffer(len - out.length);
54708 prefix.fill(0);
54709 out = Buffer.concat([prefix, out], len);
54710 }
54711 return out;
54712}
54713crt.getr = getr;
54714function getr(priv) {
54715 var len = priv.modulus.byteLength();
54716 var r = new bn(randomBytes(len));
54717 while (r.cmp(priv.modulus) >= 0 || !r.mod(priv.prime1) || !r.mod(priv.prime2)) {
54718 r = new bn(randomBytes(len));
54719 }
54720 return r;
54721}}, {"bn.js":295,"randombytes":147}],334: [function (exports, require, module, global) {var parseKeys = require('parse-asn1');
54722var mgf = require('./mgf');
54723var xor = require('./xor');
54724var bn = require('bn.js');
54725var crt = require('browserify-rsa');
54726var createHash = require('create-hash');
54727var withPublic = require('./withPublic');
54728module.exports = function privateDecrypt(private_key, enc, reverse) {
54729 var padding;
54730 if (private_key.padding) {
54731 padding = private_key.padding;
54732 } else if (reverse) {
54733 padding = 1;
54734 } else {
54735 padding = 4;
54736 }
54737
54738 var key = parseKeys(private_key);
54739 var k = key.modulus.byteLength();
54740 if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) {
54741 throw new Error('decryption error');
54742 }
54743 var msg;
54744 if (reverse) {
54745 msg = withPublic(new bn(enc), key);
54746 } else {
54747 msg = crt(enc, key);
54748 }
54749 var zBuffer = new Buffer(k - msg.length);
54750 zBuffer.fill(0);
54751 msg = Buffer.concat([zBuffer, msg], k);
54752 if (padding === 4) {
54753 return oaep(key, msg);
54754 } else if (padding === 1) {
54755 return pkcs1(key, msg, reverse);
54756 } else if (padding === 3) {
54757 return msg;
54758 } else {
54759 throw new Error('unknown padding');
54760 }
54761};
54762
54763function oaep(key, msg){
54764 var n = key.modulus;
54765 var k = key.modulus.byteLength();
54766 var mLen = msg.length;
54767 var iHash = createHash('sha1').update(new Buffer('')).digest();
54768 var hLen = iHash.length;
54769 var hLen2 = 2 * hLen;
54770 if (msg[0] !== 0) {
54771 throw new Error('decryption error');
54772 }
54773 var maskedSeed = msg.slice(1, hLen + 1);
54774 var maskedDb = msg.slice(hLen + 1);
54775 var seed = xor(maskedSeed, mgf(maskedDb, hLen));
54776 var db = xor(maskedDb, mgf(seed, k - hLen - 1));
54777 if (compare(iHash, db.slice(0, hLen))) {
54778 throw new Error('decryption error');
54779 }
54780 var i = hLen;
54781 while (db[i] === 0) {
54782 i++;
54783 }
54784 if (db[i++] !== 1) {
54785 throw new Error('decryption error');
54786 }
54787 return db.slice(i);
54788}
54789
54790function pkcs1(key, msg, reverse){
54791 var p1 = msg.slice(0, 2);
54792 var i = 2;
54793 var status = 0;
54794 while (msg[i++] !== 0) {
54795 if (i >= msg.length) {
54796 status++;
54797 break;
54798 }
54799 }
54800 var ps = msg.slice(2, i - 1);
54801 var p2 = msg.slice(i - 1, i);
54802
54803 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){
54804 status++;
54805 }
54806 if (ps.length < 8) {
54807 status++;
54808 }
54809 if (status) {
54810 throw new Error('decryption error');
54811 }
54812 return msg.slice(i);
54813}
54814function compare(a, b){
54815 a = new Buffer(a);
54816 b = new Buffer(b);
54817 var dif = 0;
54818 var len = a.length;
54819 if (a.length !== b.length) {
54820 dif++;
54821 len = Math.min(a.length, b.length);
54822 }
54823 var i = -1;
54824 while (++i < len) {
54825 dif += (a[i] ^ b[i]);
54826 }
54827 return dif;
54828}}, {"parse-asn1":292,"./mgf":330,"./xor":331,"bn.js":295,"browserify-rsa":333,"create-hash":148,"./withPublic":332}],335: [function (exports, require, module, global) {/*
54829 Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
54830
54831 Redistribution and use in source and binary forms, with or without
54832 modification, are permitted provided that the following conditions are met:
54833
54834 * Redistributions of source code must retain the above copyright
54835 notice, this list of conditions and the following disclaimer.
54836 * Redistributions in binary form must reproduce the above copyright
54837 notice, this list of conditions and the following disclaimer in the
54838 documentation and/or other materials provided with the distribution.
54839
54840 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
54841 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54842 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54843 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
54844 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
54845 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
54846 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
54847 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
54848 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
54849 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54850*/
54851
54852(function (root, factory) {
54853 'use strict';
54854
54855 // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
54856 // Rhino, and plain browser loading.
54857
54858 /* istanbul ignore next */
54859 if (typeof define === 'function' && define.amd) {
54860 define(['exports'], factory);
54861 } else if (typeof exports !== 'undefined') {
54862 factory(exports);
54863 } else {
54864 factory((root.esprima = {}));
54865 }
54866}(this, function (exports) {
54867 'use strict';
54868
54869 var Token,
54870 TokenName,
54871 FnExprTokens,
54872 Syntax,
54873 PlaceHolders,
54874 Messages,
54875 Regex,
54876 source,
54877 strict,
54878 index,
54879 lineNumber,
54880 lineStart,
54881 hasLineTerminator,
54882 lastIndex,
54883 lastLineNumber,
54884 lastLineStart,
54885 startIndex,
54886 startLineNumber,
54887 startLineStart,
54888 scanning,
54889 length,
54890 lookahead,
54891 state,
54892 extra,
54893 isBindingElement,
54894 isAssignmentTarget,
54895 firstCoverInitializedNameError;
54896
54897 Token = {
54898 BooleanLiteral: 1,
54899 EOF: 2,
54900 Identifier: 3,
54901 Keyword: 4,
54902 NullLiteral: 5,
54903 NumericLiteral: 6,
54904 Punctuator: 7,
54905 StringLiteral: 8,
54906 RegularExpression: 9,
54907 Template: 10
54908 };
54909
54910 TokenName = {};
54911 TokenName[Token.BooleanLiteral] = 'Boolean';
54912 TokenName[Token.EOF] = '<end>';
54913 TokenName[Token.Identifier] = 'Identifier';
54914 TokenName[Token.Keyword] = 'Keyword';
54915 TokenName[Token.NullLiteral] = 'Null';
54916 TokenName[Token.NumericLiteral] = 'Numeric';
54917 TokenName[Token.Punctuator] = 'Punctuator';
54918 TokenName[Token.StringLiteral] = 'String';
54919 TokenName[Token.RegularExpression] = 'RegularExpression';
54920 TokenName[Token.Template] = 'Template';
54921
54922 // A function following one of those tokens is an expression.
54923 FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
54924 'return', 'case', 'delete', 'throw', 'void',
54925 // assignment operators
54926 '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
54927 '&=', '|=', '^=', ',',
54928 // binary/unary operators
54929 '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
54930 '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
54931 '<=', '<', '>', '!=', '!=='];
54932
54933 Syntax = {
54934 AssignmentExpression: 'AssignmentExpression',
54935 AssignmentPattern: 'AssignmentPattern',
54936 ArrayExpression: 'ArrayExpression',
54937 ArrayPattern: 'ArrayPattern',
54938 ArrowFunctionExpression: 'ArrowFunctionExpression',
54939 BlockStatement: 'BlockStatement',
54940 BinaryExpression: 'BinaryExpression',
54941 BreakStatement: 'BreakStatement',
54942 CallExpression: 'CallExpression',
54943 CatchClause: 'CatchClause',
54944 ClassBody: 'ClassBody',
54945 ClassDeclaration: 'ClassDeclaration',
54946 ClassExpression: 'ClassExpression',
54947 ConditionalExpression: 'ConditionalExpression',
54948 ContinueStatement: 'ContinueStatement',
54949 DoWhileStatement: 'DoWhileStatement',
54950 DebuggerStatement: 'DebuggerStatement',
54951 EmptyStatement: 'EmptyStatement',
54952 ExportAllDeclaration: 'ExportAllDeclaration',
54953 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
54954 ExportNamedDeclaration: 'ExportNamedDeclaration',
54955 ExportSpecifier: 'ExportSpecifier',
54956 ExpressionStatement: 'ExpressionStatement',
54957 ForStatement: 'ForStatement',
54958 ForOfStatement: 'ForOfStatement',
54959 ForInStatement: 'ForInStatement',
54960 FunctionDeclaration: 'FunctionDeclaration',
54961 FunctionExpression: 'FunctionExpression',
54962 Identifier: 'Identifier',
54963 IfStatement: 'IfStatement',
54964 ImportDeclaration: 'ImportDeclaration',
54965 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
54966 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
54967 ImportSpecifier: 'ImportSpecifier',
54968 Literal: 'Literal',
54969 LabeledStatement: 'LabeledStatement',
54970 LogicalExpression: 'LogicalExpression',
54971 MemberExpression: 'MemberExpression',
54972 MetaProperty: 'MetaProperty',
54973 MethodDefinition: 'MethodDefinition',
54974 NewExpression: 'NewExpression',
54975 ObjectExpression: 'ObjectExpression',
54976 ObjectPattern: 'ObjectPattern',
54977 Program: 'Program',
54978 Property: 'Property',
54979 RestElement: 'RestElement',
54980 ReturnStatement: 'ReturnStatement',
54981 SequenceExpression: 'SequenceExpression',
54982 SpreadElement: 'SpreadElement',
54983 Super: 'Super',
54984 SwitchCase: 'SwitchCase',
54985 SwitchStatement: 'SwitchStatement',
54986 TaggedTemplateExpression: 'TaggedTemplateExpression',
54987 TemplateElement: 'TemplateElement',
54988 TemplateLiteral: 'TemplateLiteral',
54989 ThisExpression: 'ThisExpression',
54990 ThrowStatement: 'ThrowStatement',
54991 TryStatement: 'TryStatement',
54992 UnaryExpression: 'UnaryExpression',
54993 UpdateExpression: 'UpdateExpression',
54994 VariableDeclaration: 'VariableDeclaration',
54995 VariableDeclarator: 'VariableDeclarator',
54996 WhileStatement: 'WhileStatement',
54997 WithStatement: 'WithStatement',
54998 YieldExpression: 'YieldExpression'
54999 };
55000
55001 PlaceHolders = {
55002 ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
55003 };
55004
55005 // Error messages should be identical to V8.
55006 Messages = {
55007 UnexpectedToken: 'Unexpected token %0',
55008 UnexpectedNumber: 'Unexpected number',
55009 UnexpectedString: 'Unexpected string',
55010 UnexpectedIdentifier: 'Unexpected identifier',
55011 UnexpectedReserved: 'Unexpected reserved word',
55012 UnexpectedTemplate: 'Unexpected quasi %0',
55013 UnexpectedEOS: 'Unexpected end of input',
55014 NewlineAfterThrow: 'Illegal newline after throw',
55015 InvalidRegExp: 'Invalid regular expression',
55016 UnterminatedRegExp: 'Invalid regular expression: missing /',
55017 InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
55018 InvalidLHSInForIn: 'Invalid left-hand side in for-in',
55019 InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
55020 MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
55021 NoCatchOrFinally: 'Missing catch or finally after try',
55022 UnknownLabel: 'Undefined label \'%0\'',
55023 Redeclaration: '%0 \'%1\' has already been declared',
55024 IllegalContinue: 'Illegal continue statement',
55025 IllegalBreak: 'Illegal break statement',
55026 IllegalReturn: 'Illegal return statement',
55027 StrictModeWith: 'Strict mode code may not include a with statement',
55028 StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
55029 StrictVarName: 'Variable name may not be eval or arguments in strict mode',
55030 StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
55031 StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
55032 StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
55033 StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
55034 StrictDelete: 'Delete of an unqualified identifier in strict mode.',
55035 StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
55036 StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
55037 StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
55038 StrictReservedWord: 'Use of future reserved word in strict mode',
55039 TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
55040 ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
55041 DefaultRestParameter: 'Unexpected token =',
55042 ObjectPatternAsRestParameter: 'Unexpected token {',
55043 DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
55044 ConstructorSpecialMethod: 'Class constructor may not be an accessor',
55045 DuplicateConstructor: 'A class may only have one constructor',
55046 StaticPrototype: 'Classes may not have static property named prototype',
55047 MissingFromClause: 'Unexpected token',
55048 NoAsAfterImportNamespace: 'Unexpected token',
55049 InvalidModuleSpecifier: 'Unexpected token',
55050 IllegalImportDeclaration: 'Unexpected token',
55051 IllegalExportDeclaration: 'Unexpected token',
55052 DuplicateBinding: 'Duplicate binding %0'
55053 };
55054
55055 // See also tools/generate-unicode-regex.js.
55056 Regex = {
55057 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
55058 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
55059
55060 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
55061 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
55062 };
55063
55064 // Ensure the condition is true, otherwise throw an error.
55065 // This is only to have a better contract semantic, i.e. another safety net
55066 // to catch a logic error. The condition shall be fulfilled in normal case.
55067 // Do NOT use this to enforce a certain condition on any user input.
55068
55069 function assert(condition, message) {
55070 /* istanbul ignore if */
55071 if (!condition) {
55072 throw new Error('ASSERT: ' + message);
55073 }
55074 }
55075
55076 function isDecimalDigit(ch) {
55077 return (ch >= 0x30 && ch <= 0x39); // 0..9
55078 }
55079
55080 function isHexDigit(ch) {
55081 return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
55082 }
55083
55084 function isOctalDigit(ch) {
55085 return '01234567'.indexOf(ch) >= 0;
55086 }
55087
55088 function octalToDecimal(ch) {
55089 // \0 is not octal escape sequence
55090 var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
55091
55092 if (index < length && isOctalDigit(source[index])) {
55093 octal = true;
55094 code = code * 8 + '01234567'.indexOf(source[index++]);
55095
55096 // 3 digits are only allowed when string starts
55097 // with 0, 1, 2, 3
55098 if ('0123'.indexOf(ch) >= 0 &&
55099 index < length &&
55100 isOctalDigit(source[index])) {
55101 code = code * 8 + '01234567'.indexOf(source[index++]);
55102 }
55103 }
55104
55105 return {
55106 code: code,
55107 octal: octal
55108 };
55109 }
55110
55111 // ECMA-262 11.2 White Space
55112
55113 function isWhiteSpace(ch) {
55114 return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
55115 (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
55116 }
55117
55118 // ECMA-262 11.3 Line Terminators
55119
55120 function isLineTerminator(ch) {
55121 return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
55122 }
55123
55124 // ECMA-262 11.6 Identifier Names and Identifiers
55125
55126 function fromCodePoint(cp) {
55127 return (cp < 0x10000) ? String.fromCharCode(cp) :
55128 String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
55129 String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
55130 }
55131
55132 function isIdentifierStart(ch) {
55133 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
55134 (ch >= 0x41 && ch <= 0x5A) || // A..Z
55135 (ch >= 0x61 && ch <= 0x7A) || // a..z
55136 (ch === 0x5C) || // \ (backslash)
55137 ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
55138 }
55139
55140 function isIdentifierPart(ch) {
55141 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
55142 (ch >= 0x41 && ch <= 0x5A) || // A..Z
55143 (ch >= 0x61 && ch <= 0x7A) || // a..z
55144 (ch >= 0x30 && ch <= 0x39) || // 0..9
55145 (ch === 0x5C) || // \ (backslash)
55146 ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
55147 }
55148
55149 // ECMA-262 11.6.2.2 Future Reserved Words
55150
55151 function isFutureReservedWord(id) {
55152 switch (id) {
55153 case 'enum':
55154 case 'export':
55155 case 'import':
55156 case 'super':
55157 return true;
55158 default:
55159 return false;
55160 }
55161 }
55162
55163 function isStrictModeReservedWord(id) {
55164 switch (id) {
55165 case 'implements':
55166 case 'interface':
55167 case 'package':
55168 case 'private':
55169 case 'protected':
55170 case 'public':
55171 case 'static':
55172 case 'yield':
55173 case 'let':
55174 return true;
55175 default:
55176 return false;
55177 }
55178 }
55179
55180 function isRestrictedWord(id) {
55181 return id === 'eval' || id === 'arguments';
55182 }
55183
55184 // ECMA-262 11.6.2.1 Keywords
55185
55186 function isKeyword(id) {
55187 switch (id.length) {
55188 case 2:
55189 return (id === 'if') || (id === 'in') || (id === 'do');
55190 case 3:
55191 return (id === 'var') || (id === 'for') || (id === 'new') ||
55192 (id === 'try') || (id === 'let');
55193 case 4:
55194 return (id === 'this') || (id === 'else') || (id === 'case') ||
55195 (id === 'void') || (id === 'with') || (id === 'enum');
55196 case 5:
55197 return (id === 'while') || (id === 'break') || (id === 'catch') ||
55198 (id === 'throw') || (id === 'const') || (id === 'yield') ||
55199 (id === 'class') || (id === 'super');
55200 case 6:
55201 return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
55202 (id === 'switch') || (id === 'export') || (id === 'import');
55203 case 7:
55204 return (id === 'default') || (id === 'finally') || (id === 'extends');
55205 case 8:
55206 return (id === 'function') || (id === 'continue') || (id === 'debugger');
55207 case 10:
55208 return (id === 'instanceof');
55209 default:
55210 return false;
55211 }
55212 }
55213
55214 // ECMA-262 11.4 Comments
55215
55216 function addComment(type, value, start, end, loc) {
55217 var comment;
55218
55219 assert(typeof start === 'number', 'Comment must have valid position');
55220
55221 state.lastCommentStart = start;
55222
55223 comment = {
55224 type: type,
55225 value: value
55226 };
55227 if (extra.range) {
55228 comment.range = [start, end];
55229 }
55230 if (extra.loc) {
55231 comment.loc = loc;
55232 }
55233 extra.comments.push(comment);
55234 if (extra.attachComment) {
55235 extra.leadingComments.push(comment);
55236 extra.trailingComments.push(comment);
55237 }
55238 if (extra.tokenize) {
55239 comment.type = comment.type + 'Comment';
55240 if (extra.delegate) {
55241 comment = extra.delegate(comment);
55242 }
55243 extra.tokens.push(comment);
55244 }
55245 }
55246
55247 function skipSingleLineComment(offset) {
55248 var start, loc, ch, comment;
55249
55250 start = index - offset;
55251 loc = {
55252 start: {
55253 line: lineNumber,
55254 column: index - lineStart - offset
55255 }
55256 };
55257
55258 while (index < length) {
55259 ch = source.charCodeAt(index);
55260 ++index;
55261 if (isLineTerminator(ch)) {
55262 hasLineTerminator = true;
55263 if (extra.comments) {
55264 comment = source.slice(start + offset, index - 1);
55265 loc.end = {
55266 line: lineNumber,
55267 column: index - lineStart - 1
55268 };
55269 addComment('Line', comment, start, index - 1, loc);
55270 }
55271 if (ch === 13 && source.charCodeAt(index) === 10) {
55272 ++index;
55273 }
55274 ++lineNumber;
55275 lineStart = index;
55276 return;
55277 }
55278 }
55279
55280 if (extra.comments) {
55281 comment = source.slice(start + offset, index);
55282 loc.end = {
55283 line: lineNumber,
55284 column: index - lineStart
55285 };
55286 addComment('Line', comment, start, index, loc);
55287 }
55288 }
55289
55290 function skipMultiLineComment() {
55291 var start, loc, ch, comment;
55292
55293 if (extra.comments) {
55294 start = index - 2;
55295 loc = {
55296 start: {
55297 line: lineNumber,
55298 column: index - lineStart - 2
55299 }
55300 };
55301 }
55302
55303 while (index < length) {
55304 ch = source.charCodeAt(index);
55305 if (isLineTerminator(ch)) {
55306 if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
55307 ++index;
55308 }
55309 hasLineTerminator = true;
55310 ++lineNumber;
55311 ++index;
55312 lineStart = index;
55313 } else if (ch === 0x2A) {
55314 // Block comment ends with '*/'.
55315 if (source.charCodeAt(index + 1) === 0x2F) {
55316 ++index;
55317 ++index;
55318 if (extra.comments) {
55319 comment = source.slice(start + 2, index - 2);
55320 loc.end = {
55321 line: lineNumber,
55322 column: index - lineStart
55323 };
55324 addComment('Block', comment, start, index, loc);
55325 }
55326 return;
55327 }
55328 ++index;
55329 } else {
55330 ++index;
55331 }
55332 }
55333
55334 // Ran off the end of the file - the whole thing is a comment
55335 if (extra.comments) {
55336 loc.end = {
55337 line: lineNumber,
55338 column: index - lineStart
55339 };
55340 comment = source.slice(start + 2, index);
55341 addComment('Block', comment, start, index, loc);
55342 }
55343 tolerateUnexpectedToken();
55344 }
55345
55346 function skipComment() {
55347 var ch, start;
55348 hasLineTerminator = false;
55349
55350 start = (index === 0);
55351 while (index < length) {
55352 ch = source.charCodeAt(index);
55353
55354 if (isWhiteSpace(ch)) {
55355 ++index;
55356 } else if (isLineTerminator(ch)) {
55357 hasLineTerminator = true;
55358 ++index;
55359 if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
55360 ++index;
55361 }
55362 ++lineNumber;
55363 lineStart = index;
55364 start = true;
55365 } else if (ch === 0x2F) { // U+002F is '/'
55366 ch = source.charCodeAt(index + 1);
55367 if (ch === 0x2F) {
55368 ++index;
55369 ++index;
55370 skipSingleLineComment(2);
55371 start = true;
55372 } else if (ch === 0x2A) { // U+002A is '*'
55373 ++index;
55374 ++index;
55375 skipMultiLineComment();
55376 } else {
55377 break;
55378 }
55379 } else if (start && ch === 0x2D) { // U+002D is '-'
55380 // U+003E is '>'
55381 if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
55382 // '-->' is a single-line comment
55383 index += 3;
55384 skipSingleLineComment(3);
55385 } else {
55386 break;
55387 }
55388 } else if (ch === 0x3C) { // U+003C is '<'
55389 if (source.slice(index + 1, index + 4) === '!--') {
55390 ++index; // `<`
55391 ++index; // `!`
55392 ++index; // `-`
55393 ++index; // `-`
55394 skipSingleLineComment(4);
55395 } else {
55396 break;
55397 }
55398 } else {
55399 break;
55400 }
55401 }
55402 }
55403
55404 function scanHexEscape(prefix) {
55405 var i, len, ch, code = 0;
55406
55407 len = (prefix === 'u') ? 4 : 2;
55408 for (i = 0; i < len; ++i) {
55409 if (index < length && isHexDigit(source[index])) {
55410 ch = source[index++];
55411 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
55412 } else {
55413 return '';
55414 }
55415 }
55416 return String.fromCharCode(code);
55417 }
55418
55419 function scanUnicodeCodePointEscape() {
55420 var ch, code;
55421
55422 ch = source[index];
55423 code = 0;
55424
55425 // At least, one hex digit is required.
55426 if (ch === '}') {
55427 throwUnexpectedToken();
55428 }
55429
55430 while (index < length) {
55431 ch = source[index++];
55432 if (!isHexDigit(ch)) {
55433 break;
55434 }
55435 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
55436 }
55437
55438 if (code > 0x10FFFF || ch !== '}') {
55439 throwUnexpectedToken();
55440 }
55441
55442 return fromCodePoint(code);
55443 }
55444
55445 function codePointAt(i) {
55446 var cp, first, second;
55447
55448 cp = source.charCodeAt(i);
55449 if (cp >= 0xD800 && cp <= 0xDBFF) {
55450 second = source.charCodeAt(i + 1);
55451 if (second >= 0xDC00 && second <= 0xDFFF) {
55452 first = cp;
55453 cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
55454 }
55455 }
55456
55457 return cp;
55458 }
55459
55460 function getComplexIdentifier() {
55461 var cp, ch, id;
55462
55463 cp = codePointAt(index);
55464 id = fromCodePoint(cp);
55465 index += id.length;
55466
55467 // '\u' (U+005C, U+0075) denotes an escaped character.
55468 if (cp === 0x5C) {
55469 if (source.charCodeAt(index) !== 0x75) {
55470 throwUnexpectedToken();
55471 }
55472 ++index;
55473 if (source[index] === '{') {
55474 ++index;
55475 ch = scanUnicodeCodePointEscape();
55476 } else {
55477 ch = scanHexEscape('u');
55478 cp = ch.charCodeAt(0);
55479 if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
55480 throwUnexpectedToken();
55481 }
55482 }
55483 id = ch;
55484 }
55485
55486 while (index < length) {
55487 cp = codePointAt(index);
55488 if (!isIdentifierPart(cp)) {
55489 break;
55490 }
55491 ch = fromCodePoint(cp);
55492 id += ch;
55493 index += ch.length;
55494
55495 // '\u' (U+005C, U+0075) denotes an escaped character.
55496 if (cp === 0x5C) {
55497 id = id.substr(0, id.length - 1);
55498 if (source.charCodeAt(index) !== 0x75) {
55499 throwUnexpectedToken();
55500 }
55501 ++index;
55502 if (source[index] === '{') {
55503 ++index;
55504 ch = scanUnicodeCodePointEscape();
55505 } else {
55506 ch = scanHexEscape('u');
55507 cp = ch.charCodeAt(0);
55508 if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
55509 throwUnexpectedToken();
55510 }
55511 }
55512 id += ch;
55513 }
55514 }
55515
55516 return id;
55517 }
55518
55519 function getIdentifier() {
55520 var start, ch;
55521
55522 start = index++;
55523 while (index < length) {
55524 ch = source.charCodeAt(index);
55525 if (ch === 0x5C) {
55526 // Blackslash (U+005C) marks Unicode escape sequence.
55527 index = start;
55528 return getComplexIdentifier();
55529 } else if (ch >= 0xD800 && ch < 0xDFFF) {
55530 // Need to handle surrogate pairs.
55531 index = start;
55532 return getComplexIdentifier();
55533 }
55534 if (isIdentifierPart(ch)) {
55535 ++index;
55536 } else {
55537 break;
55538 }
55539 }
55540
55541 return source.slice(start, index);
55542 }
55543
55544 function scanIdentifier() {
55545 var start, id, type;
55546
55547 start = index;
55548
55549 // Backslash (U+005C) starts an escaped character.
55550 id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();
55551
55552 // There is no keyword or literal with only one character.
55553 // Thus, it must be an identifier.
55554 if (id.length === 1) {
55555 type = Token.Identifier;
55556 } else if (isKeyword(id)) {
55557 type = Token.Keyword;
55558 } else if (id === 'null') {
55559 type = Token.NullLiteral;
55560 } else if (id === 'true' || id === 'false') {
55561 type = Token.BooleanLiteral;
55562 } else {
55563 type = Token.Identifier;
55564 }
55565
55566 return {
55567 type: type,
55568 value: id,
55569 lineNumber: lineNumber,
55570 lineStart: lineStart,
55571 start: start,
55572 end: index
55573 };
55574 }
55575
55576
55577 // ECMA-262 11.7 Punctuators
55578
55579 function scanPunctuator() {
55580 var token, str;
55581
55582 token = {
55583 type: Token.Punctuator,
55584 value: '',
55585 lineNumber: lineNumber,
55586 lineStart: lineStart,
55587 start: index,
55588 end: index
55589 };
55590
55591 // Check for most common single-character punctuators.
55592 str = source[index];
55593 switch (str) {
55594
55595 case '(':
55596 if (extra.tokenize) {
55597 extra.openParenToken = extra.tokenValues.length;
55598 }
55599 ++index;
55600 break;
55601
55602 case '{':
55603 if (extra.tokenize) {
55604 extra.openCurlyToken = extra.tokenValues.length;
55605 }
55606 state.curlyStack.push('{');
55607 ++index;
55608 break;
55609
55610 case '.':
55611 ++index;
55612 if (source[index] === '.' && source[index + 1] === '.') {
55613 // Spread operator: ...
55614 index += 2;
55615 str = '...';
55616 }
55617 break;
55618
55619 case '}':
55620 ++index;
55621 state.curlyStack.pop();
55622 break;
55623 case ')':
55624 case ';':
55625 case ',':
55626 case '[':
55627 case ']':
55628 case ':':
55629 case '?':
55630 case '~':
55631 ++index;
55632 break;
55633
55634 default:
55635 // 4-character punctuator.
55636 str = source.substr(index, 4);
55637 if (str === '>>>=') {
55638 index += 4;
55639 } else {
55640
55641 // 3-character punctuators.
55642 str = str.substr(0, 3);
55643 if (str === '===' || str === '!==' || str === '>>>' ||
55644 str === '<<=' || str === '>>=') {
55645 index += 3;
55646 } else {
55647
55648 // 2-character punctuators.
55649 str = str.substr(0, 2);
55650 if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
55651 str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
55652 str === '++' || str === '--' || str === '<<' || str === '>>' ||
55653 str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
55654 str === '<=' || str === '>=' || str === '=>') {
55655 index += 2;
55656 } else {
55657
55658 // 1-character punctuators.
55659 str = source[index];
55660 if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
55661 ++index;
55662 }
55663 }
55664 }
55665 }
55666 }
55667
55668 if (index === token.start) {
55669 throwUnexpectedToken();
55670 }
55671
55672 token.end = index;
55673 token.value = str;
55674 return token;
55675 }
55676
55677 // ECMA-262 11.8.3 Numeric Literals
55678
55679 function scanHexLiteral(start) {
55680 var number = '';
55681
55682 while (index < length) {
55683 if (!isHexDigit(source[index])) {
55684 break;
55685 }
55686 number += source[index++];
55687 }
55688
55689 if (number.length === 0) {
55690 throwUnexpectedToken();
55691 }
55692
55693 if (isIdentifierStart(source.charCodeAt(index))) {
55694 throwUnexpectedToken();
55695 }
55696
55697 return {
55698 type: Token.NumericLiteral,
55699 value: parseInt('0x' + number, 16),
55700 lineNumber: lineNumber,
55701 lineStart: lineStart,
55702 start: start,
55703 end: index
55704 };
55705 }
55706
55707 function scanBinaryLiteral(start) {
55708 var ch, number;
55709
55710 number = '';
55711
55712 while (index < length) {
55713 ch = source[index];
55714 if (ch !== '0' && ch !== '1') {
55715 break;
55716 }
55717 number += source[index++];
55718 }
55719
55720 if (number.length === 0) {
55721 // only 0b or 0B
55722 throwUnexpectedToken();
55723 }
55724
55725 if (index < length) {
55726 ch = source.charCodeAt(index);
55727 /* istanbul ignore else */
55728 if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
55729 throwUnexpectedToken();
55730 }
55731 }
55732
55733 return {
55734 type: Token.NumericLiteral,
55735 value: parseInt(number, 2),
55736 lineNumber: lineNumber,
55737 lineStart: lineStart,
55738 start: start,
55739 end: index
55740 };
55741 }
55742
55743 function scanOctalLiteral(prefix, start) {
55744 var number, octal;
55745
55746 if (isOctalDigit(prefix)) {
55747 octal = true;
55748 number = '0' + source[index++];
55749 } else {
55750 octal = false;
55751 ++index;
55752 number = '';
55753 }
55754
55755 while (index < length) {
55756 if (!isOctalDigit(source[index])) {
55757 break;
55758 }
55759 number += source[index++];
55760 }
55761
55762 if (!octal && number.length === 0) {
55763 // only 0o or 0O
55764 throwUnexpectedToken();
55765 }
55766
55767 if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
55768 throwUnexpectedToken();
55769 }
55770
55771 return {
55772 type: Token.NumericLiteral,
55773 value: parseInt(number, 8),
55774 octal: octal,
55775 lineNumber: lineNumber,
55776 lineStart: lineStart,
55777 start: start,
55778 end: index
55779 };
55780 }
55781
55782 function isImplicitOctalLiteral() {
55783 var i, ch;
55784
55785 // Implicit octal, unless there is a non-octal digit.
55786 // (Annex B.1.1 on Numeric Literals)
55787 for (i = index + 1; i < length; ++i) {
55788 ch = source[i];
55789 if (ch === '8' || ch === '9') {
55790 return false;
55791 }
55792 if (!isOctalDigit(ch)) {
55793 return true;
55794 }
55795 }
55796
55797 return true;
55798 }
55799
55800 function scanNumericLiteral() {
55801 var number, start, ch;
55802
55803 ch = source[index];
55804 assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
55805 'Numeric literal must start with a decimal digit or a decimal point');
55806
55807 start = index;
55808 number = '';
55809 if (ch !== '.') {
55810 number = source[index++];
55811 ch = source[index];
55812
55813 // Hex number starts with '0x'.
55814 // Octal number starts with '0'.
55815 // Octal number in ES6 starts with '0o'.
55816 // Binary number in ES6 starts with '0b'.
55817 if (number === '0') {
55818 if (ch === 'x' || ch === 'X') {
55819 ++index;
55820 return scanHexLiteral(start);
55821 }
55822 if (ch === 'b' || ch === 'B') {
55823 ++index;
55824 return scanBinaryLiteral(start);
55825 }
55826 if (ch === 'o' || ch === 'O') {
55827 return scanOctalLiteral(ch, start);
55828 }
55829
55830 if (isOctalDigit(ch)) {
55831 if (isImplicitOctalLiteral()) {
55832 return scanOctalLiteral(ch, start);
55833 }
55834 }
55835 }
55836
55837 while (isDecimalDigit(source.charCodeAt(index))) {
55838 number += source[index++];
55839 }
55840 ch = source[index];
55841 }
55842
55843 if (ch === '.') {
55844 number += source[index++];
55845 while (isDecimalDigit(source.charCodeAt(index))) {
55846 number += source[index++];
55847 }
55848 ch = source[index];
55849 }
55850
55851 if (ch === 'e' || ch === 'E') {
55852 number += source[index++];
55853
55854 ch = source[index];
55855 if (ch === '+' || ch === '-') {
55856 number += source[index++];
55857 }
55858 if (isDecimalDigit(source.charCodeAt(index))) {
55859 while (isDecimalDigit(source.charCodeAt(index))) {
55860 number += source[index++];
55861 }
55862 } else {
55863 throwUnexpectedToken();
55864 }
55865 }
55866
55867 if (isIdentifierStart(source.charCodeAt(index))) {
55868 throwUnexpectedToken();
55869 }
55870
55871 return {
55872 type: Token.NumericLiteral,
55873 value: parseFloat(number),
55874 lineNumber: lineNumber,
55875 lineStart: lineStart,
55876 start: start,
55877 end: index
55878 };
55879 }
55880
55881 // ECMA-262 11.8.4 String Literals
55882
55883 function scanStringLiteral() {
55884 var str = '', quote, start, ch, unescaped, octToDec, octal = false;
55885
55886 quote = source[index];
55887 assert((quote === '\'' || quote === '"'),
55888 'String literal must starts with a quote');
55889
55890 start = index;
55891 ++index;
55892
55893 while (index < length) {
55894 ch = source[index++];
55895
55896 if (ch === quote) {
55897 quote = '';
55898 break;
55899 } else if (ch === '\\') {
55900 ch = source[index++];
55901 if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
55902 switch (ch) {
55903 case 'u':
55904 case 'x':
55905 if (source[index] === '{') {
55906 ++index;
55907 str += scanUnicodeCodePointEscape();
55908 } else {
55909 unescaped = scanHexEscape(ch);
55910 if (!unescaped) {
55911 throw throwUnexpectedToken();
55912 }
55913 str += unescaped;
55914 }
55915 break;
55916 case 'n':
55917 str += '\n';
55918 break;
55919 case 'r':
55920 str += '\r';
55921 break;
55922 case 't':
55923 str += '\t';
55924 break;
55925 case 'b':
55926 str += '\b';
55927 break;
55928 case 'f':
55929 str += '\f';
55930 break;
55931 case 'v':
55932 str += '\x0B';
55933 break;
55934 case '8':
55935 case '9':
55936 str += ch;
55937 tolerateUnexpectedToken();
55938 break;
55939
55940 default:
55941 if (isOctalDigit(ch)) {
55942 octToDec = octalToDecimal(ch);
55943
55944 octal = octToDec.octal || octal;
55945 str += String.fromCharCode(octToDec.code);
55946 } else {
55947 str += ch;
55948 }
55949 break;
55950 }
55951 } else {
55952 ++lineNumber;
55953 if (ch === '\r' && source[index] === '\n') {
55954 ++index;
55955 }
55956 lineStart = index;
55957 }
55958 } else if (isLineTerminator(ch.charCodeAt(0))) {
55959 break;
55960 } else {
55961 str += ch;
55962 }
55963 }
55964
55965 if (quote !== '') {
55966 throwUnexpectedToken();
55967 }
55968
55969 return {
55970 type: Token.StringLiteral,
55971 value: str,
55972 octal: octal,
55973 lineNumber: startLineNumber,
55974 lineStart: startLineStart,
55975 start: start,
55976 end: index
55977 };
55978 }
55979
55980 // ECMA-262 11.8.6 Template Literal Lexical Components
55981
55982 function scanTemplate() {
55983 var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
55984
55985 terminated = false;
55986 tail = false;
55987 start = index;
55988 head = (source[index] === '`');
55989 rawOffset = 2;
55990
55991 ++index;
55992
55993 while (index < length) {
55994 ch = source[index++];
55995 if (ch === '`') {
55996 rawOffset = 1;
55997 tail = true;
55998 terminated = true;
55999 break;
56000 } else if (ch === '$') {
56001 if (source[index] === '{') {
56002 state.curlyStack.push('${');
56003 ++index;
56004 terminated = true;
56005 break;
56006 }
56007 cooked += ch;
56008 } else if (ch === '\\') {
56009 ch = source[index++];
56010 if (!isLineTerminator(ch.charCodeAt(0))) {
56011 switch (ch) {
56012 case 'n':
56013 cooked += '\n';
56014 break;
56015 case 'r':
56016 cooked += '\r';
56017 break;
56018 case 't':
56019 cooked += '\t';
56020 break;
56021 case 'u':
56022 case 'x':
56023 if (source[index] === '{') {
56024 ++index;
56025 cooked += scanUnicodeCodePointEscape();
56026 } else {
56027 restore = index;
56028 unescaped = scanHexEscape(ch);
56029 if (unescaped) {
56030 cooked += unescaped;
56031 } else {
56032 index = restore;
56033 cooked += ch;
56034 }
56035 }
56036 break;
56037 case 'b':
56038 cooked += '\b';
56039 break;
56040 case 'f':
56041 cooked += '\f';
56042 break;
56043 case 'v':
56044 cooked += '\v';
56045 break;
56046
56047 default:
56048 if (ch === '0') {
56049 if (isDecimalDigit(source.charCodeAt(index))) {
56050 // Illegal: \01 \02 and so on
56051 throwError(Messages.TemplateOctalLiteral);
56052 }
56053 cooked += '\0';
56054 } else if (isOctalDigit(ch)) {
56055 // Illegal: \1 \2
56056 throwError(Messages.TemplateOctalLiteral);
56057 } else {
56058 cooked += ch;
56059 }
56060 break;
56061 }
56062 } else {
56063 ++lineNumber;
56064 if (ch === '\r' && source[index] === '\n') {
56065 ++index;
56066 }
56067 lineStart = index;
56068 }
56069 } else if (isLineTerminator(ch.charCodeAt(0))) {
56070 ++lineNumber;
56071 if (ch === '\r' && source[index] === '\n') {
56072 ++index;
56073 }
56074 lineStart = index;
56075 cooked += '\n';
56076 } else {
56077 cooked += ch;
56078 }
56079 }
56080
56081 if (!terminated) {
56082 throwUnexpectedToken();
56083 }
56084
56085 if (!head) {
56086 state.curlyStack.pop();
56087 }
56088
56089 return {
56090 type: Token.Template,
56091 value: {
56092 cooked: cooked,
56093 raw: source.slice(start + 1, index - rawOffset)
56094 },
56095 head: head,
56096 tail: tail,
56097 lineNumber: lineNumber,
56098 lineStart: lineStart,
56099 start: start,
56100 end: index
56101 };
56102 }
56103
56104 // ECMA-262 11.8.5 Regular Expression Literals
56105
56106 function testRegExp(pattern, flags) {
56107 // The BMP character to use as a replacement for astral symbols when
56108 // translating an ES6 "u"-flagged pattern to an ES5-compatible
56109 // approximation.
56110 // Note: replacing with '\uFFFF' enables false positives in unlikely
56111 // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
56112 // pattern that would not be detected by this substitution.
56113 var astralSubstitute = '\uFFFF',
56114 tmp = pattern;
56115
56116 if (flags.indexOf('u') >= 0) {
56117 tmp = tmp
56118 // Replace every Unicode escape sequence with the equivalent
56119 // BMP character or a constant ASCII code point in the case of
56120 // astral symbols. (See the above note on `astralSubstitute`
56121 // for more information.)
56122 .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
56123 var codePoint = parseInt($1 || $2, 16);
56124 if (codePoint > 0x10FFFF) {
56125 throwUnexpectedToken(null, Messages.InvalidRegExp);
56126 }
56127 if (codePoint <= 0xFFFF) {
56128 return String.fromCharCode(codePoint);
56129 }
56130 return astralSubstitute;
56131 })
56132 // Replace each paired surrogate with a single ASCII symbol to
56133 // avoid throwing on regular expressions that are only valid in
56134 // combination with the "u" flag.
56135 .replace(
56136 /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
56137 astralSubstitute
56138 );
56139 }
56140
56141 // First, detect invalid regular expressions.
56142 try {
56143 RegExp(tmp);
56144 } catch (e) {
56145 throwUnexpectedToken(null, Messages.InvalidRegExp);
56146 }
56147
56148 // Return a regular expression object for this pattern-flag pair, or
56149 // `null` in case the current environment doesn't support the flags it
56150 // uses.
56151 try {
56152 return new RegExp(pattern, flags);
56153 } catch (exception) {
56154 return null;
56155 }
56156 }
56157
56158 function scanRegExpBody() {
56159 var ch, str, classMarker, terminated, body;
56160
56161 ch = source[index];
56162 assert(ch === '/', 'Regular expression literal must start with a slash');
56163 str = source[index++];
56164
56165 classMarker = false;
56166 terminated = false;
56167 while (index < length) {
56168 ch = source[index++];
56169 str += ch;
56170 if (ch === '\\') {
56171 ch = source[index++];
56172 // ECMA-262 7.8.5
56173 if (isLineTerminator(ch.charCodeAt(0))) {
56174 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
56175 }
56176 str += ch;
56177 } else if (isLineTerminator(ch.charCodeAt(0))) {
56178 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
56179 } else if (classMarker) {
56180 if (ch === ']') {
56181 classMarker = false;
56182 }
56183 } else {
56184 if (ch === '/') {
56185 terminated = true;
56186 break;
56187 } else if (ch === '[') {
56188 classMarker = true;
56189 }
56190 }
56191 }
56192
56193 if (!terminated) {
56194 throwUnexpectedToken(null, Messages.UnterminatedRegExp);
56195 }
56196
56197 // Exclude leading and trailing slash.
56198 body = str.substr(1, str.length - 2);
56199 return {
56200 value: body,
56201 literal: str
56202 };
56203 }
56204
56205 function scanRegExpFlags() {
56206 var ch, str, flags, restore;
56207
56208 str = '';
56209 flags = '';
56210 while (index < length) {
56211 ch = source[index];
56212 if (!isIdentifierPart(ch.charCodeAt(0))) {
56213 break;
56214 }
56215
56216 ++index;
56217 if (ch === '\\' && index < length) {
56218 ch = source[index];
56219 if (ch === 'u') {
56220 ++index;
56221 restore = index;
56222 ch = scanHexEscape('u');
56223 if (ch) {
56224 flags += ch;
56225 for (str += '\\u'; restore < index; ++restore) {
56226 str += source[restore];
56227 }
56228 } else {
56229 index = restore;
56230 flags += 'u';
56231 str += '\\u';
56232 }
56233 tolerateUnexpectedToken();
56234 } else {
56235 str += '\\';
56236 tolerateUnexpectedToken();
56237 }
56238 } else {
56239 flags += ch;
56240 str += ch;
56241 }
56242 }
56243
56244 return {
56245 value: flags,
56246 literal: str
56247 };
56248 }
56249
56250 function scanRegExp() {
56251 var start, body, flags, value;
56252 scanning = true;
56253
56254 lookahead = null;
56255 skipComment();
56256 start = index;
56257
56258 body = scanRegExpBody();
56259 flags = scanRegExpFlags();
56260 value = testRegExp(body.value, flags.value);
56261 scanning = false;
56262 if (extra.tokenize) {
56263 return {
56264 type: Token.RegularExpression,
56265 value: value,
56266 regex: {
56267 pattern: body.value,
56268 flags: flags.value
56269 },
56270 lineNumber: lineNumber,
56271 lineStart: lineStart,
56272 start: start,
56273 end: index
56274 };
56275 }
56276
56277 return {
56278 literal: body.literal + flags.literal,
56279 value: value,
56280 regex: {
56281 pattern: body.value,
56282 flags: flags.value
56283 },
56284 start: start,
56285 end: index
56286 };
56287 }
56288
56289 function collectRegex() {
56290 var pos, loc, regex, token;
56291
56292 skipComment();
56293
56294 pos = index;
56295 loc = {
56296 start: {
56297 line: lineNumber,
56298 column: index - lineStart
56299 }
56300 };
56301
56302 regex = scanRegExp();
56303
56304 loc.end = {
56305 line: lineNumber,
56306 column: index - lineStart
56307 };
56308
56309 /* istanbul ignore next */
56310 if (!extra.tokenize) {
56311 // Pop the previous token, which is likely '/' or '/='
56312 if (extra.tokens.length > 0) {
56313 token = extra.tokens[extra.tokens.length - 1];
56314 if (token.range[0] === pos && token.type === 'Punctuator') {
56315 if (token.value === '/' || token.value === '/=') {
56316 extra.tokens.pop();
56317 }
56318 }
56319 }
56320
56321 extra.tokens.push({
56322 type: 'RegularExpression',
56323 value: regex.literal,
56324 regex: regex.regex,
56325 range: [pos, index],
56326 loc: loc
56327 });
56328 }
56329
56330 return regex;
56331 }
56332
56333 function isIdentifierName(token) {
56334 return token.type === Token.Identifier ||
56335 token.type === Token.Keyword ||
56336 token.type === Token.BooleanLiteral ||
56337 token.type === Token.NullLiteral;
56338 }
56339
56340 // Using the following algorithm:
56341 // https://github.com/mozilla/sweet.js/wiki/design
56342
56343 function advanceSlash() {
56344 var regex, previous, check;
56345
56346 function testKeyword(value) {
56347 return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
56348 }
56349
56350 previous = extra.tokenValues[extra.tokens.length - 1];
56351 regex = (previous !== null);
56352
56353 switch (previous) {
56354 case 'this':
56355 case ']':
56356 regex = false;
56357 break;
56358
56359 case ')':
56360 check = extra.tokenValues[extra.openParenToken - 1];
56361 regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
56362 break;
56363
56364 case '}':
56365 // Dividing a function by anything makes little sense,
56366 // but we have to check for that.
56367 regex = false;
56368 if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
56369 // Anonymous function, e.g. function(){} /42
56370 check = extra.tokenValues[extra.openCurlyToken - 4];
56371 regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
56372 } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
56373 // Named function, e.g. function f(){} /42/
56374 check = extra.tokenValues[extra.openCurlyToken - 5];
56375 regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
56376 }
56377 }
56378
56379 return regex ? collectRegex() : scanPunctuator();
56380 }
56381
56382 function advance() {
56383 var cp, token;
56384
56385 if (index >= length) {
56386 return {
56387 type: Token.EOF,
56388 lineNumber: lineNumber,
56389 lineStart: lineStart,
56390 start: index,
56391 end: index
56392 };
56393 }
56394
56395 cp = source.charCodeAt(index);
56396
56397 if (isIdentifierStart(cp)) {
56398 token = scanIdentifier();
56399 if (strict && isStrictModeReservedWord(token.value)) {
56400 token.type = Token.Keyword;
56401 }
56402 return token;
56403 }
56404
56405 // Very common: ( and ) and ;
56406 if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
56407 return scanPunctuator();
56408 }
56409
56410 // String literal starts with single quote (U+0027) or double quote (U+0022).
56411 if (cp === 0x27 || cp === 0x22) {
56412 return scanStringLiteral();
56413 }
56414
56415 // Dot (.) U+002E can also start a floating-point number, hence the need
56416 // to check the next character.
56417 if (cp === 0x2E) {
56418 if (isDecimalDigit(source.charCodeAt(index + 1))) {
56419 return scanNumericLiteral();
56420 }
56421 return scanPunctuator();
56422 }
56423
56424 if (isDecimalDigit(cp)) {
56425 return scanNumericLiteral();
56426 }
56427
56428 // Slash (/) U+002F can also start a regex.
56429 if (extra.tokenize && cp === 0x2F) {
56430 return advanceSlash();
56431 }
56432
56433 // Template literals start with ` (U+0060) for template head
56434 // or } (U+007D) for template middle or template tail.
56435 if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
56436 return scanTemplate();
56437 }
56438
56439 // Possible identifier start in a surrogate pair.
56440 if (cp >= 0xD800 && cp < 0xDFFF) {
56441 cp = codePointAt(index);
56442 if (isIdentifierStart(cp)) {
56443 return scanIdentifier();
56444 }
56445 }
56446
56447 return scanPunctuator();
56448 }
56449
56450 function collectToken() {
56451 var loc, token, value, entry;
56452
56453 loc = {
56454 start: {
56455 line: lineNumber,
56456 column: index - lineStart
56457 }
56458 };
56459
56460 token = advance();
56461 loc.end = {
56462 line: lineNumber,
56463 column: index - lineStart
56464 };
56465
56466 if (token.type !== Token.EOF) {
56467 value = source.slice(token.start, token.end);
56468 entry = {
56469 type: TokenName[token.type],
56470 value: value,
56471 range: [token.start, token.end],
56472 loc: loc
56473 };
56474 if (token.regex) {
56475 entry.regex = {
56476 pattern: token.regex.pattern,
56477 flags: token.regex.flags
56478 };
56479 }
56480 if (extra.tokenValues) {
56481 extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
56482 }
56483 if (extra.tokenize) {
56484 if (!extra.range) {
56485 delete entry.range;
56486 }
56487 if (!extra.loc) {
56488 delete entry.loc;
56489 }
56490 if (extra.delegate) {
56491 entry = extra.delegate(entry);
56492 }
56493 }
56494 extra.tokens.push(entry);
56495 }
56496
56497 return token;
56498 }
56499
56500 function lex() {
56501 var token;
56502 scanning = true;
56503
56504 lastIndex = index;
56505 lastLineNumber = lineNumber;
56506 lastLineStart = lineStart;
56507
56508 skipComment();
56509
56510 token = lookahead;
56511
56512 startIndex = index;
56513 startLineNumber = lineNumber;
56514 startLineStart = lineStart;
56515
56516 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
56517 scanning = false;
56518 return token;
56519 }
56520
56521 function peek() {
56522 scanning = true;
56523
56524 skipComment();
56525
56526 lastIndex = index;
56527 lastLineNumber = lineNumber;
56528 lastLineStart = lineStart;
56529
56530 startIndex = index;
56531 startLineNumber = lineNumber;
56532 startLineStart = lineStart;
56533
56534 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
56535 scanning = false;
56536 }
56537
56538 function Position() {
56539 this.line = startLineNumber;
56540 this.column = startIndex - startLineStart;
56541 }
56542
56543 function SourceLocation() {
56544 this.start = new Position();
56545 this.end = null;
56546 }
56547
56548 function WrappingSourceLocation(startToken) {
56549 this.start = {
56550 line: startToken.lineNumber,
56551 column: startToken.start - startToken.lineStart
56552 };
56553 this.end = null;
56554 }
56555
56556 function Node() {
56557 if (extra.range) {
56558 this.range = [startIndex, 0];
56559 }
56560 if (extra.loc) {
56561 this.loc = new SourceLocation();
56562 }
56563 }
56564
56565 function WrappingNode(startToken) {
56566 if (extra.range) {
56567 this.range = [startToken.start, 0];
56568 }
56569 if (extra.loc) {
56570 this.loc = new WrappingSourceLocation(startToken);
56571 }
56572 }
56573
56574 WrappingNode.prototype = Node.prototype = {
56575
56576 processComment: function () {
56577 var lastChild,
56578 innerComments,
56579 leadingComments,
56580 trailingComments,
56581 bottomRight = extra.bottomRightStack,
56582 i,
56583 comment,
56584 last = bottomRight[bottomRight.length - 1];
56585
56586 if (this.type === Syntax.Program) {
56587 if (this.body.length > 0) {
56588 return;
56589 }
56590 }
56591 /**
56592 * patch innnerComments for properties empty block
56593 * `function a() {/** comments **\/}`
56594 */
56595
56596 if (this.type === Syntax.BlockStatement && this.body.length === 0) {
56597 innerComments = [];
56598 for (i = extra.leadingComments.length - 1; i >= 0; --i) {
56599 comment = extra.leadingComments[i];
56600 if (this.range[1] >= comment.range[1]) {
56601 innerComments.unshift(comment);
56602 extra.leadingComments.splice(i, 1);
56603 extra.trailingComments.splice(i, 1);
56604 }
56605 }
56606 if (innerComments.length) {
56607 this.innerComments = innerComments;
56608 //bottomRight.push(this);
56609 return;
56610 }
56611 }
56612
56613 if (extra.trailingComments.length > 0) {
56614 trailingComments = [];
56615 for (i = extra.trailingComments.length - 1; i >= 0; --i) {
56616 comment = extra.trailingComments[i];
56617 if (comment.range[0] >= this.range[1]) {
56618 trailingComments.unshift(comment);
56619 extra.trailingComments.splice(i, 1);
56620 }
56621 }
56622 extra.trailingComments = [];
56623 } else {
56624 if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
56625 trailingComments = last.trailingComments;
56626 delete last.trailingComments;
56627 }
56628 }
56629
56630 // Eating the stack.
56631 while (last && last.range[0] >= this.range[0]) {
56632 lastChild = bottomRight.pop();
56633 last = bottomRight[bottomRight.length - 1];
56634 }
56635
56636 if (lastChild) {
56637 if (lastChild.leadingComments) {
56638 leadingComments = [];
56639 for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
56640 comment = lastChild.leadingComments[i];
56641 if (comment.range[1] <= this.range[0]) {
56642 leadingComments.unshift(comment);
56643 lastChild.leadingComments.splice(i, 1);
56644 }
56645 }
56646
56647 if (!lastChild.leadingComments.length) {
56648 lastChild.leadingComments = undefined;
56649 }
56650 }
56651 } else if (extra.leadingComments.length > 0) {
56652 leadingComments = [];
56653 for (i = extra.leadingComments.length - 1; i >= 0; --i) {
56654 comment = extra.leadingComments[i];
56655 if (comment.range[1] <= this.range[0]) {
56656 leadingComments.unshift(comment);
56657 extra.leadingComments.splice(i, 1);
56658 }
56659 }
56660 }
56661
56662
56663 if (leadingComments && leadingComments.length > 0) {
56664 this.leadingComments = leadingComments;
56665 }
56666 if (trailingComments && trailingComments.length > 0) {
56667 this.trailingComments = trailingComments;
56668 }
56669
56670 bottomRight.push(this);
56671 },
56672
56673 finish: function () {
56674 if (extra.range) {
56675 this.range[1] = lastIndex;
56676 }
56677 if (extra.loc) {
56678 this.loc.end = {
56679 line: lastLineNumber,
56680 column: lastIndex - lastLineStart
56681 };
56682 if (extra.source) {
56683 this.loc.source = extra.source;
56684 }
56685 }
56686
56687 if (extra.attachComment) {
56688 this.processComment();
56689 }
56690 },
56691
56692 finishArrayExpression: function (elements) {
56693 this.type = Syntax.ArrayExpression;
56694 this.elements = elements;
56695 this.finish();
56696 return this;
56697 },
56698
56699 finishArrayPattern: function (elements) {
56700 this.type = Syntax.ArrayPattern;
56701 this.elements = elements;
56702 this.finish();
56703 return this;
56704 },
56705
56706 finishArrowFunctionExpression: function (params, defaults, body, expression) {
56707 this.type = Syntax.ArrowFunctionExpression;
56708 this.id = null;
56709 this.params = params;
56710 this.defaults = defaults;
56711 this.body = body;
56712 this.generator = false;
56713 this.expression = expression;
56714 this.finish();
56715 return this;
56716 },
56717
56718 finishAssignmentExpression: function (operator, left, right) {
56719 this.type = Syntax.AssignmentExpression;
56720 this.operator = operator;
56721 this.left = left;
56722 this.right = right;
56723 this.finish();
56724 return this;
56725 },
56726
56727 finishAssignmentPattern: function (left, right) {
56728 this.type = Syntax.AssignmentPattern;
56729 this.left = left;
56730 this.right = right;
56731 this.finish();
56732 return this;
56733 },
56734
56735 finishBinaryExpression: function (operator, left, right) {
56736 this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
56737 this.operator = operator;
56738 this.left = left;
56739 this.right = right;
56740 this.finish();
56741 return this;
56742 },
56743
56744 finishBlockStatement: function (body) {
56745 this.type = Syntax.BlockStatement;
56746 this.body = body;
56747 this.finish();
56748 return this;
56749 },
56750
56751 finishBreakStatement: function (label) {
56752 this.type = Syntax.BreakStatement;
56753 this.label = label;
56754 this.finish();
56755 return this;
56756 },
56757
56758 finishCallExpression: function (callee, args) {
56759 this.type = Syntax.CallExpression;
56760 this.callee = callee;
56761 this.arguments = args;
56762 this.finish();
56763 return this;
56764 },
56765
56766 finishCatchClause: function (param, body) {
56767 this.type = Syntax.CatchClause;
56768 this.param = param;
56769 this.body = body;
56770 this.finish();
56771 return this;
56772 },
56773
56774 finishClassBody: function (body) {
56775 this.type = Syntax.ClassBody;
56776 this.body = body;
56777 this.finish();
56778 return this;
56779 },
56780
56781 finishClassDeclaration: function (id, superClass, body) {
56782 this.type = Syntax.ClassDeclaration;
56783 this.id = id;
56784 this.superClass = superClass;
56785 this.body = body;
56786 this.finish();
56787 return this;
56788 },
56789
56790 finishClassExpression: function (id, superClass, body) {
56791 this.type = Syntax.ClassExpression;
56792 this.id = id;
56793 this.superClass = superClass;
56794 this.body = body;
56795 this.finish();
56796 return this;
56797 },
56798
56799 finishConditionalExpression: function (test, consequent, alternate) {
56800 this.type = Syntax.ConditionalExpression;
56801 this.test = test;
56802 this.consequent = consequent;
56803 this.alternate = alternate;
56804 this.finish();
56805 return this;
56806 },
56807
56808 finishContinueStatement: function (label) {
56809 this.type = Syntax.ContinueStatement;
56810 this.label = label;
56811 this.finish();
56812 return this;
56813 },
56814
56815 finishDebuggerStatement: function () {
56816 this.type = Syntax.DebuggerStatement;
56817 this.finish();
56818 return this;
56819 },
56820
56821 finishDoWhileStatement: function (body, test) {
56822 this.type = Syntax.DoWhileStatement;
56823 this.body = body;
56824 this.test = test;
56825 this.finish();
56826 return this;
56827 },
56828
56829 finishEmptyStatement: function () {
56830 this.type = Syntax.EmptyStatement;
56831 this.finish();
56832 return this;
56833 },
56834
56835 finishExpressionStatement: function (expression) {
56836 this.type = Syntax.ExpressionStatement;
56837 this.expression = expression;
56838 this.finish();
56839 return this;
56840 },
56841
56842 finishForStatement: function (init, test, update, body) {
56843 this.type = Syntax.ForStatement;
56844 this.init = init;
56845 this.test = test;
56846 this.update = update;
56847 this.body = body;
56848 this.finish();
56849 return this;
56850 },
56851
56852 finishForOfStatement: function (left, right, body) {
56853 this.type = Syntax.ForOfStatement;
56854 this.left = left;
56855 this.right = right;
56856 this.body = body;
56857 this.finish();
56858 return this;
56859 },
56860
56861 finishForInStatement: function (left, right, body) {
56862 this.type = Syntax.ForInStatement;
56863 this.left = left;
56864 this.right = right;
56865 this.body = body;
56866 this.each = false;
56867 this.finish();
56868 return this;
56869 },
56870
56871 finishFunctionDeclaration: function (id, params, defaults, body, generator) {
56872 this.type = Syntax.FunctionDeclaration;
56873 this.id = id;
56874 this.params = params;
56875 this.defaults = defaults;
56876 this.body = body;
56877 this.generator = generator;
56878 this.expression = false;
56879 this.finish();
56880 return this;
56881 },
56882
56883 finishFunctionExpression: function (id, params, defaults, body, generator) {
56884 this.type = Syntax.FunctionExpression;
56885 this.id = id;
56886 this.params = params;
56887 this.defaults = defaults;
56888 this.body = body;
56889 this.generator = generator;
56890 this.expression = false;
56891 this.finish();
56892 return this;
56893 },
56894
56895 finishIdentifier: function (name) {
56896 this.type = Syntax.Identifier;
56897 this.name = name;
56898 this.finish();
56899 return this;
56900 },
56901
56902 finishIfStatement: function (test, consequent, alternate) {
56903 this.type = Syntax.IfStatement;
56904 this.test = test;
56905 this.consequent = consequent;
56906 this.alternate = alternate;
56907 this.finish();
56908 return this;
56909 },
56910
56911 finishLabeledStatement: function (label, body) {
56912 this.type = Syntax.LabeledStatement;
56913 this.label = label;
56914 this.body = body;
56915 this.finish();
56916 return this;
56917 },
56918
56919 finishLiteral: function (token) {
56920 this.type = Syntax.Literal;
56921 this.value = token.value;
56922 this.raw = source.slice(token.start, token.end);
56923 if (token.regex) {
56924 this.regex = token.regex;
56925 }
56926 this.finish();
56927 return this;
56928 },
56929
56930 finishMemberExpression: function (accessor, object, property) {
56931 this.type = Syntax.MemberExpression;
56932 this.computed = accessor === '[';
56933 this.object = object;
56934 this.property = property;
56935 this.finish();
56936 return this;
56937 },
56938
56939 finishMetaProperty: function (meta, property) {
56940 this.type = Syntax.MetaProperty;
56941 this.meta = meta;
56942 this.property = property;
56943 this.finish();
56944 return this;
56945 },
56946
56947 finishNewExpression: function (callee, args) {
56948 this.type = Syntax.NewExpression;
56949 this.callee = callee;
56950 this.arguments = args;
56951 this.finish();
56952 return this;
56953 },
56954
56955 finishObjectExpression: function (properties) {
56956 this.type = Syntax.ObjectExpression;
56957 this.properties = properties;
56958 this.finish();
56959 return this;
56960 },
56961
56962 finishObjectPattern: function (properties) {
56963 this.type = Syntax.ObjectPattern;
56964 this.properties = properties;
56965 this.finish();
56966 return this;
56967 },
56968
56969 finishPostfixExpression: function (operator, argument) {
56970 this.type = Syntax.UpdateExpression;
56971 this.operator = operator;
56972 this.argument = argument;
56973 this.prefix = false;
56974 this.finish();
56975 return this;
56976 },
56977
56978 finishProgram: function (body, sourceType) {
56979 this.type = Syntax.Program;
56980 this.body = body;
56981 this.sourceType = sourceType;
56982 this.finish();
56983 return this;
56984 },
56985
56986 finishProperty: function (kind, key, computed, value, method, shorthand) {
56987 this.type = Syntax.Property;
56988 this.key = key;
56989 this.computed = computed;
56990 this.value = value;
56991 this.kind = kind;
56992 this.method = method;
56993 this.shorthand = shorthand;
56994 this.finish();
56995 return this;
56996 },
56997
56998 finishRestElement: function (argument) {
56999 this.type = Syntax.RestElement;
57000 this.argument = argument;
57001 this.finish();
57002 return this;
57003 },
57004
57005 finishReturnStatement: function (argument) {
57006 this.type = Syntax.ReturnStatement;
57007 this.argument = argument;
57008 this.finish();
57009 return this;
57010 },
57011
57012 finishSequenceExpression: function (expressions) {
57013 this.type = Syntax.SequenceExpression;
57014 this.expressions = expressions;
57015 this.finish();
57016 return this;
57017 },
57018
57019 finishSpreadElement: function (argument) {
57020 this.type = Syntax.SpreadElement;
57021 this.argument = argument;
57022 this.finish();
57023 return this;
57024 },
57025
57026 finishSwitchCase: function (test, consequent) {
57027 this.type = Syntax.SwitchCase;
57028 this.test = test;
57029 this.consequent = consequent;
57030 this.finish();
57031 return this;
57032 },
57033
57034 finishSuper: function () {
57035 this.type = Syntax.Super;
57036 this.finish();
57037 return this;
57038 },
57039
57040 finishSwitchStatement: function (discriminant, cases) {
57041 this.type = Syntax.SwitchStatement;
57042 this.discriminant = discriminant;
57043 this.cases = cases;
57044 this.finish();
57045 return this;
57046 },
57047
57048 finishTaggedTemplateExpression: function (tag, quasi) {
57049 this.type = Syntax.TaggedTemplateExpression;
57050 this.tag = tag;
57051 this.quasi = quasi;
57052 this.finish();
57053 return this;
57054 },
57055
57056 finishTemplateElement: function (value, tail) {
57057 this.type = Syntax.TemplateElement;
57058 this.value = value;
57059 this.tail = tail;
57060 this.finish();
57061 return this;
57062 },
57063
57064 finishTemplateLiteral: function (quasis, expressions) {
57065 this.type = Syntax.TemplateLiteral;
57066 this.quasis = quasis;
57067 this.expressions = expressions;
57068 this.finish();
57069 return this;
57070 },
57071
57072 finishThisExpression: function () {
57073 this.type = Syntax.ThisExpression;
57074 this.finish();
57075 return this;
57076 },
57077
57078 finishThrowStatement: function (argument) {
57079 this.type = Syntax.ThrowStatement;
57080 this.argument = argument;
57081 this.finish();
57082 return this;
57083 },
57084
57085 finishTryStatement: function (block, handler, finalizer) {
57086 this.type = Syntax.TryStatement;
57087 this.block = block;
57088 this.guardedHandlers = [];
57089 this.handlers = handler ? [handler] : [];
57090 this.handler = handler;
57091 this.finalizer = finalizer;
57092 this.finish();
57093 return this;
57094 },
57095
57096 finishUnaryExpression: function (operator, argument) {
57097 this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
57098 this.operator = operator;
57099 this.argument = argument;
57100 this.prefix = true;
57101 this.finish();
57102 return this;
57103 },
57104
57105 finishVariableDeclaration: function (declarations) {
57106 this.type = Syntax.VariableDeclaration;
57107 this.declarations = declarations;
57108 this.kind = 'var';
57109 this.finish();
57110 return this;
57111 },
57112
57113 finishLexicalDeclaration: function (declarations, kind) {
57114 this.type = Syntax.VariableDeclaration;
57115 this.declarations = declarations;
57116 this.kind = kind;
57117 this.finish();
57118 return this;
57119 },
57120
57121 finishVariableDeclarator: function (id, init) {
57122 this.type = Syntax.VariableDeclarator;
57123 this.id = id;
57124 this.init = init;
57125 this.finish();
57126 return this;
57127 },
57128
57129 finishWhileStatement: function (test, body) {
57130 this.type = Syntax.WhileStatement;
57131 this.test = test;
57132 this.body = body;
57133 this.finish();
57134 return this;
57135 },
57136
57137 finishWithStatement: function (object, body) {
57138 this.type = Syntax.WithStatement;
57139 this.object = object;
57140 this.body = body;
57141 this.finish();
57142 return this;
57143 },
57144
57145 finishExportSpecifier: function (local, exported) {
57146 this.type = Syntax.ExportSpecifier;
57147 this.exported = exported || local;
57148 this.local = local;
57149 this.finish();
57150 return this;
57151 },
57152
57153 finishImportDefaultSpecifier: function (local) {
57154 this.type = Syntax.ImportDefaultSpecifier;
57155 this.local = local;
57156 this.finish();
57157 return this;
57158 },
57159
57160 finishImportNamespaceSpecifier: function (local) {
57161 this.type = Syntax.ImportNamespaceSpecifier;
57162 this.local = local;
57163 this.finish();
57164 return this;
57165 },
57166
57167 finishExportNamedDeclaration: function (declaration, specifiers, src) {
57168 this.type = Syntax.ExportNamedDeclaration;
57169 this.declaration = declaration;
57170 this.specifiers = specifiers;
57171 this.source = src;
57172 this.finish();
57173 return this;
57174 },
57175
57176 finishExportDefaultDeclaration: function (declaration) {
57177 this.type = Syntax.ExportDefaultDeclaration;
57178 this.declaration = declaration;
57179 this.finish();
57180 return this;
57181 },
57182
57183 finishExportAllDeclaration: function (src) {
57184 this.type = Syntax.ExportAllDeclaration;
57185 this.source = src;
57186 this.finish();
57187 return this;
57188 },
57189
57190 finishImportSpecifier: function (local, imported) {
57191 this.type = Syntax.ImportSpecifier;
57192 this.local = local || imported;
57193 this.imported = imported;
57194 this.finish();
57195 return this;
57196 },
57197
57198 finishImportDeclaration: function (specifiers, src) {
57199 this.type = Syntax.ImportDeclaration;
57200 this.specifiers = specifiers;
57201 this.source = src;
57202 this.finish();
57203 return this;
57204 },
57205
57206 finishYieldExpression: function (argument, delegate) {
57207 this.type = Syntax.YieldExpression;
57208 this.argument = argument;
57209 this.delegate = delegate;
57210 this.finish();
57211 return this;
57212 }
57213 };
57214
57215
57216 function recordError(error) {
57217 var e, existing;
57218
57219 for (e = 0; e < extra.errors.length; e++) {
57220 existing = extra.errors[e];
57221 // Prevent duplicated error.
57222 /* istanbul ignore next */
57223 if (existing.index === error.index && existing.message === error.message) {
57224 return;
57225 }
57226 }
57227
57228 extra.errors.push(error);
57229 }
57230
57231 function constructError(msg, column) {
57232 var error = new Error(msg);
57233 try {
57234 throw error;
57235 } catch (base) {
57236 /* istanbul ignore else */
57237 if (Object.create && Object.defineProperty) {
57238 error = Object.create(base);
57239 Object.defineProperty(error, 'column', { value: column });
57240 }
57241 } finally {
57242 return error;
57243 }
57244 }
57245
57246 function createError(line, pos, description) {
57247 var msg, column, error;
57248
57249 msg = 'Line ' + line + ': ' + description;
57250 column = pos - (scanning ? lineStart : lastLineStart) + 1;
57251 error = constructError(msg, column);
57252 error.lineNumber = line;
57253 error.description = description;
57254 error.index = pos;
57255 return error;
57256 }
57257
57258 // Throw an exception
57259
57260 function throwError(messageFormat) {
57261 var args, msg;
57262
57263 args = Array.prototype.slice.call(arguments, 1);
57264 msg = messageFormat.replace(/%(\d)/g,
57265 function (whole, idx) {
57266 assert(idx < args.length, 'Message reference must be in range');
57267 return args[idx];
57268 }
57269 );
57270
57271 throw createError(lastLineNumber, lastIndex, msg);
57272 }
57273
57274 function tolerateError(messageFormat) {
57275 var args, msg, error;
57276
57277 args = Array.prototype.slice.call(arguments, 1);
57278 /* istanbul ignore next */
57279 msg = messageFormat.replace(/%(\d)/g,
57280 function (whole, idx) {
57281 assert(idx < args.length, 'Message reference must be in range');
57282 return args[idx];
57283 }
57284 );
57285
57286 error = createError(lineNumber, lastIndex, msg);
57287 if (extra.errors) {
57288 recordError(error);
57289 } else {
57290 throw error;
57291 }
57292 }
57293
57294 // Throw an exception because of the token.
57295
57296 function unexpectedTokenError(token, message) {
57297 var value, msg = message || Messages.UnexpectedToken;
57298
57299 if (token) {
57300 if (!message) {
57301 msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
57302 (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
57303 (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
57304 (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
57305 (token.type === Token.Template) ? Messages.UnexpectedTemplate :
57306 Messages.UnexpectedToken;
57307
57308 if (token.type === Token.Keyword) {
57309 if (isFutureReservedWord(token.value)) {
57310 msg = Messages.UnexpectedReserved;
57311 } else if (strict && isStrictModeReservedWord(token.value)) {
57312 msg = Messages.StrictReservedWord;
57313 }
57314 }
57315 }
57316
57317 value = (token.type === Token.Template) ? token.value.raw : token.value;
57318 } else {
57319 value = 'ILLEGAL';
57320 }
57321
57322 msg = msg.replace('%0', value);
57323
57324 return (token && typeof token.lineNumber === 'number') ?
57325 createError(token.lineNumber, token.start, msg) :
57326 createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
57327 }
57328
57329 function throwUnexpectedToken(token, message) {
57330 throw unexpectedTokenError(token, message);
57331 }
57332
57333 function tolerateUnexpectedToken(token, message) {
57334 var error = unexpectedTokenError(token, message);
57335 if (extra.errors) {
57336 recordError(error);
57337 } else {
57338 throw error;
57339 }
57340 }
57341
57342 // Expect the next token to match the specified punctuator.
57343 // If not, an exception will be thrown.
57344
57345 function expect(value) {
57346 var token = lex();
57347 if (token.type !== Token.Punctuator || token.value !== value) {
57348 throwUnexpectedToken(token);
57349 }
57350 }
57351
57352 /**
57353 * @name expectCommaSeparator
57354 * @description Quietly expect a comma when in tolerant mode, otherwise delegates
57355 * to <code>expect(value)</code>
57356 * @since 2.0
57357 */
57358 function expectCommaSeparator() {
57359 var token;
57360
57361 if (extra.errors) {
57362 token = lookahead;
57363 if (token.type === Token.Punctuator && token.value === ',') {
57364 lex();
57365 } else if (token.type === Token.Punctuator && token.value === ';') {
57366 lex();
57367 tolerateUnexpectedToken(token);
57368 } else {
57369 tolerateUnexpectedToken(token, Messages.UnexpectedToken);
57370 }
57371 } else {
57372 expect(',');
57373 }
57374 }
57375
57376 // Expect the next token to match the specified keyword.
57377 // If not, an exception will be thrown.
57378
57379 function expectKeyword(keyword) {
57380 var token = lex();
57381 if (token.type !== Token.Keyword || token.value !== keyword) {
57382 throwUnexpectedToken(token);
57383 }
57384 }
57385
57386 // Return true if the next token matches the specified punctuator.
57387
57388 function match(value) {
57389 return lookahead.type === Token.Punctuator && lookahead.value === value;
57390 }
57391
57392 // Return true if the next token matches the specified keyword
57393
57394 function matchKeyword(keyword) {
57395 return lookahead.type === Token.Keyword && lookahead.value === keyword;
57396 }
57397
57398 // Return true if the next token matches the specified contextual keyword
57399 // (where an identifier is sometimes a keyword depending on the context)
57400
57401 function matchContextualKeyword(keyword) {
57402 return lookahead.type === Token.Identifier && lookahead.value === keyword;
57403 }
57404
57405 // Return true if the next token is an assignment operator
57406
57407 function matchAssign() {
57408 var op;
57409
57410 if (lookahead.type !== Token.Punctuator) {
57411 return false;
57412 }
57413 op = lookahead.value;
57414 return op === '=' ||
57415 op === '*=' ||
57416 op === '/=' ||
57417 op === '%=' ||
57418 op === '+=' ||
57419 op === '-=' ||
57420 op === '<<=' ||
57421 op === '>>=' ||
57422 op === '>>>=' ||
57423 op === '&=' ||
57424 op === '^=' ||
57425 op === '|=';
57426 }
57427
57428 function consumeSemicolon() {
57429 // Catch the very common case first: immediately a semicolon (U+003B).
57430 if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
57431 lex();
57432 return;
57433 }
57434
57435 if (hasLineTerminator) {
57436 return;
57437 }
57438
57439 // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
57440 lastIndex = startIndex;
57441 lastLineNumber = startLineNumber;
57442 lastLineStart = startLineStart;
57443
57444 if (lookahead.type !== Token.EOF && !match('}')) {
57445 throwUnexpectedToken(lookahead);
57446 }
57447 }
57448
57449 // Cover grammar support.
57450 //
57451 // When an assignment expression position starts with an left parenthesis, the determination of the type
57452 // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
57453 // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
57454 //
57455 // There are three productions that can be parsed in a parentheses pair that needs to be determined
57456 // after the outermost pair is closed. They are:
57457 //
57458 // 1. AssignmentExpression
57459 // 2. BindingElements
57460 // 3. AssignmentTargets
57461 //
57462 // In order to avoid exponential backtracking, we use two flags to denote if the production can be
57463 // binding element or assignment target.
57464 //
57465 // The three productions have the relationship:
57466 //
57467 // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
57468 //
57469 // with a single exception that CoverInitializedName when used directly in an Expression, generates
57470 // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
57471 // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
57472 //
57473 // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
57474 // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
57475 // the CoverInitializedName check is conducted.
57476 //
57477 // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
57478 // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
57479 // pattern. The CoverInitializedName check is deferred.
57480 function isolateCoverGrammar(parser) {
57481 var oldIsBindingElement = isBindingElement,
57482 oldIsAssignmentTarget = isAssignmentTarget,
57483 oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
57484 result;
57485 isBindingElement = true;
57486 isAssignmentTarget = true;
57487 firstCoverInitializedNameError = null;
57488 result = parser();
57489 if (firstCoverInitializedNameError !== null) {
57490 throwUnexpectedToken(firstCoverInitializedNameError);
57491 }
57492 isBindingElement = oldIsBindingElement;
57493 isAssignmentTarget = oldIsAssignmentTarget;
57494 firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
57495 return result;
57496 }
57497
57498 function inheritCoverGrammar(parser) {
57499 var oldIsBindingElement = isBindingElement,
57500 oldIsAssignmentTarget = isAssignmentTarget,
57501 oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
57502 result;
57503 isBindingElement = true;
57504 isAssignmentTarget = true;
57505 firstCoverInitializedNameError = null;
57506 result = parser();
57507 isBindingElement = isBindingElement && oldIsBindingElement;
57508 isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
57509 firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
57510 return result;
57511 }
57512
57513 // ECMA-262 13.3.3 Destructuring Binding Patterns
57514
57515 function parseArrayPattern(params, kind) {
57516 var node = new Node(), elements = [], rest, restNode;
57517 expect('[');
57518
57519 while (!match(']')) {
57520 if (match(',')) {
57521 lex();
57522 elements.push(null);
57523 } else {
57524 if (match('...')) {
57525 restNode = new Node();
57526 lex();
57527 params.push(lookahead);
57528 rest = parseVariableIdentifier(kind);
57529 elements.push(restNode.finishRestElement(rest));
57530 break;
57531 } else {
57532 elements.push(parsePatternWithDefault(params, kind));
57533 }
57534 if (!match(']')) {
57535 expect(',');
57536 }
57537 }
57538
57539 }
57540
57541 expect(']');
57542
57543 return node.finishArrayPattern(elements);
57544 }
57545
57546 function parsePropertyPattern(params, kind) {
57547 var node = new Node(), key, keyToken, computed = match('['), init;
57548 if (lookahead.type === Token.Identifier) {
57549 keyToken = lookahead;
57550 key = parseVariableIdentifier();
57551 if (match('=')) {
57552 params.push(keyToken);
57553 lex();
57554 init = parseAssignmentExpression();
57555
57556 return node.finishProperty(
57557 'init', key, false,
57558 new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, false);
57559 } else if (!match(':')) {
57560 params.push(keyToken);
57561 return node.finishProperty('init', key, false, key, false, true);
57562 }
57563 } else {
57564 key = parseObjectPropertyKey();
57565 }
57566 expect(':');
57567 init = parsePatternWithDefault(params, kind);
57568 return node.finishProperty('init', key, computed, init, false, false);
57569 }
57570
57571 function parseObjectPattern(params, kind) {
57572 var node = new Node(), properties = [];
57573
57574 expect('{');
57575
57576 while (!match('}')) {
57577 properties.push(parsePropertyPattern(params, kind));
57578 if (!match('}')) {
57579 expect(',');
57580 }
57581 }
57582
57583 lex();
57584
57585 return node.finishObjectPattern(properties);
57586 }
57587
57588 function parsePattern(params, kind) {
57589 if (match('[')) {
57590 return parseArrayPattern(params, kind);
57591 } else if (match('{')) {
57592 return parseObjectPattern(params, kind);
57593 } else if (matchKeyword('let')) {
57594 if (kind === 'const' || kind === 'let') {
57595 tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
57596 }
57597 }
57598
57599 params.push(lookahead);
57600 return parseVariableIdentifier(kind);
57601 }
57602
57603 function parsePatternWithDefault(params, kind) {
57604 var startToken = lookahead, pattern, previousAllowYield, right;
57605 pattern = parsePattern(params, kind);
57606 if (match('=')) {
57607 lex();
57608 previousAllowYield = state.allowYield;
57609 state.allowYield = true;
57610 right = isolateCoverGrammar(parseAssignmentExpression);
57611 state.allowYield = previousAllowYield;
57612 pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
57613 }
57614 return pattern;
57615 }
57616
57617 // ECMA-262 12.2.5 Array Initializer
57618
57619 function parseArrayInitializer() {
57620 var elements = [], node = new Node(), restSpread;
57621
57622 expect('[');
57623
57624 while (!match(']')) {
57625 if (match(',')) {
57626 lex();
57627 elements.push(null);
57628 } else if (match('...')) {
57629 restSpread = new Node();
57630 lex();
57631 restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
57632
57633 if (!match(']')) {
57634 isAssignmentTarget = isBindingElement = false;
57635 expect(',');
57636 }
57637 elements.push(restSpread);
57638 } else {
57639 elements.push(inheritCoverGrammar(parseAssignmentExpression));
57640
57641 if (!match(']')) {
57642 expect(',');
57643 }
57644 }
57645 }
57646
57647 lex();
57648
57649 return node.finishArrayExpression(elements);
57650 }
57651
57652 // ECMA-262 12.2.6 Object Initializer
57653
57654 function parsePropertyFunction(node, paramInfo, isGenerator) {
57655 var previousStrict, body;
57656
57657 isAssignmentTarget = isBindingElement = false;
57658
57659 previousStrict = strict;
57660 body = isolateCoverGrammar(parseFunctionSourceElements);
57661
57662 if (strict && paramInfo.firstRestricted) {
57663 tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
57664 }
57665 if (strict && paramInfo.stricted) {
57666 tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
57667 }
57668
57669 strict = previousStrict;
57670 return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
57671 }
57672
57673 function parsePropertyMethodFunction() {
57674 var params, method, node = new Node(),
57675 previousAllowYield = state.allowYield;
57676
57677 state.allowYield = false;
57678 params = parseParams();
57679 state.allowYield = previousAllowYield;
57680
57681 state.allowYield = false;
57682 method = parsePropertyFunction(node, params, false);
57683 state.allowYield = previousAllowYield;
57684
57685 return method;
57686 }
57687
57688 function parseObjectPropertyKey() {
57689 var token, node = new Node(), expr;
57690
57691 token = lex();
57692
57693 // Note: This function is called only from parseObjectProperty(), where
57694 // EOF and Punctuator tokens are already filtered out.
57695
57696 switch (token.type) {
57697 case Token.StringLiteral:
57698 case Token.NumericLiteral:
57699 if (strict && token.octal) {
57700 tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
57701 }
57702 return node.finishLiteral(token);
57703 case Token.Identifier:
57704 case Token.BooleanLiteral:
57705 case Token.NullLiteral:
57706 case Token.Keyword:
57707 return node.finishIdentifier(token.value);
57708 case Token.Punctuator:
57709 if (token.value === '[') {
57710 expr = isolateCoverGrammar(parseAssignmentExpression);
57711 expect(']');
57712 return expr;
57713 }
57714 break;
57715 }
57716 throwUnexpectedToken(token);
57717 }
57718
57719 function lookaheadPropertyName() {
57720 switch (lookahead.type) {
57721 case Token.Identifier:
57722 case Token.StringLiteral:
57723 case Token.BooleanLiteral:
57724 case Token.NullLiteral:
57725 case Token.NumericLiteral:
57726 case Token.Keyword:
57727 return true;
57728 case Token.Punctuator:
57729 return lookahead.value === '[';
57730 }
57731 return false;
57732 }
57733
57734 // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
57735 // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
57736 // This can only be determined after we consumed up to the left parentheses.
57737 //
57738 // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
57739 // is responsible to visit other options.
57740 function tryParseMethodDefinition(token, key, computed, node) {
57741 var value, options, methodNode, params,
57742 previousAllowYield = state.allowYield;
57743
57744 if (token.type === Token.Identifier) {
57745 // check for `get` and `set`;
57746
57747 if (token.value === 'get' && lookaheadPropertyName()) {
57748 computed = match('[');
57749 key = parseObjectPropertyKey();
57750 methodNode = new Node();
57751 expect('(');
57752 expect(')');
57753
57754 state.allowYield = false;
57755 value = parsePropertyFunction(methodNode, {
57756 params: [],
57757 defaults: [],
57758 stricted: null,
57759 firstRestricted: null,
57760 message: null
57761 }, false);
57762 state.allowYield = previousAllowYield;
57763
57764 return node.finishProperty('get', key, computed, value, false, false);
57765 } else if (token.value === 'set' && lookaheadPropertyName()) {
57766 computed = match('[');
57767 key = parseObjectPropertyKey();
57768 methodNode = new Node();
57769 expect('(');
57770
57771 options = {
57772 params: [],
57773 defaultCount: 0,
57774 defaults: [],
57775 firstRestricted: null,
57776 paramSet: {}
57777 };
57778 if (match(')')) {
57779 tolerateUnexpectedToken(lookahead);
57780 } else {
57781 state.allowYield = false;
57782 parseParam(options);
57783 state.allowYield = previousAllowYield;
57784 if (options.defaultCount === 0) {
57785 options.defaults = [];
57786 }
57787 }
57788 expect(')');
57789
57790 state.allowYield = false;
57791 value = parsePropertyFunction(methodNode, options, false);
57792 state.allowYield = previousAllowYield;
57793
57794 return node.finishProperty('set', key, computed, value, false, false);
57795 }
57796 } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
57797 computed = match('[');
57798 key = parseObjectPropertyKey();
57799 methodNode = new Node();
57800
57801 state.allowYield = true;
57802 params = parseParams();
57803 state.allowYield = previousAllowYield;
57804
57805 state.allowYield = false;
57806 value = parsePropertyFunction(methodNode, params, true);
57807 state.allowYield = previousAllowYield;
57808
57809 return node.finishProperty('init', key, computed, value, true, false);
57810 }
57811
57812 if (key && match('(')) {
57813 value = parsePropertyMethodFunction();
57814 return node.finishProperty('init', key, computed, value, true, false);
57815 }
57816
57817 // Not a MethodDefinition.
57818 return null;
57819 }
57820
57821 function parseObjectProperty(hasProto) {
57822 var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;
57823
57824 computed = match('[');
57825 if (match('*')) {
57826 lex();
57827 } else {
57828 key = parseObjectPropertyKey();
57829 }
57830 maybeMethod = tryParseMethodDefinition(token, key, computed, node);
57831 if (maybeMethod) {
57832 return maybeMethod;
57833 }
57834
57835 if (!key) {
57836 throwUnexpectedToken(lookahead);
57837 }
57838
57839 // Check for duplicated __proto__
57840 if (!computed) {
57841 proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
57842 (key.type === Syntax.Literal && key.value === '__proto__');
57843 if (hasProto.value && proto) {
57844 tolerateError(Messages.DuplicateProtoProperty);
57845 }
57846 hasProto.value |= proto;
57847 }
57848
57849 if (match(':')) {
57850 lex();
57851 value = inheritCoverGrammar(parseAssignmentExpression);
57852 return node.finishProperty('init', key, computed, value, false, false);
57853 }
57854
57855 if (token.type === Token.Identifier) {
57856 if (match('=')) {
57857 firstCoverInitializedNameError = lookahead;
57858 lex();
57859 value = isolateCoverGrammar(parseAssignmentExpression);
57860 return node.finishProperty('init', key, computed,
57861 new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
57862 }
57863 return node.finishProperty('init', key, computed, key, false, true);
57864 }
57865
57866 throwUnexpectedToken(lookahead);
57867 }
57868
57869 function parseObjectInitializer() {
57870 var properties = [], hasProto = {value: false}, node = new Node();
57871
57872 expect('{');
57873
57874 while (!match('}')) {
57875 properties.push(parseObjectProperty(hasProto));
57876
57877 if (!match('}')) {
57878 expectCommaSeparator();
57879 }
57880 }
57881
57882 expect('}');
57883
57884 return node.finishObjectExpression(properties);
57885 }
57886
57887 function reinterpretExpressionAsPattern(expr) {
57888 var i;
57889 switch (expr.type) {
57890 case Syntax.Identifier:
57891 case Syntax.MemberExpression:
57892 case Syntax.RestElement:
57893 case Syntax.AssignmentPattern:
57894 break;
57895 case Syntax.SpreadElement:
57896 expr.type = Syntax.RestElement;
57897 reinterpretExpressionAsPattern(expr.argument);
57898 break;
57899 case Syntax.ArrayExpression:
57900 expr.type = Syntax.ArrayPattern;
57901 for (i = 0; i < expr.elements.length; i++) {
57902 if (expr.elements[i] !== null) {
57903 reinterpretExpressionAsPattern(expr.elements[i]);
57904 }
57905 }
57906 break;
57907 case Syntax.ObjectExpression:
57908 expr.type = Syntax.ObjectPattern;
57909 for (i = 0; i < expr.properties.length; i++) {
57910 reinterpretExpressionAsPattern(expr.properties[i].value);
57911 }
57912 break;
57913 case Syntax.AssignmentExpression:
57914 expr.type = Syntax.AssignmentPattern;
57915 reinterpretExpressionAsPattern(expr.left);
57916 break;
57917 default:
57918 // Allow other node type for tolerant parsing.
57919 break;
57920 }
57921 }
57922
57923 // ECMA-262 12.2.9 Template Literals
57924
57925 function parseTemplateElement(option) {
57926 var node, token;
57927
57928 if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
57929 throwUnexpectedToken();
57930 }
57931
57932 node = new Node();
57933 token = lex();
57934
57935 return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
57936 }
57937
57938 function parseTemplateLiteral() {
57939 var quasi, quasis, expressions, node = new Node();
57940
57941 quasi = parseTemplateElement({ head: true });
57942 quasis = [quasi];
57943 expressions = [];
57944
57945 while (!quasi.tail) {
57946 expressions.push(parseExpression());
57947 quasi = parseTemplateElement({ head: false });
57948 quasis.push(quasi);
57949 }
57950
57951 return node.finishTemplateLiteral(quasis, expressions);
57952 }
57953
57954 // ECMA-262 12.2.10 The Grouping Operator
57955
57956 function parseGroupExpression() {
57957 var expr, expressions, startToken, i, params = [];
57958
57959 expect('(');
57960
57961 if (match(')')) {
57962 lex();
57963 if (!match('=>')) {
57964 expect('=>');
57965 }
57966 return {
57967 type: PlaceHolders.ArrowParameterPlaceHolder,
57968 params: [],
57969 rawParams: []
57970 };
57971 }
57972
57973 startToken = lookahead;
57974 if (match('...')) {
57975 expr = parseRestElement(params);
57976 expect(')');
57977 if (!match('=>')) {
57978 expect('=>');
57979 }
57980 return {
57981 type: PlaceHolders.ArrowParameterPlaceHolder,
57982 params: [expr]
57983 };
57984 }
57985
57986 isBindingElement = true;
57987 expr = inheritCoverGrammar(parseAssignmentExpression);
57988
57989 if (match(',')) {
57990 isAssignmentTarget = false;
57991 expressions = [expr];
57992
57993 while (startIndex < length) {
57994 if (!match(',')) {
57995 break;
57996 }
57997 lex();
57998
57999 if (match('...')) {
58000 if (!isBindingElement) {
58001 throwUnexpectedToken(lookahead);
58002 }
58003 expressions.push(parseRestElement(params));
58004 expect(')');
58005 if (!match('=>')) {
58006 expect('=>');
58007 }
58008 isBindingElement = false;
58009 for (i = 0; i < expressions.length; i++) {
58010 reinterpretExpressionAsPattern(expressions[i]);
58011 }
58012 return {
58013 type: PlaceHolders.ArrowParameterPlaceHolder,
58014 params: expressions
58015 };
58016 }
58017
58018 expressions.push(inheritCoverGrammar(parseAssignmentExpression));
58019 }
58020
58021 expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
58022 }
58023
58024
58025 expect(')');
58026
58027 if (match('=>')) {
58028 if (expr.type === Syntax.Identifier && expr.name === 'yield') {
58029 return {
58030 type: PlaceHolders.ArrowParameterPlaceHolder,
58031 params: [expr]
58032 };
58033 }
58034
58035 if (!isBindingElement) {
58036 throwUnexpectedToken(lookahead);
58037 }
58038
58039 if (expr.type === Syntax.SequenceExpression) {
58040 for (i = 0; i < expr.expressions.length; i++) {
58041 reinterpretExpressionAsPattern(expr.expressions[i]);
58042 }
58043 } else {
58044 reinterpretExpressionAsPattern(expr);
58045 }
58046
58047 expr = {
58048 type: PlaceHolders.ArrowParameterPlaceHolder,
58049 params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
58050 };
58051 }
58052 isBindingElement = false;
58053 return expr;
58054 }
58055
58056
58057 // ECMA-262 12.2 Primary Expressions
58058
58059 function parsePrimaryExpression() {
58060 var type, token, expr, node;
58061
58062 if (match('(')) {
58063 isBindingElement = false;
58064 return inheritCoverGrammar(parseGroupExpression);
58065 }
58066
58067 if (match('[')) {
58068 return inheritCoverGrammar(parseArrayInitializer);
58069 }
58070
58071 if (match('{')) {
58072 return inheritCoverGrammar(parseObjectInitializer);
58073 }
58074
58075 type = lookahead.type;
58076 node = new Node();
58077
58078 if (type === Token.Identifier) {
58079 if (state.sourceType === 'module' && lookahead.value === 'await') {
58080 tolerateUnexpectedToken(lookahead);
58081 }
58082 expr = node.finishIdentifier(lex().value);
58083 } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
58084 isAssignmentTarget = isBindingElement = false;
58085 if (strict && lookahead.octal) {
58086 tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
58087 }
58088 expr = node.finishLiteral(lex());
58089 } else if (type === Token.Keyword) {
58090 if (!strict && state.allowYield && matchKeyword('yield')) {
58091 return parseNonComputedProperty();
58092 }
58093 isAssignmentTarget = isBindingElement = false;
58094 if (matchKeyword('function')) {
58095 return parseFunctionExpression();
58096 }
58097 if (matchKeyword('this')) {
58098 lex();
58099 return node.finishThisExpression();
58100 }
58101 if (matchKeyword('class')) {
58102 return parseClassExpression();
58103 }
58104 if (!strict && matchKeyword('let')) {
58105 return node.finishIdentifier(lex().value);
58106 }
58107 throwUnexpectedToken(lex());
58108 } else if (type === Token.BooleanLiteral) {
58109 isAssignmentTarget = isBindingElement = false;
58110 token = lex();
58111 token.value = (token.value === 'true');
58112 expr = node.finishLiteral(token);
58113 } else if (type === Token.NullLiteral) {
58114 isAssignmentTarget = isBindingElement = false;
58115 token = lex();
58116 token.value = null;
58117 expr = node.finishLiteral(token);
58118 } else if (match('/') || match('/=')) {
58119 isAssignmentTarget = isBindingElement = false;
58120 index = startIndex;
58121
58122 if (typeof extra.tokens !== 'undefined') {
58123 token = collectRegex();
58124 } else {
58125 token = scanRegExp();
58126 }
58127 lex();
58128 expr = node.finishLiteral(token);
58129 } else if (type === Token.Template) {
58130 expr = parseTemplateLiteral();
58131 } else {
58132 throwUnexpectedToken(lex());
58133 }
58134
58135 return expr;
58136 }
58137
58138 // ECMA-262 12.3 Left-Hand-Side Expressions
58139
58140 function parseArguments() {
58141 var args = [], expr;
58142
58143 expect('(');
58144
58145 if (!match(')')) {
58146 while (startIndex < length) {
58147 if (match('...')) {
58148 expr = new Node();
58149 lex();
58150 expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
58151 } else {
58152 expr = isolateCoverGrammar(parseAssignmentExpression);
58153 }
58154 args.push(expr);
58155 if (match(')')) {
58156 break;
58157 }
58158 expectCommaSeparator();
58159 }
58160 }
58161
58162 expect(')');
58163
58164 return args;
58165 }
58166
58167 function parseNonComputedProperty() {
58168 var token, node = new Node();
58169
58170 token = lex();
58171
58172 if (!isIdentifierName(token)) {
58173 throwUnexpectedToken(token);
58174 }
58175
58176 return node.finishIdentifier(token.value);
58177 }
58178
58179 function parseNonComputedMember() {
58180 expect('.');
58181
58182 return parseNonComputedProperty();
58183 }
58184
58185 function parseComputedMember() {
58186 var expr;
58187
58188 expect('[');
58189
58190 expr = isolateCoverGrammar(parseExpression);
58191
58192 expect(']');
58193
58194 return expr;
58195 }
58196
58197 // ECMA-262 12.3.3 The new Operator
58198
58199 function parseNewExpression() {
58200 var callee, args, node = new Node();
58201
58202 expectKeyword('new');
58203
58204 if (match('.')) {
58205 lex();
58206 if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
58207 if (state.inFunctionBody) {
58208 lex();
58209 return node.finishMetaProperty('new', 'target');
58210 }
58211 }
58212 throwUnexpectedToken(lookahead);
58213 }
58214
58215 callee = isolateCoverGrammar(parseLeftHandSideExpression);
58216 args = match('(') ? parseArguments() : [];
58217
58218 isAssignmentTarget = isBindingElement = false;
58219
58220 return node.finishNewExpression(callee, args);
58221 }
58222
58223 // ECMA-262 12.3.4 Function Calls
58224
58225 function parseLeftHandSideExpressionAllowCall() {
58226 var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
58227
58228 startToken = lookahead;
58229 state.allowIn = true;
58230
58231 if (matchKeyword('super') && state.inFunctionBody) {
58232 expr = new Node();
58233 lex();
58234 expr = expr.finishSuper();
58235 if (!match('(') && !match('.') && !match('[')) {
58236 throwUnexpectedToken(lookahead);
58237 }
58238 } else {
58239 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
58240 }
58241
58242 for (;;) {
58243 if (match('.')) {
58244 isBindingElement = false;
58245 isAssignmentTarget = true;
58246 property = parseNonComputedMember();
58247 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
58248 } else if (match('(')) {
58249 isBindingElement = false;
58250 isAssignmentTarget = false;
58251 args = parseArguments();
58252 expr = new WrappingNode(startToken).finishCallExpression(expr, args);
58253 } else if (match('[')) {
58254 isBindingElement = false;
58255 isAssignmentTarget = true;
58256 property = parseComputedMember();
58257 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
58258 } else if (lookahead.type === Token.Template && lookahead.head) {
58259 quasi = parseTemplateLiteral();
58260 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
58261 } else {
58262 break;
58263 }
58264 }
58265 state.allowIn = previousAllowIn;
58266
58267 return expr;
58268 }
58269
58270 // ECMA-262 12.3 Left-Hand-Side Expressions
58271
58272 function parseLeftHandSideExpression() {
58273 var quasi, expr, property, startToken;
58274 assert(state.allowIn, 'callee of new expression always allow in keyword.');
58275
58276 startToken = lookahead;
58277
58278 if (matchKeyword('super') && state.inFunctionBody) {
58279 expr = new Node();
58280 lex();
58281 expr = expr.finishSuper();
58282 if (!match('[') && !match('.')) {
58283 throwUnexpectedToken(lookahead);
58284 }
58285 } else {
58286 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
58287 }
58288
58289 for (;;) {
58290 if (match('[')) {
58291 isBindingElement = false;
58292 isAssignmentTarget = true;
58293 property = parseComputedMember();
58294 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
58295 } else if (match('.')) {
58296 isBindingElement = false;
58297 isAssignmentTarget = true;
58298 property = parseNonComputedMember();
58299 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
58300 } else if (lookahead.type === Token.Template && lookahead.head) {
58301 quasi = parseTemplateLiteral();
58302 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
58303 } else {
58304 break;
58305 }
58306 }
58307 return expr;
58308 }
58309
58310 // ECMA-262 12.4 Postfix Expressions
58311
58312 function parsePostfixExpression() {
58313 var expr, token, startToken = lookahead;
58314
58315 expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
58316
58317 if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
58318 if (match('++') || match('--')) {
58319 // ECMA-262 11.3.1, 11.3.2
58320 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
58321 tolerateError(Messages.StrictLHSPostfix);
58322 }
58323
58324 if (!isAssignmentTarget) {
58325 tolerateError(Messages.InvalidLHSInAssignment);
58326 }
58327
58328 isAssignmentTarget = isBindingElement = false;
58329
58330 token = lex();
58331 expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
58332 }
58333 }
58334
58335 return expr;
58336 }
58337
58338 // ECMA-262 12.5 Unary Operators
58339
58340 function parseUnaryExpression() {
58341 var token, expr, startToken;
58342
58343 if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
58344 expr = parsePostfixExpression();
58345 } else if (match('++') || match('--')) {
58346 startToken = lookahead;
58347 token = lex();
58348 expr = inheritCoverGrammar(parseUnaryExpression);
58349 // ECMA-262 11.4.4, 11.4.5
58350 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
58351 tolerateError(Messages.StrictLHSPrefix);
58352 }
58353
58354 if (!isAssignmentTarget) {
58355 tolerateError(Messages.InvalidLHSInAssignment);
58356 }
58357 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
58358 isAssignmentTarget = isBindingElement = false;
58359 } else if (match('+') || match('-') || match('~') || match('!')) {
58360 startToken = lookahead;
58361 token = lex();
58362 expr = inheritCoverGrammar(parseUnaryExpression);
58363 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
58364 isAssignmentTarget = isBindingElement = false;
58365 } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
58366 startToken = lookahead;
58367 token = lex();
58368 expr = inheritCoverGrammar(parseUnaryExpression);
58369 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
58370 if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
58371 tolerateError(Messages.StrictDelete);
58372 }
58373 isAssignmentTarget = isBindingElement = false;
58374 } else {
58375 expr = parsePostfixExpression();
58376 }
58377
58378 return expr;
58379 }
58380
58381 function binaryPrecedence(token, allowIn) {
58382 var prec = 0;
58383
58384 if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
58385 return 0;
58386 }
58387
58388 switch (token.value) {
58389 case '||':
58390 prec = 1;
58391 break;
58392
58393 case '&&':
58394 prec = 2;
58395 break;
58396
58397 case '|':
58398 prec = 3;
58399 break;
58400
58401 case '^':
58402 prec = 4;
58403 break;
58404
58405 case '&':
58406 prec = 5;
58407 break;
58408
58409 case '==':
58410 case '!=':
58411 case '===':
58412 case '!==':
58413 prec = 6;
58414 break;
58415
58416 case '<':
58417 case '>':
58418 case '<=':
58419 case '>=':
58420 case 'instanceof':
58421 prec = 7;
58422 break;
58423
58424 case 'in':
58425 prec = allowIn ? 7 : 0;
58426 break;
58427
58428 case '<<':
58429 case '>>':
58430 case '>>>':
58431 prec = 8;
58432 break;
58433
58434 case '+':
58435 case '-':
58436 prec = 9;
58437 break;
58438
58439 case '*':
58440 case '/':
58441 case '%':
58442 prec = 11;
58443 break;
58444
58445 default:
58446 break;
58447 }
58448
58449 return prec;
58450 }
58451
58452 // ECMA-262 12.6 Multiplicative Operators
58453 // ECMA-262 12.7 Additive Operators
58454 // ECMA-262 12.8 Bitwise Shift Operators
58455 // ECMA-262 12.9 Relational Operators
58456 // ECMA-262 12.10 Equality Operators
58457 // ECMA-262 12.11 Binary Bitwise Operators
58458 // ECMA-262 12.12 Binary Logical Operators
58459
58460 function parseBinaryExpression() {
58461 var marker, markers, expr, token, prec, stack, right, operator, left, i;
58462
58463 marker = lookahead;
58464 left = inheritCoverGrammar(parseUnaryExpression);
58465
58466 token = lookahead;
58467 prec = binaryPrecedence(token, state.allowIn);
58468 if (prec === 0) {
58469 return left;
58470 }
58471 isAssignmentTarget = isBindingElement = false;
58472 token.prec = prec;
58473 lex();
58474
58475 markers = [marker, lookahead];
58476 right = isolateCoverGrammar(parseUnaryExpression);
58477
58478 stack = [left, token, right];
58479
58480 while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
58481
58482 // Reduce: make a binary expression from the three topmost entries.
58483 while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
58484 right = stack.pop();
58485 operator = stack.pop().value;
58486 left = stack.pop();
58487 markers.pop();
58488 expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
58489 stack.push(expr);
58490 }
58491
58492 // Shift.
58493 token = lex();
58494 token.prec = prec;
58495 stack.push(token);
58496 markers.push(lookahead);
58497 expr = isolateCoverGrammar(parseUnaryExpression);
58498 stack.push(expr);
58499 }
58500
58501 // Final reduce to clean-up the stack.
58502 i = stack.length - 1;
58503 expr = stack[i];
58504 markers.pop();
58505 while (i > 1) {
58506 expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
58507 i -= 2;
58508 }
58509
58510 return expr;
58511 }
58512
58513
58514 // ECMA-262 12.13 Conditional Operator
58515
58516 function parseConditionalExpression() {
58517 var expr, previousAllowIn, consequent, alternate, startToken;
58518
58519 startToken = lookahead;
58520
58521 expr = inheritCoverGrammar(parseBinaryExpression);
58522 if (match('?')) {
58523 lex();
58524 previousAllowIn = state.allowIn;
58525 state.allowIn = true;
58526 consequent = isolateCoverGrammar(parseAssignmentExpression);
58527 state.allowIn = previousAllowIn;
58528 expect(':');
58529 alternate = isolateCoverGrammar(parseAssignmentExpression);
58530
58531 expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
58532 isAssignmentTarget = isBindingElement = false;
58533 }
58534
58535 return expr;
58536 }
58537
58538 // ECMA-262 14.2 Arrow Function Definitions
58539
58540 function parseConciseBody() {
58541 if (match('{')) {
58542 return parseFunctionSourceElements();
58543 }
58544 return isolateCoverGrammar(parseAssignmentExpression);
58545 }
58546
58547 function checkPatternParam(options, param) {
58548 var i;
58549 switch (param.type) {
58550 case Syntax.Identifier:
58551 validateParam(options, param, param.name);
58552 break;
58553 case Syntax.RestElement:
58554 checkPatternParam(options, param.argument);
58555 break;
58556 case Syntax.AssignmentPattern:
58557 checkPatternParam(options, param.left);
58558 break;
58559 case Syntax.ArrayPattern:
58560 for (i = 0; i < param.elements.length; i++) {
58561 if (param.elements[i] !== null) {
58562 checkPatternParam(options, param.elements[i]);
58563 }
58564 }
58565 break;
58566 case Syntax.YieldExpression:
58567 break;
58568 default:
58569 assert(param.type === Syntax.ObjectPattern, 'Invalid type');
58570 for (i = 0; i < param.properties.length; i++) {
58571 checkPatternParam(options, param.properties[i].value);
58572 }
58573 break;
58574 }
58575 }
58576 function reinterpretAsCoverFormalsList(expr) {
58577 var i, len, param, params, defaults, defaultCount, options, token;
58578
58579 defaults = [];
58580 defaultCount = 0;
58581 params = [expr];
58582
58583 switch (expr.type) {
58584 case Syntax.Identifier:
58585 break;
58586 case PlaceHolders.ArrowParameterPlaceHolder:
58587 params = expr.params;
58588 break;
58589 default:
58590 return null;
58591 }
58592
58593 options = {
58594 paramSet: {}
58595 };
58596
58597 for (i = 0, len = params.length; i < len; i += 1) {
58598 param = params[i];
58599 switch (param.type) {
58600 case Syntax.AssignmentPattern:
58601 params[i] = param.left;
58602 if (param.right.type === Syntax.YieldExpression) {
58603 if (param.right.argument) {
58604 throwUnexpectedToken(lookahead);
58605 }
58606 param.right.type = Syntax.Identifier;
58607 param.right.name = 'yield';
58608 delete param.right.argument;
58609 delete param.right.delegate;
58610 }
58611 defaults.push(param.right);
58612 ++defaultCount;
58613 checkPatternParam(options, param.left);
58614 break;
58615 default:
58616 checkPatternParam(options, param);
58617 params[i] = param;
58618 defaults.push(null);
58619 break;
58620 }
58621 }
58622
58623 if (strict || !state.allowYield) {
58624 for (i = 0, len = params.length; i < len; i += 1) {
58625 param = params[i];
58626 if (param.type === Syntax.YieldExpression) {
58627 throwUnexpectedToken(lookahead);
58628 }
58629 }
58630 }
58631
58632 if (options.message === Messages.StrictParamDupe) {
58633 token = strict ? options.stricted : options.firstRestricted;
58634 throwUnexpectedToken(token, options.message);
58635 }
58636
58637 if (defaultCount === 0) {
58638 defaults = [];
58639 }
58640
58641 return {
58642 params: params,
58643 defaults: defaults,
58644 stricted: options.stricted,
58645 firstRestricted: options.firstRestricted,
58646 message: options.message
58647 };
58648 }
58649
58650 function parseArrowFunctionExpression(options, node) {
58651 var previousStrict, previousAllowYield, body;
58652
58653 if (hasLineTerminator) {
58654 tolerateUnexpectedToken(lookahead);
58655 }
58656 expect('=>');
58657
58658 previousStrict = strict;
58659 previousAllowYield = state.allowYield;
58660 state.allowYield = true;
58661
58662 body = parseConciseBody();
58663
58664 if (strict && options.firstRestricted) {
58665 throwUnexpectedToken(options.firstRestricted, options.message);
58666 }
58667 if (strict && options.stricted) {
58668 tolerateUnexpectedToken(options.stricted, options.message);
58669 }
58670
58671 strict = previousStrict;
58672 state.allowYield = previousAllowYield;
58673
58674 return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
58675 }
58676
58677 // ECMA-262 14.4 Yield expression
58678
58679 function parseYieldExpression() {
58680 var argument, expr, delegate, previousAllowYield;
58681
58682 argument = null;
58683 expr = new Node();
58684
58685 expectKeyword('yield');
58686
58687 if (!hasLineTerminator) {
58688 previousAllowYield = state.allowYield;
58689 state.allowYield = false;
58690 delegate = match('*');
58691 if (delegate) {
58692 lex();
58693 argument = parseAssignmentExpression();
58694 } else {
58695 if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
58696 argument = parseAssignmentExpression();
58697 }
58698 }
58699 state.allowYield = previousAllowYield;
58700 }
58701
58702 return expr.finishYieldExpression(argument, delegate);
58703 }
58704
58705 // ECMA-262 12.14 Assignment Operators
58706
58707 function parseAssignmentExpression() {
58708 var token, expr, right, list, startToken;
58709
58710 startToken = lookahead;
58711 token = lookahead;
58712
58713 if (!state.allowYield && matchKeyword('yield')) {
58714 return parseYieldExpression();
58715 }
58716
58717 expr = parseConditionalExpression();
58718
58719 if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
58720 isAssignmentTarget = isBindingElement = false;
58721 list = reinterpretAsCoverFormalsList(expr);
58722
58723 if (list) {
58724 firstCoverInitializedNameError = null;
58725 return parseArrowFunctionExpression(list, new WrappingNode(startToken));
58726 }
58727
58728 return expr;
58729 }
58730
58731 if (matchAssign()) {
58732 if (!isAssignmentTarget) {
58733 tolerateError(Messages.InvalidLHSInAssignment);
58734 }
58735
58736 // ECMA-262 12.1.1
58737 if (strict && expr.type === Syntax.Identifier) {
58738 if (isRestrictedWord(expr.name)) {
58739 tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
58740 }
58741 if (isStrictModeReservedWord(expr.name)) {
58742 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
58743 }
58744 }
58745
58746 if (!match('=')) {
58747 isAssignmentTarget = isBindingElement = false;
58748 } else {
58749 reinterpretExpressionAsPattern(expr);
58750 }
58751
58752 token = lex();
58753 right = isolateCoverGrammar(parseAssignmentExpression);
58754 expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
58755 firstCoverInitializedNameError = null;
58756 }
58757
58758 return expr;
58759 }
58760
58761 // ECMA-262 12.15 Comma Operator
58762
58763 function parseExpression() {
58764 var expr, startToken = lookahead, expressions;
58765
58766 expr = isolateCoverGrammar(parseAssignmentExpression);
58767
58768 if (match(',')) {
58769 expressions = [expr];
58770
58771 while (startIndex < length) {
58772 if (!match(',')) {
58773 break;
58774 }
58775 lex();
58776 expressions.push(isolateCoverGrammar(parseAssignmentExpression));
58777 }
58778
58779 expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
58780 }
58781
58782 return expr;
58783 }
58784
58785 // ECMA-262 13.2 Block
58786
58787 function parseStatementListItem() {
58788 if (lookahead.type === Token.Keyword) {
58789 switch (lookahead.value) {
58790 case 'export':
58791 if (state.sourceType !== 'module') {
58792 tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
58793 }
58794 return parseExportDeclaration();
58795 case 'import':
58796 if (state.sourceType !== 'module') {
58797 tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
58798 }
58799 return parseImportDeclaration();
58800 case 'const':
58801 return parseLexicalDeclaration({inFor: false});
58802 case 'function':
58803 return parseFunctionDeclaration(new Node());
58804 case 'class':
58805 return parseClassDeclaration();
58806 }
58807 }
58808
58809 if (matchKeyword('let') && isLexicalDeclaration()) {
58810 return parseLexicalDeclaration({inFor: false});
58811 }
58812
58813 return parseStatement();
58814 }
58815
58816 function parseStatementList() {
58817 var list = [];
58818 while (startIndex < length) {
58819 if (match('}')) {
58820 break;
58821 }
58822 list.push(parseStatementListItem());
58823 }
58824
58825 return list;
58826 }
58827
58828 function parseBlock() {
58829 var block, node = new Node();
58830
58831 expect('{');
58832
58833 block = parseStatementList();
58834
58835 expect('}');
58836
58837 return node.finishBlockStatement(block);
58838 }
58839
58840 // ECMA-262 13.3.2 Variable Statement
58841
58842 function parseVariableIdentifier(kind) {
58843 var token, node = new Node();
58844
58845 token = lex();
58846
58847 if (token.type === Token.Keyword && token.value === 'yield') {
58848 if (strict) {
58849 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
58850 } if (!state.allowYield) {
58851 throwUnexpectedToken(token);
58852 }
58853 } else if (token.type !== Token.Identifier) {
58854 if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
58855 tolerateUnexpectedToken(token, Messages.StrictReservedWord);
58856 } else {
58857 if (strict || token.value !== 'let' || kind !== 'var') {
58858 throwUnexpectedToken(token);
58859 }
58860 }
58861 } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
58862 tolerateUnexpectedToken(token);
58863 }
58864
58865 return node.finishIdentifier(token.value);
58866 }
58867
58868 function parseVariableDeclaration(options) {
58869 var init = null, id, node = new Node(), params = [];
58870
58871 id = parsePattern(params, 'var');
58872
58873 // ECMA-262 12.2.1
58874 if (strict && isRestrictedWord(id.name)) {
58875 tolerateError(Messages.StrictVarName);
58876 }
58877
58878 if (match('=')) {
58879 lex();
58880 init = isolateCoverGrammar(parseAssignmentExpression);
58881 } else if (id.type !== Syntax.Identifier && !options.inFor) {
58882 expect('=');
58883 }
58884
58885 return node.finishVariableDeclarator(id, init);
58886 }
58887
58888 function parseVariableDeclarationList(options) {
58889 var list = [];
58890
58891 do {
58892 list.push(parseVariableDeclaration({ inFor: options.inFor }));
58893 if (!match(',')) {
58894 break;
58895 }
58896 lex();
58897 } while (startIndex < length);
58898
58899 return list;
58900 }
58901
58902 function parseVariableStatement(node) {
58903 var declarations;
58904
58905 expectKeyword('var');
58906
58907 declarations = parseVariableDeclarationList({ inFor: false });
58908
58909 consumeSemicolon();
58910
58911 return node.finishVariableDeclaration(declarations);
58912 }
58913
58914 // ECMA-262 13.3.1 Let and Const Declarations
58915
58916 function parseLexicalBinding(kind, options) {
58917 var init = null, id, node = new Node(), params = [];
58918
58919 id = parsePattern(params, kind);
58920
58921 // ECMA-262 12.2.1
58922 if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
58923 tolerateError(Messages.StrictVarName);
58924 }
58925
58926 if (kind === 'const') {
58927 if (!matchKeyword('in') && !matchContextualKeyword('of')) {
58928 expect('=');
58929 init = isolateCoverGrammar(parseAssignmentExpression);
58930 }
58931 } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
58932 expect('=');
58933 init = isolateCoverGrammar(parseAssignmentExpression);
58934 }
58935
58936 return node.finishVariableDeclarator(id, init);
58937 }
58938
58939 function parseBindingList(kind, options) {
58940 var list = [];
58941
58942 do {
58943 list.push(parseLexicalBinding(kind, options));
58944 if (!match(',')) {
58945 break;
58946 }
58947 lex();
58948 } while (startIndex < length);
58949
58950 return list;
58951 }
58952
58953
58954 function tokenizerState() {
58955 return {
58956 index: index,
58957 lineNumber: lineNumber,
58958 lineStart: lineStart,
58959 hasLineTerminator: hasLineTerminator,
58960 lastIndex: lastIndex,
58961 lastLineNumber: lastLineNumber,
58962 lastLineStart: lastLineStart,
58963 startIndex: startIndex,
58964 startLineNumber: startLineNumber,
58965 startLineStart: startLineStart,
58966 lookahead: lookahead,
58967 tokenCount: extra.tokens ? extra.tokens.length : 0
58968 };
58969 }
58970
58971 function resetTokenizerState(ts) {
58972 index = ts.index;
58973 lineNumber = ts.lineNumber;
58974 lineStart = ts.lineStart;
58975 hasLineTerminator = ts.hasLineTerminator;
58976 lastIndex = ts.lastIndex;
58977 lastLineNumber = ts.lastLineNumber;
58978 lastLineStart = ts.lastLineStart;
58979 startIndex = ts.startIndex;
58980 startLineNumber = ts.startLineNumber;
58981 startLineStart = ts.startLineStart;
58982 lookahead = ts.lookahead;
58983 if (extra.tokens) {
58984 extra.tokens.splice(ts.tokenCount, extra.tokens.length);
58985 }
58986 }
58987
58988 function isLexicalDeclaration() {
58989 var lexical, ts;
58990
58991 ts = tokenizerState();
58992
58993 lex();
58994 lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
58995 matchKeyword('let') || matchKeyword('yield');
58996
58997 resetTokenizerState(ts);
58998
58999 return lexical;
59000 }
59001
59002 function parseLexicalDeclaration(options) {
59003 var kind, declarations, node = new Node();
59004
59005 kind = lex().value;
59006 assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
59007
59008 declarations = parseBindingList(kind, options);
59009
59010 consumeSemicolon();
59011
59012 return node.finishLexicalDeclaration(declarations, kind);
59013 }
59014
59015 function parseRestElement(params) {
59016 var param, node = new Node();
59017
59018 lex();
59019
59020 if (match('{')) {
59021 throwError(Messages.ObjectPatternAsRestParameter);
59022 }
59023
59024 params.push(lookahead);
59025
59026 param = parseVariableIdentifier();
59027
59028 if (match('=')) {
59029 throwError(Messages.DefaultRestParameter);
59030 }
59031
59032 if (!match(')')) {
59033 throwError(Messages.ParameterAfterRestParameter);
59034 }
59035
59036 return node.finishRestElement(param);
59037 }
59038
59039 // ECMA-262 13.4 Empty Statement
59040
59041 function parseEmptyStatement(node) {
59042 expect(';');
59043 return node.finishEmptyStatement();
59044 }
59045
59046 // ECMA-262 12.4 Expression Statement
59047
59048 function parseExpressionStatement(node) {
59049 var expr = parseExpression();
59050 consumeSemicolon();
59051 return node.finishExpressionStatement(expr);
59052 }
59053
59054 // ECMA-262 13.6 If statement
59055
59056 function parseIfStatement(node) {
59057 var test, consequent, alternate;
59058
59059 expectKeyword('if');
59060
59061 expect('(');
59062
59063 test = parseExpression();
59064
59065 expect(')');
59066
59067 consequent = parseStatement();
59068
59069 if (matchKeyword('else')) {
59070 lex();
59071 alternate = parseStatement();
59072 } else {
59073 alternate = null;
59074 }
59075
59076 return node.finishIfStatement(test, consequent, alternate);
59077 }
59078
59079 // ECMA-262 13.7 Iteration Statements
59080
59081 function parseDoWhileStatement(node) {
59082 var body, test, oldInIteration;
59083
59084 expectKeyword('do');
59085
59086 oldInIteration = state.inIteration;
59087 state.inIteration = true;
59088
59089 body = parseStatement();
59090
59091 state.inIteration = oldInIteration;
59092
59093 expectKeyword('while');
59094
59095 expect('(');
59096
59097 test = parseExpression();
59098
59099 expect(')');
59100
59101 if (match(';')) {
59102 lex();
59103 }
59104
59105 return node.finishDoWhileStatement(body, test);
59106 }
59107
59108 function parseWhileStatement(node) {
59109 var test, body, oldInIteration;
59110
59111 expectKeyword('while');
59112
59113 expect('(');
59114
59115 test = parseExpression();
59116
59117 expect(')');
59118
59119 oldInIteration = state.inIteration;
59120 state.inIteration = true;
59121
59122 body = parseStatement();
59123
59124 state.inIteration = oldInIteration;
59125
59126 return node.finishWhileStatement(test, body);
59127 }
59128
59129 function parseForStatement(node) {
59130 var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
59131 body, oldInIteration, previousAllowIn = state.allowIn;
59132
59133 init = test = update = null;
59134 forIn = true;
59135
59136 expectKeyword('for');
59137
59138 expect('(');
59139
59140 if (match(';')) {
59141 lex();
59142 } else {
59143 if (matchKeyword('var')) {
59144 init = new Node();
59145 lex();
59146
59147 state.allowIn = false;
59148 declarations = parseVariableDeclarationList({ inFor: true });
59149 state.allowIn = previousAllowIn;
59150
59151 if (declarations.length === 1 && matchKeyword('in')) {
59152 init = init.finishVariableDeclaration(declarations);
59153 lex();
59154 left = init;
59155 right = parseExpression();
59156 init = null;
59157 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
59158 init = init.finishVariableDeclaration(declarations);
59159 lex();
59160 left = init;
59161 right = parseAssignmentExpression();
59162 init = null;
59163 forIn = false;
59164 } else {
59165 init = init.finishVariableDeclaration(declarations);
59166 expect(';');
59167 }
59168 } else if (matchKeyword('const') || matchKeyword('let')) {
59169 init = new Node();
59170 kind = lex().value;
59171
59172 if (!strict && lookahead.value === 'in') {
59173 init = init.finishIdentifier(kind);
59174 lex();
59175 left = init;
59176 right = parseExpression();
59177 init = null;
59178 } else {
59179 state.allowIn = false;
59180 declarations = parseBindingList(kind, {inFor: true});
59181 state.allowIn = previousAllowIn;
59182
59183 if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
59184 init = init.finishLexicalDeclaration(declarations, kind);
59185 lex();
59186 left = init;
59187 right = parseExpression();
59188 init = null;
59189 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
59190 init = init.finishLexicalDeclaration(declarations, kind);
59191 lex();
59192 left = init;
59193 right = parseAssignmentExpression();
59194 init = null;
59195 forIn = false;
59196 } else {
59197 consumeSemicolon();
59198 init = init.finishLexicalDeclaration(declarations, kind);
59199 }
59200 }
59201 } else {
59202 initStartToken = lookahead;
59203 state.allowIn = false;
59204 init = inheritCoverGrammar(parseAssignmentExpression);
59205 state.allowIn = previousAllowIn;
59206
59207 if (matchKeyword('in')) {
59208 if (!isAssignmentTarget) {
59209 tolerateError(Messages.InvalidLHSInForIn);
59210 }
59211
59212 lex();
59213 reinterpretExpressionAsPattern(init);
59214 left = init;
59215 right = parseExpression();
59216 init = null;
59217 } else if (matchContextualKeyword('of')) {
59218 if (!isAssignmentTarget) {
59219 tolerateError(Messages.InvalidLHSInForLoop);
59220 }
59221
59222 lex();
59223 reinterpretExpressionAsPattern(init);
59224 left = init;
59225 right = parseAssignmentExpression();
59226 init = null;
59227 forIn = false;
59228 } else {
59229 if (match(',')) {
59230 initSeq = [init];
59231 while (match(',')) {
59232 lex();
59233 initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
59234 }
59235 init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
59236 }
59237 expect(';');
59238 }
59239 }
59240 }
59241
59242 if (typeof left === 'undefined') {
59243
59244 if (!match(';')) {
59245 test = parseExpression();
59246 }
59247 expect(';');
59248
59249 if (!match(')')) {
59250 update = parseExpression();
59251 }
59252 }
59253
59254 expect(')');
59255
59256 oldInIteration = state.inIteration;
59257 state.inIteration = true;
59258
59259 body = isolateCoverGrammar(parseStatement);
59260
59261 state.inIteration = oldInIteration;
59262
59263 return (typeof left === 'undefined') ?
59264 node.finishForStatement(init, test, update, body) :
59265 forIn ? node.finishForInStatement(left, right, body) :
59266 node.finishForOfStatement(left, right, body);
59267 }
59268
59269 // ECMA-262 13.8 The continue statement
59270
59271 function parseContinueStatement(node) {
59272 var label = null, key;
59273
59274 expectKeyword('continue');
59275
59276 // Optimize the most common form: 'continue;'.
59277 if (source.charCodeAt(startIndex) === 0x3B) {
59278 lex();
59279
59280 if (!state.inIteration) {
59281 throwError(Messages.IllegalContinue);
59282 }
59283
59284 return node.finishContinueStatement(null);
59285 }
59286
59287 if (hasLineTerminator) {
59288 if (!state.inIteration) {
59289 throwError(Messages.IllegalContinue);
59290 }
59291
59292 return node.finishContinueStatement(null);
59293 }
59294
59295 if (lookahead.type === Token.Identifier) {
59296 label = parseVariableIdentifier();
59297
59298 key = '$' + label.name;
59299 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
59300 throwError(Messages.UnknownLabel, label.name);
59301 }
59302 }
59303
59304 consumeSemicolon();
59305
59306 if (label === null && !state.inIteration) {
59307 throwError(Messages.IllegalContinue);
59308 }
59309
59310 return node.finishContinueStatement(label);
59311 }
59312
59313 // ECMA-262 13.9 The break statement
59314
59315 function parseBreakStatement(node) {
59316 var label = null, key;
59317
59318 expectKeyword('break');
59319
59320 // Catch the very common case first: immediately a semicolon (U+003B).
59321 if (source.charCodeAt(lastIndex) === 0x3B) {
59322 lex();
59323
59324 if (!(state.inIteration || state.inSwitch)) {
59325 throwError(Messages.IllegalBreak);
59326 }
59327
59328 return node.finishBreakStatement(null);
59329 }
59330
59331 if (hasLineTerminator) {
59332 if (!(state.inIteration || state.inSwitch)) {
59333 throwError(Messages.IllegalBreak);
59334 }
59335 } else if (lookahead.type === Token.Identifier) {
59336 label = parseVariableIdentifier();
59337
59338 key = '$' + label.name;
59339 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
59340 throwError(Messages.UnknownLabel, label.name);
59341 }
59342 }
59343
59344 consumeSemicolon();
59345
59346 if (label === null && !(state.inIteration || state.inSwitch)) {
59347 throwError(Messages.IllegalBreak);
59348 }
59349
59350 return node.finishBreakStatement(label);
59351 }
59352
59353 // ECMA-262 13.10 The return statement
59354
59355 function parseReturnStatement(node) {
59356 var argument = null;
59357
59358 expectKeyword('return');
59359
59360 if (!state.inFunctionBody) {
59361 tolerateError(Messages.IllegalReturn);
59362 }
59363
59364 // 'return' followed by a space and an identifier is very common.
59365 if (source.charCodeAt(lastIndex) === 0x20) {
59366 if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
59367 argument = parseExpression();
59368 consumeSemicolon();
59369 return node.finishReturnStatement(argument);
59370 }
59371 }
59372
59373 if (hasLineTerminator) {
59374 // HACK
59375 return node.finishReturnStatement(null);
59376 }
59377
59378 if (!match(';')) {
59379 if (!match('}') && lookahead.type !== Token.EOF) {
59380 argument = parseExpression();
59381 }
59382 }
59383
59384 consumeSemicolon();
59385
59386 return node.finishReturnStatement(argument);
59387 }
59388
59389 // ECMA-262 13.11 The with statement
59390
59391 function parseWithStatement(node) {
59392 var object, body;
59393
59394 if (strict) {
59395 tolerateError(Messages.StrictModeWith);
59396 }
59397
59398 expectKeyword('with');
59399
59400 expect('(');
59401
59402 object = parseExpression();
59403
59404 expect(')');
59405
59406 body = parseStatement();
59407
59408 return node.finishWithStatement(object, body);
59409 }
59410
59411 // ECMA-262 13.12 The switch statement
59412
59413 function parseSwitchCase() {
59414 var test, consequent = [], statement, node = new Node();
59415
59416 if (matchKeyword('default')) {
59417 lex();
59418 test = null;
59419 } else {
59420 expectKeyword('case');
59421 test = parseExpression();
59422 }
59423 expect(':');
59424
59425 while (startIndex < length) {
59426 if (match('}') || matchKeyword('default') || matchKeyword('case')) {
59427 break;
59428 }
59429 statement = parseStatementListItem();
59430 consequent.push(statement);
59431 }
59432
59433 return node.finishSwitchCase(test, consequent);
59434 }
59435
59436 function parseSwitchStatement(node) {
59437 var discriminant, cases, clause, oldInSwitch, defaultFound;
59438
59439 expectKeyword('switch');
59440
59441 expect('(');
59442
59443 discriminant = parseExpression();
59444
59445 expect(')');
59446
59447 expect('{');
59448
59449 cases = [];
59450
59451 if (match('}')) {
59452 lex();
59453 return node.finishSwitchStatement(discriminant, cases);
59454 }
59455
59456 oldInSwitch = state.inSwitch;
59457 state.inSwitch = true;
59458 defaultFound = false;
59459
59460 while (startIndex < length) {
59461 if (match('}')) {
59462 break;
59463 }
59464 clause = parseSwitchCase();
59465 if (clause.test === null) {
59466 if (defaultFound) {
59467 throwError(Messages.MultipleDefaultsInSwitch);
59468 }
59469 defaultFound = true;
59470 }
59471 cases.push(clause);
59472 }
59473
59474 state.inSwitch = oldInSwitch;
59475
59476 expect('}');
59477
59478 return node.finishSwitchStatement(discriminant, cases);
59479 }
59480
59481 // ECMA-262 13.14 The throw statement
59482
59483 function parseThrowStatement(node) {
59484 var argument;
59485
59486 expectKeyword('throw');
59487
59488 if (hasLineTerminator) {
59489 throwError(Messages.NewlineAfterThrow);
59490 }
59491
59492 argument = parseExpression();
59493
59494 consumeSemicolon();
59495
59496 return node.finishThrowStatement(argument);
59497 }
59498
59499 // ECMA-262 13.15 The try statement
59500
59501 function parseCatchClause() {
59502 var param, params = [], paramMap = {}, key, i, body, node = new Node();
59503
59504 expectKeyword('catch');
59505
59506 expect('(');
59507 if (match(')')) {
59508 throwUnexpectedToken(lookahead);
59509 }
59510
59511 param = parsePattern(params);
59512 for (i = 0; i < params.length; i++) {
59513 key = '$' + params[i].value;
59514 if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
59515 tolerateError(Messages.DuplicateBinding, params[i].value);
59516 }
59517 paramMap[key] = true;
59518 }
59519
59520 // ECMA-262 12.14.1
59521 if (strict && isRestrictedWord(param.name)) {
59522 tolerateError(Messages.StrictCatchVariable);
59523 }
59524
59525 expect(')');
59526 body = parseBlock();
59527 return node.finishCatchClause(param, body);
59528 }
59529
59530 function parseTryStatement(node) {
59531 var block, handler = null, finalizer = null;
59532
59533 expectKeyword('try');
59534
59535 block = parseBlock();
59536
59537 if (matchKeyword('catch')) {
59538 handler = parseCatchClause();
59539 }
59540
59541 if (matchKeyword('finally')) {
59542 lex();
59543 finalizer = parseBlock();
59544 }
59545
59546 if (!handler && !finalizer) {
59547 throwError(Messages.NoCatchOrFinally);
59548 }
59549
59550 return node.finishTryStatement(block, handler, finalizer);
59551 }
59552
59553 // ECMA-262 13.16 The debugger statement
59554
59555 function parseDebuggerStatement(node) {
59556 expectKeyword('debugger');
59557
59558 consumeSemicolon();
59559
59560 return node.finishDebuggerStatement();
59561 }
59562
59563 // 13 Statements
59564
59565 function parseStatement() {
59566 var type = lookahead.type,
59567 expr,
59568 labeledBody,
59569 key,
59570 node;
59571
59572 if (type === Token.EOF) {
59573 throwUnexpectedToken(lookahead);
59574 }
59575
59576 if (type === Token.Punctuator && lookahead.value === '{') {
59577 return parseBlock();
59578 }
59579 isAssignmentTarget = isBindingElement = true;
59580 node = new Node();
59581
59582 if (type === Token.Punctuator) {
59583 switch (lookahead.value) {
59584 case ';':
59585 return parseEmptyStatement(node);
59586 case '(':
59587 return parseExpressionStatement(node);
59588 default:
59589 break;
59590 }
59591 } else if (type === Token.Keyword) {
59592 switch (lookahead.value) {
59593 case 'break':
59594 return parseBreakStatement(node);
59595 case 'continue':
59596 return parseContinueStatement(node);
59597 case 'debugger':
59598 return parseDebuggerStatement(node);
59599 case 'do':
59600 return parseDoWhileStatement(node);
59601 case 'for':
59602 return parseForStatement(node);
59603 case 'function':
59604 return parseFunctionDeclaration(node);
59605 case 'if':
59606 return parseIfStatement(node);
59607 case 'return':
59608 return parseReturnStatement(node);
59609 case 'switch':
59610 return parseSwitchStatement(node);
59611 case 'throw':
59612 return parseThrowStatement(node);
59613 case 'try':
59614 return parseTryStatement(node);
59615 case 'var':
59616 return parseVariableStatement(node);
59617 case 'while':
59618 return parseWhileStatement(node);
59619 case 'with':
59620 return parseWithStatement(node);
59621 default:
59622 break;
59623 }
59624 }
59625
59626 expr = parseExpression();
59627
59628 // ECMA-262 12.12 Labelled Statements
59629 if ((expr.type === Syntax.Identifier) && match(':')) {
59630 lex();
59631
59632 key = '$' + expr.name;
59633 if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
59634 throwError(Messages.Redeclaration, 'Label', expr.name);
59635 }
59636
59637 state.labelSet[key] = true;
59638 labeledBody = parseStatement();
59639 delete state.labelSet[key];
59640 return node.finishLabeledStatement(expr, labeledBody);
59641 }
59642
59643 consumeSemicolon();
59644
59645 return node.finishExpressionStatement(expr);
59646 }
59647
59648 // ECMA-262 14.1 Function Definition
59649
59650 function parseFunctionSourceElements() {
59651 var statement, body = [], token, directive, firstRestricted,
59652 oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
59653 node = new Node();
59654
59655 expect('{');
59656
59657 while (startIndex < length) {
59658 if (lookahead.type !== Token.StringLiteral) {
59659 break;
59660 }
59661 token = lookahead;
59662
59663 statement = parseStatementListItem();
59664 body.push(statement);
59665 if (statement.expression.type !== Syntax.Literal) {
59666 // this is not directive
59667 break;
59668 }
59669 directive = source.slice(token.start + 1, token.end - 1);
59670 if (directive === 'use strict') {
59671 strict = true;
59672 if (firstRestricted) {
59673 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
59674 }
59675 } else {
59676 if (!firstRestricted && token.octal) {
59677 firstRestricted = token;
59678 }
59679 }
59680 }
59681
59682 oldLabelSet = state.labelSet;
59683 oldInIteration = state.inIteration;
59684 oldInSwitch = state.inSwitch;
59685 oldInFunctionBody = state.inFunctionBody;
59686 oldParenthesisCount = state.parenthesizedCount;
59687
59688 state.labelSet = {};
59689 state.inIteration = false;
59690 state.inSwitch = false;
59691 state.inFunctionBody = true;
59692 state.parenthesizedCount = 0;
59693
59694 while (startIndex < length) {
59695 if (match('}')) {
59696 break;
59697 }
59698 body.push(parseStatementListItem());
59699 }
59700
59701 expect('}');
59702
59703 state.labelSet = oldLabelSet;
59704 state.inIteration = oldInIteration;
59705 state.inSwitch = oldInSwitch;
59706 state.inFunctionBody = oldInFunctionBody;
59707 state.parenthesizedCount = oldParenthesisCount;
59708
59709 return node.finishBlockStatement(body);
59710 }
59711
59712 function validateParam(options, param, name) {
59713 var key = '$' + name;
59714 if (strict) {
59715 if (isRestrictedWord(name)) {
59716 options.stricted = param;
59717 options.message = Messages.StrictParamName;
59718 }
59719 if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
59720 options.stricted = param;
59721 options.message = Messages.StrictParamDupe;
59722 }
59723 } else if (!options.firstRestricted) {
59724 if (isRestrictedWord(name)) {
59725 options.firstRestricted = param;
59726 options.message = Messages.StrictParamName;
59727 } else if (isStrictModeReservedWord(name)) {
59728 options.firstRestricted = param;
59729 options.message = Messages.StrictReservedWord;
59730 } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
59731 options.stricted = param;
59732 options.message = Messages.StrictParamDupe;
59733 }
59734 }
59735 options.paramSet[key] = true;
59736 }
59737
59738 function parseParam(options) {
59739 var token, param, params = [], i, def;
59740
59741 token = lookahead;
59742 if (token.value === '...') {
59743 param = parseRestElement(params);
59744 validateParam(options, param.argument, param.argument.name);
59745 options.params.push(param);
59746 options.defaults.push(null);
59747 return false;
59748 }
59749
59750 param = parsePatternWithDefault(params);
59751 for (i = 0; i < params.length; i++) {
59752 validateParam(options, params[i], params[i].value);
59753 }
59754
59755 if (param.type === Syntax.AssignmentPattern) {
59756 def = param.right;
59757 param = param.left;
59758 ++options.defaultCount;
59759 }
59760
59761 options.params.push(param);
59762 options.defaults.push(def);
59763
59764 return !match(')');
59765 }
59766
59767 function parseParams(firstRestricted) {
59768 var options;
59769
59770 options = {
59771 params: [],
59772 defaultCount: 0,
59773 defaults: [],
59774 firstRestricted: firstRestricted
59775 };
59776
59777 expect('(');
59778
59779 if (!match(')')) {
59780 options.paramSet = {};
59781 while (startIndex < length) {
59782 if (!parseParam(options)) {
59783 break;
59784 }
59785 expect(',');
59786 }
59787 }
59788
59789 expect(')');
59790
59791 if (options.defaultCount === 0) {
59792 options.defaults = [];
59793 }
59794
59795 return {
59796 params: options.params,
59797 defaults: options.defaults,
59798 stricted: options.stricted,
59799 firstRestricted: options.firstRestricted,
59800 message: options.message
59801 };
59802 }
59803
59804 function parseFunctionDeclaration(node, identifierIsOptional) {
59805 var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
59806 isGenerator, previousAllowYield;
59807
59808 previousAllowYield = state.allowYield;
59809
59810 expectKeyword('function');
59811
59812 isGenerator = match('*');
59813 if (isGenerator) {
59814 lex();
59815 }
59816
59817 if (!identifierIsOptional || !match('(')) {
59818 token = lookahead;
59819 id = parseVariableIdentifier();
59820 if (strict) {
59821 if (isRestrictedWord(token.value)) {
59822 tolerateUnexpectedToken(token, Messages.StrictFunctionName);
59823 }
59824 } else {
59825 if (isRestrictedWord(token.value)) {
59826 firstRestricted = token;
59827 message = Messages.StrictFunctionName;
59828 } else if (isStrictModeReservedWord(token.value)) {
59829 firstRestricted = token;
59830 message = Messages.StrictReservedWord;
59831 }
59832 }
59833 }
59834
59835 state.allowYield = !isGenerator;
59836 tmp = parseParams(firstRestricted);
59837 params = tmp.params;
59838 defaults = tmp.defaults;
59839 stricted = tmp.stricted;
59840 firstRestricted = tmp.firstRestricted;
59841 if (tmp.message) {
59842 message = tmp.message;
59843 }
59844
59845
59846 previousStrict = strict;
59847 body = parseFunctionSourceElements();
59848 if (strict && firstRestricted) {
59849 throwUnexpectedToken(firstRestricted, message);
59850 }
59851 if (strict && stricted) {
59852 tolerateUnexpectedToken(stricted, message);
59853 }
59854
59855 strict = previousStrict;
59856 state.allowYield = previousAllowYield;
59857
59858 return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
59859 }
59860
59861 function parseFunctionExpression() {
59862 var token, id = null, stricted, firstRestricted, message, tmp,
59863 params = [], defaults = [], body, previousStrict, node = new Node(),
59864 isGenerator, previousAllowYield;
59865
59866 previousAllowYield = state.allowYield;
59867
59868 expectKeyword('function');
59869
59870 isGenerator = match('*');
59871 if (isGenerator) {
59872 lex();
59873 }
59874
59875 state.allowYield = !isGenerator;
59876 if (!match('(')) {
59877 token = lookahead;
59878 id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
59879 if (strict) {
59880 if (isRestrictedWord(token.value)) {
59881 tolerateUnexpectedToken(token, Messages.StrictFunctionName);
59882 }
59883 } else {
59884 if (isRestrictedWord(token.value)) {
59885 firstRestricted = token;
59886 message = Messages.StrictFunctionName;
59887 } else if (isStrictModeReservedWord(token.value)) {
59888 firstRestricted = token;
59889 message = Messages.StrictReservedWord;
59890 }
59891 }
59892 }
59893
59894 tmp = parseParams(firstRestricted);
59895 params = tmp.params;
59896 defaults = tmp.defaults;
59897 stricted = tmp.stricted;
59898 firstRestricted = tmp.firstRestricted;
59899 if (tmp.message) {
59900 message = tmp.message;
59901 }
59902
59903 previousStrict = strict;
59904 body = parseFunctionSourceElements();
59905 if (strict && firstRestricted) {
59906 throwUnexpectedToken(firstRestricted, message);
59907 }
59908 if (strict && stricted) {
59909 tolerateUnexpectedToken(stricted, message);
59910 }
59911 strict = previousStrict;
59912 state.allowYield = previousAllowYield;
59913
59914 return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
59915 }
59916
59917 // ECMA-262 14.5 Class Definitions
59918
59919 function parseClassBody() {
59920 var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
59921
59922 classBody = new Node();
59923
59924 expect('{');
59925 body = [];
59926 while (!match('}')) {
59927 if (match(';')) {
59928 lex();
59929 } else {
59930 method = new Node();
59931 token = lookahead;
59932 isStatic = false;
59933 computed = match('[');
59934 if (match('*')) {
59935 lex();
59936 } else {
59937 key = parseObjectPropertyKey();
59938 if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
59939 token = lookahead;
59940 isStatic = true;
59941 computed = match('[');
59942 if (match('*')) {
59943 lex();
59944 } else {
59945 key = parseObjectPropertyKey();
59946 }
59947 }
59948 }
59949 method = tryParseMethodDefinition(token, key, computed, method);
59950 if (method) {
59951 method['static'] = isStatic; // jscs:ignore requireDotNotation
59952 if (method.kind === 'init') {
59953 method.kind = 'method';
59954 }
59955 if (!isStatic) {
59956 if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
59957 if (method.kind !== 'method' || !method.method || method.value.generator) {
59958 throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
59959 }
59960 if (hasConstructor) {
59961 throwUnexpectedToken(token, Messages.DuplicateConstructor);
59962 } else {
59963 hasConstructor = true;
59964 }
59965 method.kind = 'constructor';
59966 }
59967 } else {
59968 if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
59969 throwUnexpectedToken(token, Messages.StaticPrototype);
59970 }
59971 }
59972 method.type = Syntax.MethodDefinition;
59973 delete method.method;
59974 delete method.shorthand;
59975 body.push(method);
59976 } else {
59977 throwUnexpectedToken(lookahead);
59978 }
59979 }
59980 }
59981 lex();
59982 return classBody.finishClassBody(body);
59983 }
59984
59985 function parseClassDeclaration(identifierIsOptional) {
59986 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
59987 strict = true;
59988
59989 expectKeyword('class');
59990
59991 if (!identifierIsOptional || lookahead.type === Token.Identifier) {
59992 id = parseVariableIdentifier();
59993 }
59994
59995 if (matchKeyword('extends')) {
59996 lex();
59997 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
59998 }
59999 classBody = parseClassBody();
60000 strict = previousStrict;
60001
60002 return classNode.finishClassDeclaration(id, superClass, classBody);
60003 }
60004
60005 function parseClassExpression() {
60006 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
60007 strict = true;
60008
60009 expectKeyword('class');
60010
60011 if (lookahead.type === Token.Identifier) {
60012 id = parseVariableIdentifier();
60013 }
60014
60015 if (matchKeyword('extends')) {
60016 lex();
60017 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
60018 }
60019 classBody = parseClassBody();
60020 strict = previousStrict;
60021
60022 return classNode.finishClassExpression(id, superClass, classBody);
60023 }
60024
60025 // ECMA-262 15.2 Modules
60026
60027 function parseModuleSpecifier() {
60028 var node = new Node();
60029
60030 if (lookahead.type !== Token.StringLiteral) {
60031 throwError(Messages.InvalidModuleSpecifier);
60032 }
60033 return node.finishLiteral(lex());
60034 }
60035
60036 // ECMA-262 15.2.3 Exports
60037
60038 function parseExportSpecifier() {
60039 var exported, local, node = new Node(), def;
60040 if (matchKeyword('default')) {
60041 // export {default} from 'something';
60042 def = new Node();
60043 lex();
60044 local = def.finishIdentifier('default');
60045 } else {
60046 local = parseVariableIdentifier();
60047 }
60048 if (matchContextualKeyword('as')) {
60049 lex();
60050 exported = parseNonComputedProperty();
60051 }
60052 return node.finishExportSpecifier(local, exported);
60053 }
60054
60055 function parseExportNamedDeclaration(node) {
60056 var declaration = null,
60057 isExportFromIdentifier,
60058 src = null, specifiers = [];
60059
60060 // non-default export
60061 if (lookahead.type === Token.Keyword) {
60062 // covers:
60063 // export var f = 1;
60064 switch (lookahead.value) {
60065 case 'let':
60066 case 'const':
60067 declaration = parseLexicalDeclaration({inFor: false});
60068 return node.finishExportNamedDeclaration(declaration, specifiers, null);
60069 case 'var':
60070 case 'class':
60071 case 'function':
60072 declaration = parseStatementListItem();
60073 return node.finishExportNamedDeclaration(declaration, specifiers, null);
60074 }
60075 }
60076
60077 expect('{');
60078 while (!match('}')) {
60079 isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
60080 specifiers.push(parseExportSpecifier());
60081 if (!match('}')) {
60082 expect(',');
60083 if (match('}')) {
60084 break;
60085 }
60086 }
60087 }
60088 expect('}');
60089
60090 if (matchContextualKeyword('from')) {
60091 // covering:
60092 // export {default} from 'foo';
60093 // export {foo} from 'foo';
60094 lex();
60095 src = parseModuleSpecifier();
60096 consumeSemicolon();
60097 } else if (isExportFromIdentifier) {
60098 // covering:
60099 // export {default}; // missing fromClause
60100 throwError(lookahead.value ?
60101 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
60102 } else {
60103 // cover
60104 // export {foo};
60105 consumeSemicolon();
60106 }
60107 return node.finishExportNamedDeclaration(declaration, specifiers, src);
60108 }
60109
60110 function parseExportDefaultDeclaration(node) {
60111 var declaration = null,
60112 expression = null;
60113
60114 // covers:
60115 // export default ...
60116 expectKeyword('default');
60117
60118 if (matchKeyword('function')) {
60119 // covers:
60120 // export default function foo () {}
60121 // export default function () {}
60122 declaration = parseFunctionDeclaration(new Node(), true);
60123 return node.finishExportDefaultDeclaration(declaration);
60124 }
60125 if (matchKeyword('class')) {
60126 declaration = parseClassDeclaration(true);
60127 return node.finishExportDefaultDeclaration(declaration);
60128 }
60129
60130 if (matchContextualKeyword('from')) {
60131 throwError(Messages.UnexpectedToken, lookahead.value);
60132 }
60133
60134 // covers:
60135 // export default {};
60136 // export default [];
60137 // export default (1 + 2);
60138 if (match('{')) {
60139 expression = parseObjectInitializer();
60140 } else if (match('[')) {
60141 expression = parseArrayInitializer();
60142 } else {
60143 expression = parseAssignmentExpression();
60144 }
60145 consumeSemicolon();
60146 return node.finishExportDefaultDeclaration(expression);
60147 }
60148
60149 function parseExportAllDeclaration(node) {
60150 var src;
60151
60152 // covers:
60153 // export * from 'foo';
60154 expect('*');
60155 if (!matchContextualKeyword('from')) {
60156 throwError(lookahead.value ?
60157 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
60158 }
60159 lex();
60160 src = parseModuleSpecifier();
60161 consumeSemicolon();
60162
60163 return node.finishExportAllDeclaration(src);
60164 }
60165
60166 function parseExportDeclaration() {
60167 var node = new Node();
60168 if (state.inFunctionBody) {
60169 throwError(Messages.IllegalExportDeclaration);
60170 }
60171
60172 expectKeyword('export');
60173
60174 if (matchKeyword('default')) {
60175 return parseExportDefaultDeclaration(node);
60176 }
60177 if (match('*')) {
60178 return parseExportAllDeclaration(node);
60179 }
60180 return parseExportNamedDeclaration(node);
60181 }
60182
60183 // ECMA-262 15.2.2 Imports
60184
60185 function parseImportSpecifier() {
60186 // import {<foo as bar>} ...;
60187 var local, imported, node = new Node();
60188
60189 imported = parseNonComputedProperty();
60190 if (matchContextualKeyword('as')) {
60191 lex();
60192 local = parseVariableIdentifier();
60193 }
60194
60195 return node.finishImportSpecifier(local, imported);
60196 }
60197
60198 function parseNamedImports() {
60199 var specifiers = [];
60200 // {foo, bar as bas}
60201 expect('{');
60202 while (!match('}')) {
60203 specifiers.push(parseImportSpecifier());
60204 if (!match('}')) {
60205 expect(',');
60206 if (match('}')) {
60207 break;
60208 }
60209 }
60210 }
60211 expect('}');
60212 return specifiers;
60213 }
60214
60215 function parseImportDefaultSpecifier() {
60216 // import <foo> ...;
60217 var local, node = new Node();
60218
60219 local = parseNonComputedProperty();
60220
60221 return node.finishImportDefaultSpecifier(local);
60222 }
60223
60224 function parseImportNamespaceSpecifier() {
60225 // import <* as foo> ...;
60226 var local, node = new Node();
60227
60228 expect('*');
60229 if (!matchContextualKeyword('as')) {
60230 throwError(Messages.NoAsAfterImportNamespace);
60231 }
60232 lex();
60233 local = parseNonComputedProperty();
60234
60235 return node.finishImportNamespaceSpecifier(local);
60236 }
60237
60238 function parseImportDeclaration() {
60239 var specifiers = [], src, node = new Node();
60240
60241 if (state.inFunctionBody) {
60242 throwError(Messages.IllegalImportDeclaration);
60243 }
60244
60245 expectKeyword('import');
60246
60247 if (lookahead.type === Token.StringLiteral) {
60248 // import 'foo';
60249 src = parseModuleSpecifier();
60250 } else {
60251
60252 if (match('{')) {
60253 // import {bar}
60254 specifiers = specifiers.concat(parseNamedImports());
60255 } else if (match('*')) {
60256 // import * as foo
60257 specifiers.push(parseImportNamespaceSpecifier());
60258 } else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
60259 // import foo
60260 specifiers.push(parseImportDefaultSpecifier());
60261 if (match(',')) {
60262 lex();
60263 if (match('*')) {
60264 // import foo, * as foo
60265 specifiers.push(parseImportNamespaceSpecifier());
60266 } else if (match('{')) {
60267 // import foo, {bar}
60268 specifiers = specifiers.concat(parseNamedImports());
60269 } else {
60270 throwUnexpectedToken(lookahead);
60271 }
60272 }
60273 } else {
60274 throwUnexpectedToken(lex());
60275 }
60276
60277 if (!matchContextualKeyword('from')) {
60278 throwError(lookahead.value ?
60279 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
60280 }
60281 lex();
60282 src = parseModuleSpecifier();
60283 }
60284
60285 consumeSemicolon();
60286 return node.finishImportDeclaration(specifiers, src);
60287 }
60288
60289 // ECMA-262 15.1 Scripts
60290
60291 function parseScriptBody() {
60292 var statement, body = [], token, directive, firstRestricted;
60293
60294 while (startIndex < length) {
60295 token = lookahead;
60296 if (token.type !== Token.StringLiteral) {
60297 break;
60298 }
60299
60300 statement = parseStatementListItem();
60301 body.push(statement);
60302 if (statement.expression.type !== Syntax.Literal) {
60303 // this is not directive
60304 break;
60305 }
60306 directive = source.slice(token.start + 1, token.end - 1);
60307 if (directive === 'use strict') {
60308 strict = true;
60309 if (firstRestricted) {
60310 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
60311 }
60312 } else {
60313 if (!firstRestricted && token.octal) {
60314 firstRestricted = token;
60315 }
60316 }
60317 }
60318
60319 while (startIndex < length) {
60320 statement = parseStatementListItem();
60321 /* istanbul ignore if */
60322 if (typeof statement === 'undefined') {
60323 break;
60324 }
60325 body.push(statement);
60326 }
60327 return body;
60328 }
60329
60330 function parseProgram() {
60331 var body, node;
60332
60333 peek();
60334 node = new Node();
60335
60336 body = parseScriptBody();
60337 return node.finishProgram(body, state.sourceType);
60338 }
60339
60340 function filterTokenLocation() {
60341 var i, entry, token, tokens = [];
60342
60343 for (i = 0; i < extra.tokens.length; ++i) {
60344 entry = extra.tokens[i];
60345 token = {
60346 type: entry.type,
60347 value: entry.value
60348 };
60349 if (entry.regex) {
60350 token.regex = {
60351 pattern: entry.regex.pattern,
60352 flags: entry.regex.flags
60353 };
60354 }
60355 if (extra.range) {
60356 token.range = entry.range;
60357 }
60358 if (extra.loc) {
60359 token.loc = entry.loc;
60360 }
60361 tokens.push(token);
60362 }
60363
60364 extra.tokens = tokens;
60365 }
60366
60367 function tokenize(code, options, delegate) {
60368 var toString,
60369 tokens;
60370
60371 toString = String;
60372 if (typeof code !== 'string' && !(code instanceof String)) {
60373 code = toString(code);
60374 }
60375
60376 source = code;
60377 index = 0;
60378 lineNumber = (source.length > 0) ? 1 : 0;
60379 lineStart = 0;
60380 startIndex = index;
60381 startLineNumber = lineNumber;
60382 startLineStart = lineStart;
60383 length = source.length;
60384 lookahead = null;
60385 state = {
60386 allowIn: true,
60387 allowYield: true,
60388 labelSet: {},
60389 inFunctionBody: false,
60390 inIteration: false,
60391 inSwitch: false,
60392 lastCommentStart: -1,
60393 curlyStack: []
60394 };
60395
60396 extra = {};
60397
60398 // Options matching.
60399 options = options || {};
60400
60401 // Of course we collect tokens here.
60402 options.tokens = true;
60403 extra.tokens = [];
60404 extra.tokenValues = [];
60405 extra.tokenize = true;
60406 extra.delegate = delegate;
60407
60408 // The following two fields are necessary to compute the Regex tokens.
60409 extra.openParenToken = -1;
60410 extra.openCurlyToken = -1;
60411
60412 extra.range = (typeof options.range === 'boolean') && options.range;
60413 extra.loc = (typeof options.loc === 'boolean') && options.loc;
60414
60415 if (typeof options.comment === 'boolean' && options.comment) {
60416 extra.comments = [];
60417 }
60418 if (typeof options.tolerant === 'boolean' && options.tolerant) {
60419 extra.errors = [];
60420 }
60421
60422 try {
60423 peek();
60424 if (lookahead.type === Token.EOF) {
60425 return extra.tokens;
60426 }
60427
60428 lex();
60429 while (lookahead.type !== Token.EOF) {
60430 try {
60431 lex();
60432 } catch (lexError) {
60433 if (extra.errors) {
60434 recordError(lexError);
60435 // We have to break on the first error
60436 // to avoid infinite loops.
60437 break;
60438 } else {
60439 throw lexError;
60440 }
60441 }
60442 }
60443
60444 tokens = extra.tokens;
60445 if (typeof extra.errors !== 'undefined') {
60446 tokens.errors = extra.errors;
60447 }
60448 } catch (e) {
60449 throw e;
60450 } finally {
60451 extra = {};
60452 }
60453 return tokens;
60454 }
60455
60456 function parse(code, options) {
60457 var program, toString;
60458
60459 toString = String;
60460 if (typeof code !== 'string' && !(code instanceof String)) {
60461 code = toString(code);
60462 }
60463
60464 source = code;
60465 index = 0;
60466 lineNumber = (source.length > 0) ? 1 : 0;
60467 lineStart = 0;
60468 startIndex = index;
60469 startLineNumber = lineNumber;
60470 startLineStart = lineStart;
60471 length = source.length;
60472 lookahead = null;
60473 state = {
60474 allowIn: true,
60475 allowYield: true,
60476 labelSet: {},
60477 inFunctionBody: false,
60478 inIteration: false,
60479 inSwitch: false,
60480 lastCommentStart: -1,
60481 curlyStack: [],
60482 sourceType: 'script'
60483 };
60484 strict = false;
60485
60486 extra = {};
60487 if (typeof options !== 'undefined') {
60488 extra.range = (typeof options.range === 'boolean') && options.range;
60489 extra.loc = (typeof options.loc === 'boolean') && options.loc;
60490 extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
60491
60492 if (extra.loc && options.source !== null && options.source !== undefined) {
60493 extra.source = toString(options.source);
60494 }
60495
60496 if (typeof options.tokens === 'boolean' && options.tokens) {
60497 extra.tokens = [];
60498 }
60499 if (typeof options.comment === 'boolean' && options.comment) {
60500 extra.comments = [];
60501 }
60502 if (typeof options.tolerant === 'boolean' && options.tolerant) {
60503 extra.errors = [];
60504 }
60505 if (extra.attachComment) {
60506 extra.range = true;
60507 extra.comments = [];
60508 extra.bottomRightStack = [];
60509 extra.trailingComments = [];
60510 extra.leadingComments = [];
60511 }
60512 if (options.sourceType === 'module') {
60513 // very restrictive condition for now
60514 state.sourceType = options.sourceType;
60515 strict = true;
60516 }
60517 }
60518
60519 try {
60520 program = parseProgram();
60521 if (typeof extra.comments !== 'undefined') {
60522 program.comments = extra.comments;
60523 }
60524 if (typeof extra.tokens !== 'undefined') {
60525 filterTokenLocation();
60526 program.tokens = extra.tokens;
60527 }
60528 if (typeof extra.errors !== 'undefined') {
60529 program.errors = extra.errors;
60530 }
60531 } catch (e) {
60532 throw e;
60533 } finally {
60534 extra = {};
60535 }
60536
60537 return program;
60538 }
60539
60540 // Sync with *.json manifests.
60541 exports.version = '2.7.0';
60542
60543 exports.tokenize = tokenize;
60544
60545 exports.parse = parse;
60546
60547 // Deep copy.
60548 /* istanbul ignore next */
60549 exports.Syntax = (function () {
60550 var name, types = {};
60551
60552 if (typeof Object.create === 'function') {
60553 types = Object.create(null);
60554 }
60555
60556 for (name in Syntax) {
60557 if (Syntax.hasOwnProperty(name)) {
60558 types[name] = Syntax[name];
60559 }
60560 }
60561
60562 if (typeof Object.freeze === 'function') {
60563 Object.freeze(types);
60564 }
60565
60566 return types;
60567 }());
60568
60569}));
60570/* vim: set sw=4 ts=4 et tw=80 : */
60571}, {}],336: [function (exports, require, module, global) {var core = require('./lib/core');
60572exports = module.exports = require('./lib/async');
60573exports.core = core;
60574exports.isCore = function (x) { return core[x] };
60575exports.sync = require('./lib/sync');
60576}, {"./lib/core":337,"./lib/async":339,"./lib/sync":342}],337: [function (exports, require, module, global) {module.exports = require('./core.json').reduce(function (acc, x) {
60577 acc[x] = true;
60578 return acc;
60579}, {});
60580}, {"./core.json":338}],338: [function (exports, require, module, global) {module.exports = [
60581 "assert",
60582 "buffer_ieee754",
60583 "buffer",
60584 "child_process",
60585 "cluster",
60586 "console",
60587 "constants",
60588 "crypto",
60589 "_debugger",
60590 "dgram",
60591 "dns",
60592 "domain",
60593 "events",
60594 "freelist",
60595 "fs",
60596 "http",
60597 "https",
60598 "_linklist",
60599 "module",
60600 "net",
60601 "os",
60602 "path",
60603 "punycode",
60604 "querystring",
60605 "readline",
60606 "repl",
60607 "stream",
60608 "string_decoder",
60609 "sys",
60610 "timers",
60611 "tls",
60612 "tty",
60613 "url",
60614 "util",
60615 "vm",
60616 "zlib"
60617]
60618}, {}],339: [function (exports, require, module, global) {var core = require('./core');
60619var fs = require('fs');
60620var path = require('path');
60621var caller = require('./caller.js');
60622var nodeModulesPaths = require('./node-modules-paths.js');
60623var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//;
60624
60625module.exports = function resolve (x, opts, cb) {
60626 if (typeof opts === 'function') {
60627 cb = opts;
60628 opts = {};
60629 }
60630 if (!opts) opts = {};
60631 if (typeof x !== 'string') {
60632 return process.nextTick(function () {
60633 cb(new Error('path must be a string'));
60634 });
60635 }
60636
60637 var isFile = opts.isFile || function (file, cb) {
60638 fs.stat(file, function (err, stat) {
60639 if (err && err.code === 'ENOENT') cb(null, false)
60640 else if (err) cb(err)
60641 else cb(null, stat.isFile() || stat.isFIFO())
60642 });
60643 };
60644 var readFile = opts.readFile || fs.readFile;
60645
60646 var extensions = opts.extensions || [ '.js' ];
60647 var y = opts.basedir || path.dirname(caller());
60648
60649 opts.paths = opts.paths || [];
60650
60651 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
60652 var res = path.resolve(y, x);
60653 if (x === '..') res += '/';
60654 if (/\/$/.test(x) && res === y) {
60655 loadAsDirectory(res, opts.package, onfile);
60656 }
60657 else loadAsFile(res, opts.package, onfile);
60658 }
60659 else loadNodeModules(x, y, function (err, n, pkg) {
60660 if (err) cb(err)
60661 else if (n) cb(null, n, pkg)
60662 else if (core[x]) return cb(null, x);
60663 else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
60664 });
60665
60666 function onfile (err, m, pkg) {
60667 if (err) cb(err)
60668 else if (m) cb(null, m, pkg)
60669 else loadAsDirectory(res, function (err, d, pkg) {
60670 if (err) cb(err)
60671 else if (d) cb(null, d, pkg)
60672 else cb(new Error("Cannot find module '" + x + "' from '" + y + "'"))
60673 })
60674 }
60675
60676 function loadAsFile (x, pkg, cb) {
60677 if (typeof pkg === 'function') {
60678 cb = pkg;
60679 pkg = undefined;
60680 }
60681
60682 var exts = [''].concat(extensions);
60683 load(exts, x, pkg)
60684
60685 function load (exts, x, pkg) {
60686 if (exts.length === 0) return cb(null, undefined, pkg);
60687 var file = x + exts[0];
60688
60689 if (pkg) onpkg(null, pkg)
60690 else loadpkg(path.dirname(file), onpkg);
60691
60692 function onpkg (err, pkg_, dir) {
60693 pkg = pkg_;
60694 if (err) return cb(err)
60695 if (dir && pkg && opts.pathFilter) {
60696 var rfile = path.relative(dir, file);
60697 var rel = rfile.slice(0, rfile.length - exts[0].length);
60698 var r = opts.pathFilter(pkg, x, rel);
60699 if (r) return load(
60700 [''].concat(extensions.slice()),
60701 path.resolve(dir, r),
60702 pkg
60703 );
60704 }
60705 isFile(file, onex);
60706 }
60707 function onex (err, ex) {
60708 if (err) cb(err)
60709 else if (!ex) load(exts.slice(1), x, pkg)
60710 else cb(null, file, pkg)
60711 }
60712 }
60713 }
60714
60715 function loadpkg (dir, cb) {
60716 if (dir === '' || dir === '/') return cb(null);
60717 if (process.platform === 'win32' && /^\w:[\\\/]*$/.test(dir)) {
60718 return cb(null);
60719 }
60720 if (/[\\\/]node_modules[\\\/]*$/.test(dir)) return cb(null);
60721
60722 var pkgfile = path.join(dir, 'package.json');
60723 isFile(pkgfile, function (err, ex) {
60724 // on err, ex is false
60725 if (!ex) return loadpkg(
60726 path.dirname(dir), cb
60727 );
60728
60729 readFile(pkgfile, function (err, body) {
60730 if (err) cb(err);
60731 try { var pkg = JSON.parse(body) }
60732 catch (err) {}
60733
60734 if (pkg && opts.packageFilter) {
60735 pkg = opts.packageFilter(pkg, pkgfile);
60736 }
60737 cb(null, pkg, dir);
60738 });
60739 });
60740 }
60741
60742 function loadAsDirectory (x, fpkg, cb) {
60743 if (typeof fpkg === 'function') {
60744 cb = fpkg;
60745 fpkg = opts.package;
60746 }
60747
60748 var pkgfile = path.join(x, '/package.json');
60749 isFile(pkgfile, function (err, ex) {
60750 if (err) return cb(err);
60751 if (!ex) return loadAsFile(path.join(x, '/index'), fpkg, cb);
60752
60753 readFile(pkgfile, function (err, body) {
60754 if (err) return cb(err);
60755 try {
60756 var pkg = JSON.parse(body);
60757 }
60758 catch (err) {}
60759
60760 if (opts.packageFilter) {
60761 pkg = opts.packageFilter(pkg, pkgfile);
60762 }
60763
60764 if (pkg.main) {
60765 if (pkg.main === '.' || pkg.main === './'){
60766 pkg.main = 'index'
60767 }
60768 loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
60769 if (err) return cb(err);
60770 if (m) return cb(null, m, pkg);
60771 if (!pkg) return loadAsFile(path.join(x, '/index'), pkg, cb);
60772
60773 var dir = path.resolve(x, pkg.main);
60774 loadAsDirectory(dir, pkg, function (err, n, pkg) {
60775 if (err) return cb(err);
60776 if (n) return cb(null, n, pkg);
60777 loadAsFile(path.join(x, '/index'), pkg, cb);
60778 });
60779 });
60780 return;
60781 }
60782
60783 loadAsFile(path.join(x, '/index'), pkg, cb);
60784 });
60785 });
60786 }
60787
60788 function loadNodeModules (x, start, cb) {
60789 (function process (dirs) {
60790 if (dirs.length === 0) return cb(null, undefined);
60791 var dir = dirs[0];
60792
60793 var file = path.join(dir, '/', x);
60794 loadAsFile(file, undefined, onfile);
60795
60796 function onfile (err, m, pkg) {
60797 if (err) return cb(err);
60798 if (m) return cb(null, m, pkg);
60799 loadAsDirectory(path.join(dir, '/', x), undefined, ondir);
60800 }
60801
60802 function ondir (err, n, pkg) {
60803 if (err) return cb(err);
60804 if (n) return cb(null, n, pkg);
60805 process(dirs.slice(1));
60806 }
60807 })(nodeModulesPaths(start, opts));
60808 }
60809};
60810}, {"./core":337,"fs":16,"path":8,"./caller.js":340,"./node-modules-paths.js":341}],340: [function (exports, require, module, global) {module.exports = function () {
60811 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
60812 var origPrepareStackTrace = Error.prepareStackTrace;
60813 Error.prepareStackTrace = function (_, stack) { return stack };
60814 var stack = (new Error()).stack;
60815 Error.prepareStackTrace = origPrepareStackTrace;
60816 return stack[2].getFileName();
60817};
60818}, {}],341: [function (exports, require, module, global) {var path = require('path');
60819
60820module.exports = function (start, opts) {
60821 var modules = opts.moduleDirectory
60822 ? [].concat(opts.moduleDirectory)
60823 : ['node_modules']
60824 ;
60825 var prefix = '/';
60826 if (/^([A-Za-z]:)/.test(start)) {
60827 prefix = '';
60828 } else if (/^\\\\/.test(start)) {
60829 prefix = '\\\\';
60830 }
60831 var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
60832
60833 // ensure that `start` is an absolute path at this point,
60834 // resolving againt the process' current working directory
60835 start = path.resolve(start);
60836
60837 var parts = start.split(splitRe);
60838
60839 var dirs = [];
60840 for (var i = parts.length - 1; i >= 0; i--) {
60841 if (modules.indexOf(parts[i]) !== -1) continue;
60842 dirs = dirs.concat(modules.map(function(module_dir) {
60843 return prefix + path.join(
60844 path.join.apply(path, parts.slice(0, i + 1)),
60845 module_dir
60846 );
60847 }));
60848 }
60849 if (process.platform === 'win32'){
60850 dirs[dirs.length-1] = dirs[dirs.length-1].replace(":", ":\\");
60851 }
60852 return dirs.concat(opts.paths);
60853}
60854}, {"path":8}],342: [function (exports, require, module, global) {var core = require('./core');
60855var fs = require('fs');
60856var path = require('path');
60857var caller = require('./caller.js');
60858var nodeModulesPaths = require('./node-modules-paths.js');
60859
60860module.exports = function (x, opts) {
60861 if (!opts) opts = {};
60862 var isFile = opts.isFile || function (file) {
60863 try { var stat = fs.statSync(file) }
60864 catch (err) { if (err && err.code === 'ENOENT') return false }
60865 return stat.isFile() || stat.isFIFO();
60866 };
60867 var readFileSync = opts.readFileSync || fs.readFileSync;
60868
60869 var extensions = opts.extensions || [ '.js' ];
60870 var y = opts.basedir || path.dirname(caller());
60871
60872 opts.paths = opts.paths || [];
60873
60874 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
60875 var res = path.resolve(y, x);
60876 if (x === '..') res += '/';
60877 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
60878 if (m) return m;
60879 } else {
60880 var n = loadNodeModulesSync(x, y);
60881 if (n) return n;
60882 }
60883
60884 if (core[x]) return x;
60885
60886 throw new Error("Cannot find module '" + x + "' from '" + y + "'");
60887
60888 function loadAsFileSync (x) {
60889 if (isFile(x)) {
60890 return x;
60891 }
60892
60893 for (var i = 0; i < extensions.length; i++) {
60894 var file = x + extensions[i];
60895 if (isFile(file)) {
60896 return file;
60897 }
60898 }
60899 }
60900
60901 function loadAsDirectorySync (x) {
60902 var pkgfile = path.join(x, '/package.json');
60903 if (isFile(pkgfile)) {
60904 var body = readFileSync(pkgfile, 'utf8');
60905 try {
60906 var pkg = JSON.parse(body);
60907 if (opts.packageFilter) {
60908 pkg = opts.packageFilter(pkg, x);
60909 }
60910
60911 if (pkg.main) {
60912 var m = loadAsFileSync(path.resolve(x, pkg.main));
60913 if (m) return m;
60914 var n = loadAsDirectorySync(path.resolve(x, pkg.main));
60915 if (n) return n;
60916 }
60917 }
60918 catch (err) {}
60919 }
60920
60921 return loadAsFileSync(path.join( x, '/index'));
60922 }
60923
60924 function loadNodeModulesSync (x, start) {
60925 var dirs = nodeModulesPaths(start, opts);
60926 for (var i = 0; i < dirs.length; i++) {
60927 var dir = dirs[i];
60928 var m = loadAsFileSync(path.join( dir, '/', x));
60929 if (m) return m;
60930 var n = loadAsDirectorySync(path.join( dir, '/', x ));
60931 if (n) return n;
60932 }
60933 }
60934};
60935}, {"./core":337,"fs":16,"path":8,"./caller.js":340,"./node-modules-paths.js":341}],343: [function (exports, require, module, global) {// builtin
60936var fs = require('fs');
60937var path = require('path');
60938
60939// vendor
60940var resv = require('resolve');
60941
60942// given a path, create an array of node_module paths for it
60943// borrowed from substack/resolve
60944function nodeModulesPaths (start, cb) {
60945 var splitRe = process.platform === 'win32' ? /[\/\\]/ : /\/+/;
60946 var parts = start.split(splitRe);
60947
60948 var dirs = [];
60949 for (var i = parts.length - 1; i >= 0; i--) {
60950 if (parts[i] === 'node_modules') continue;
60951 var dir = path.join.apply(
60952 path, parts.slice(0, i + 1).concat(['node_modules'])
60953 );
60954 if (!parts[0].match(/([A-Za-z]:)/)) {
60955 dir = '/' + dir;
60956 }
60957 dirs.push(dir);
60958 }
60959 return dirs;
60960}
60961
60962function find_shims_in_package(pkgJson, cur_path, shims, browser) {
60963 try {
60964 var info = JSON.parse(pkgJson);
60965 }
60966 catch (err) {
60967 err.message = pkgJson + ' : ' + err.message
60968 throw err;
60969 }
60970
60971 var replacements = getReplacements(info, browser);
60972
60973 // no replacements, skip shims
60974 if (!replacements) {
60975 return;
60976 }
60977
60978 // if browser mapping is a string
60979 // then it just replaces the main entry point
60980 if (typeof replacements === 'string') {
60981 var key = path.resolve(cur_path, info.main || 'index.js');
60982 shims[key] = path.resolve(cur_path, replacements);
60983 return;
60984 }
60985
60986 // http://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders
60987 Object.keys(replacements).forEach(function(key) {
60988 var val;
60989 if (replacements[key] === false) {
60990 val = __dirname + '/empty.js';
60991 }
60992 else {
60993 val = replacements[key];
60994 // if target is a relative path, then resolve
60995 // otherwise we assume target is a module
60996 if (val[0] === '.') {
60997 val = path.resolve(cur_path, val);
60998 }
60999 }
61000
61001 if (key[0] === '/' || key[0] === '.') {
61002 // if begins with / ../ or ./ then we must resolve to a full path
61003 key = path.resolve(cur_path, key);
61004 }
61005 shims[key] = val;
61006 });
61007}
61008
61009// paths is mutated
61010// load shims from first package.json file found
61011function load_shims(paths, browser, cb) {
61012 // identify if our file should be replaced per the browser field
61013 // original filename|id -> replacement
61014 var shims = Object.create(null);
61015
61016 (function next() {
61017 var cur_path = paths.shift();
61018 if (!cur_path) {
61019 return cb(null, shims);
61020 }
61021
61022 var pkg_path = path.join(cur_path, 'package.json');
61023
61024 fs.readFile(pkg_path, 'utf8', function(err, data) {
61025 if (err) {
61026 // ignore paths we can't open
61027 // avoids an exists check
61028 if (err.code === 'ENOENT') {
61029 return next();
61030 }
61031
61032 return cb(err);
61033 }
61034 try {
61035 find_shims_in_package(data, cur_path, shims, browser);
61036 return cb(null, shims);
61037 }
61038 catch (err) {
61039 return cb(err);
61040 }
61041 });
61042 })();
61043};
61044
61045// paths is mutated
61046// synchronously load shims from first package.json file found
61047function load_shims_sync(paths, browser) {
61048 // identify if our file should be replaced per the browser field
61049 // original filename|id -> replacement
61050 var shims = Object.create(null);
61051 var cur_path;
61052
61053 while (cur_path = paths.shift()) {
61054 var pkg_path = path.join(cur_path, 'package.json');
61055
61056 try {
61057 var data = fs.readFileSync(pkg_path, 'utf8');
61058 find_shims_in_package(data, cur_path, shims, browser);
61059 return shims;
61060 }
61061 catch (err) {
61062 // ignore paths we can't open
61063 // avoids an exists check
61064 if (err.code === 'ENOENT') {
61065 continue;
61066 }
61067
61068 throw err;
61069 }
61070 }
61071 return shims;
61072}
61073
61074function build_resolve_opts(opts, base) {
61075 var packageFilter = opts.packageFilter;
61076 var browser = normalizeBrowserFieldName(opts.browser)
61077
61078 opts.basedir = base;
61079 opts.packageFilter = function (info, pkgdir) {
61080 if (packageFilter) info = packageFilter(info, pkgdir);
61081
61082 var replacements = getReplacements(info, browser);
61083
61084 // no browser field, keep info unchanged
61085 if (!replacements) {
61086 return info;
61087 }
61088
61089 info[browser] = replacements;
61090
61091 // replace main
61092 if (typeof replacements === 'string') {
61093 info.main = replacements;
61094 return info;
61095 }
61096
61097 var replace_main = replacements[info.main || './index.js'] ||
61098 replacements['./' + info.main || './index.js'];
61099
61100 info.main = replace_main || info.main;
61101 return info;
61102 };
61103
61104 var pathFilter = opts.pathFilter;
61105 opts.pathFilter = function(info, resvPath, relativePath) {
61106 if (relativePath[0] != '.') {
61107 relativePath = './' + relativePath;
61108 }
61109 var mappedPath;
61110 if (pathFilter) {
61111 mappedPath = pathFilter.apply(this, arguments);
61112 }
61113 if (mappedPath) {
61114 return mappedPath;
61115 }
61116
61117 var replacements = info[browser];
61118 if (!replacements) {
61119 return;
61120 }
61121
61122 mappedPath = replacements[relativePath];
61123 if (!mappedPath && path.extname(relativePath) === '') {
61124 mappedPath = replacements[relativePath + '.js'];
61125 if (!mappedPath) {
61126 mappedPath = replacements[relativePath + '.json'];
61127 }
61128 }
61129 return mappedPath;
61130 };
61131
61132 return opts;
61133}
61134
61135function resolve(id, opts, cb) {
61136
61137 // opts.filename
61138 // opts.paths
61139 // opts.modules
61140 // opts.packageFilter
61141
61142 opts = opts || {};
61143
61144 var base = path.dirname(opts.filename);
61145
61146 if (opts.basedir) {
61147 base = opts.basedir;
61148 }
61149
61150 var paths = nodeModulesPaths(base);
61151
61152 if (opts.paths) {
61153 paths.push.apply(paths, opts.paths);
61154 }
61155
61156 paths = paths.map(function(p) {
61157 return path.dirname(p);
61158 });
61159
61160 // we must always load shims because the browser field could shim out a module
61161 load_shims(paths, opts.browser, function(err, shims) {
61162 if (err) {
61163 return cb(err);
61164 }
61165
61166 if (shims[id]) {
61167 // if the shim was is an absolute path, it was fully resolved
61168 if (shims[id][0] === '/') {
61169 return cb(null, shims[id], opts.package);
61170 }
61171
61172 // module -> alt-module shims
61173 id = shims[id];
61174 }
61175
61176 var modules = opts.modules || Object.create(null);
61177 var shim_path = modules[id];
61178 if (shim_path) {
61179 return cb(null, shim_path);
61180 }
61181
61182 // our browser field resolver
61183 // if browser field is an object tho?
61184 var full = resv(id, build_resolve_opts(opts, base), function(err, full, pkg) {
61185 if (err) {
61186 return cb(err);
61187 }
61188
61189 var resolved = (shims) ? shims[full] || full : full;
61190 cb(null, resolved, pkg);
61191 });
61192 });
61193};
61194
61195resolve.sync = function (id, opts) {
61196
61197 // opts.filename
61198 // opts.paths
61199 // opts.modules
61200 // opts.packageFilter
61201
61202 opts = opts || {};
61203 var base = path.dirname(opts.filename);
61204
61205 if (opts.basedir) {
61206 base = opts.basedir;
61207 }
61208
61209 var paths = nodeModulesPaths(base);
61210
61211 if (opts.paths) {
61212 paths.push.apply(paths, opts.paths);
61213 }
61214
61215 paths = paths.map(function(p) {
61216 return path.dirname(p);
61217 });
61218
61219 // we must always load shims because the browser field could shim out a module
61220 var shims = load_shims_sync(paths, opts.browser);
61221
61222 if (shims[id]) {
61223 // if the shim was is an absolute path, it was fully resolved
61224 if (shims[id][0] === '/') {
61225 return shims[id];
61226 }
61227
61228 // module -> alt-module shims
61229 id = shims[id];
61230 }
61231
61232 var modules = opts.modules || Object.create(null);
61233 var shim_path = modules[id];
61234 if (shim_path) {
61235 return shim_path;
61236 }
61237
61238 // our browser field resolver
61239 // if browser field is an object tho?
61240 var full = resv.sync(id, build_resolve_opts(opts, base));
61241
61242 return (shims) ? shims[full] || full : full;
61243};
61244
61245function normalizeBrowserFieldName(browser) {
61246 return browser || 'browser';
61247}
61248
61249function getReplacements(info, browser) {
61250 browser = normalizeBrowserFieldName(browser);
61251 var replacements = info[browser] || info.browser;
61252
61253 // support legacy browserify field for easier migration from legacy
61254 // many packages used this field historically
61255 if (typeof info.browserify === 'string' && !replacements) {
61256 replacements = info.browserify;
61257 }
61258
61259 return replacements;
61260}
61261
61262module.exports = resolve;
61263}, {"fs":16,"path":8,"resolve":336}]}, this);
\No newline at end of file