UNPKG

334 kBJavaScriptView Raw
1/**
2 * Modules in this bundle
3 * @license
4 *
5 * power-assert-formatter:
6 * license: MIT
7 * author: Takuto Wada <takuto.wada@gmail.com>
8 * contributors: James Talmage
9 * homepage: http://github.com/power-assert-js/power-assert-formatter
10 * version: 1.3.2
11 *
12 * acorn:
13 * license: MIT
14 * maintainers: marijn <marijnh@gmail.com>, rreverser <me@rreverser.com>
15 * contributors: keeyipchan, List of Acorn contributors. Updated before every release., Alistair Braidwood, Andres Suarez, Aparajita Fishman, Arian Stolwijk, Artem Govorov, Brandon Mills, Charles Hughes, Conrad Irwin, David Bonnet, ForbesLindesay, Forbes Lindesay, Gilad Peleg, impinball, Ingvar Stepanyan, Jesse McCarthy, Jiaxing Wang, Joel Kemp, Johannes Herr, Jürg Lehni, Adrian Rakovsky, Kevin Kwok, krator, Marijn Haverbeke, Martin Carlberg, Mathias Bynens, Mathieu 'p01' Henri, Max Schaefer, Max Zerzouri, Mihai Bazon, Mike Rennie, Nick Fitzgerald, Oskar Schöldström, Paul Harper, Peter Rust, PlNG, r-e-d, Rich Harris, Sebastian McKenzie, Timothy Gu, zsjforcn
16 * homepage: https://github.com/ternjs/acorn
17 * version: 2.6.4
18 *
19 * acorn-es7-plugin:
20 * license: MIT
21 * author: matatbread
22 * maintainers: matatbread <npm@mailed.me.uk>
23 * homepage: https://github.com/MatAtBread/acorn-es7-plugin#readme
24 * version: 1.0.10
25 *
26 * array-filter:
27 * license: MIT
28 * author: Julian Gruber <mail@juliangruber.com>
29 * maintainers: juliangruber <julian@juliangruber.com>
30 * homepage: https://github.com/juliangruber/array-filter
31 * version: 1.0.0
32 *
33 * array-foreach:
34 * license: MIT
35 * author: Takuto Wada <takuto.wada@gmail.com>
36 * maintainers: twada <takuto.wada@gmail.com>
37 * homepage: https://github.com/twada/array-foreach
38 * version: 1.0.1
39 *
40 * array-map:
41 * license: MIT
42 * author: James Halliday <mail@substack.net>
43 * maintainers: substack <mail@substack.net>
44 * homepage: https://github.com/substack/array-map
45 * version: 0.0.0
46 *
47 * array-reduce:
48 * license: MIT
49 * author: James Halliday <mail@substack.net>
50 * maintainers: substack <mail@substack.net>
51 * homepage: https://github.com/substack/array-reduce
52 * version: 0.0.0
53 *
54 * array-reduce-right:
55 * license: MIT
56 * author: Takuto Wada <takuto.wada@gmail.com>
57 * maintainers: twada <takuto.wada@gmail.com>
58 * homepage: https://github.com/twada/array-reduce-right
59 * version: 1.0.0
60 *
61 * eastasianwidth:
62 * license: MIT
63 * author: Masaki Komagata
64 * maintainers: komagata <komagata@gmail.com>
65 * homepage: https://github.com/komagata/eastasianwidth#readme
66 * version: 0.1.1
67 *
68 * estraverse:
69 * license: BSD-2-Clause
70 * maintainers: constellation <utatane.tea@gmail.com>, michaelficarra <npm@michael.ficarra.me>, nzakas <nicholas@nczconsulting.com>
71 * homepage: https://github.com/estools/estraverse
72 * version: 4.1.1
73 *
74 * events:
75 * author: Irakli Gozalishvili <rfobic@gmail.com>
76 * maintainers: gozala <rfobic@gmail.com>, shtylman <shtylman@gmail.com>
77 * homepage: https://github.com/Gozala/events
78 * version: 1.0.2
79 *
80 * googlediff:
81 * licenses: Apache
82 * author: Neil Fraser <root@neil.fraser.name>
83 * maintainers: shimondoodkin <helpmepro1@gmail.com>
84 * contributors: Shimon Doodkin <helpmepro1@gmail.com>, Ryan Graham <r.m.graham@gmail.com>
85 * homepage: http://code.google.com/p/google-diff-match-patch/
86 * version: 0.1.0
87 *
88 * indexof:
89 * maintainers: tjholowaychuk <tj@vision-media.ca>
90 * version: 0.0.1
91 *
92 * inherits:
93 * license: ISC
94 * maintainers: isaacs <i@izs.me>
95 * homepage: https://github.com/isaacs/inherits#readme
96 * version: 2.0.1
97 *
98 * object-keys:
99 * license: MIT
100 * author: Jordan Harband <ljharb@gmail.com>
101 * maintainers: ljharb <ljharb@gmail.com>
102 * contributors: Jordan Harband <ljharb@gmail.com>, Raynos <raynos2@gmail.com>, Nathan Rajlich <nathan@tootallnate.net>, Ivan Starkov <istarkov@gmail.com>, Gary Katsevman <git@gkatsev.com>
103 * homepage: https://github.com/ljharb/object-keys#readme
104 * version: 1.0.9
105 *
106 * process:
107 * license: MIT
108 * author: Roman Shtylman <shtylman@gmail.com>
109 * maintainers: coolaj86 <coolaj86@gmail.com>, defunctzombie <shtylman@gmail.com>
110 * homepage: https://github.com/shtylman/node-process#readme
111 * version: 0.11.2
112 *
113 * stringifier:
114 * license: MIT
115 * author: Takuto Wada <takuto.wada@gmail.com>
116 * maintainers: twada <takuto.wada@gmail.com>
117 * homepage: https://github.com/twada/stringifier
118 * version: 1.2.1
119 *
120 * traverse:
121 * license: MIT
122 * author: James Halliday <mail@substack.net>
123 * maintainers: substack <mail@substack.net>
124 * homepage: https://github.com/substack/js-traverse
125 * version: 0.6.6
126 *
127 * type-name:
128 * license: MIT
129 * author: Takuto Wada <takuto.wada@gmail.com>
130 * maintainers: twada <takuto.wada@gmail.com>
131 * contributors: azu, Yosuke Furukawa
132 * homepage: https://github.com/twada/type-name
133 * version: 1.1.0
134 *
135 * util:
136 * license: MIT
137 * author: Joyent
138 * maintainers: shtylman <shtylman@gmail.com>
139 * homepage: https://github.com/defunctzombie/node-util
140 * version: 0.10.3
141 *
142 * xtend:
143 * license: MIT
144 * author: Raynos <raynos2@gmail.com>
145 * maintainers: raynos <raynos2@gmail.com>
146 * contributors: Jake Verbaten, Matt Esch
147 * homepage: https://github.com/Raynos/xtend
148 * version: 4.0.1
149 *
150 * This header is generated by licensify (https://github.com/twada/licensify)
151 */
152(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.powerAssertFormatter = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
153/**
154 * power-assert-formatter.js - Power Assert output formatter
155 *
156 * https://github.com/power-assert-js/power-assert-formatter
157 *
158 * Copyright (c) 2013-2015 Takuto Wada
159 * Licensed under the MIT license.
160 * https://github.com/power-assert-js/power-assert-formatter/blob/master/MIT-LICENSE.txt
161 */
162'use strict';
163
164module.exports = _dereq_('./lib/create');
165
166},{"./lib/create":6}],2:[function(_dereq_,module,exports){
167'use strict';
168
169function AssertionRenderer (config) {
170}
171
172AssertionRenderer.prototype.init = function (traversal) {
173 var assertionLine;
174 traversal.on('start', function (context) {
175 assertionLine = context.source.content;
176 });
177 traversal.on('render', function (writer) {
178 writer.write('');
179 writer.write(assertionLine);
180 });
181};
182
183module.exports = AssertionRenderer;
184
185},{}],3:[function(_dereq_,module,exports){
186'use strict';
187
188var typeName = _dereq_('type-name');
189var keys = Object.keys || _dereq_('object-keys');
190var syntax = _dereq_('estraverse').Syntax;
191var forEach = _dereq_('array-foreach');
192
193
194function BinaryExpressionRenderer(config) {
195 this.config = config;
196 this.stringify = config.stringify;
197 this.diff = config.diff;
198 this.espathToPair = {};
199}
200
201BinaryExpressionRenderer.prototype.init = function (traversal) {
202 var _this = this;
203 traversal.on('esnode', function (esNode) {
204 var pair;
205 if (!esNode.isCaptured()) {
206 if (isTargetBinaryExpression(esNode.getParent()) && esNode.currentNode.type === syntax.Literal) {
207 _this.espathToPair[esNode.parentEspath][esNode.currentProp] = {code: esNode.code(), value: esNode.value()};
208 }
209 return;
210 }
211 if (isTargetBinaryExpression(esNode.getParent())) {
212 _this.espathToPair[esNode.parentEspath][esNode.currentProp] = {code: esNode.code(), value: esNode.value()};
213 }
214 if (isTargetBinaryExpression(esNode)) {
215 pair = {
216 operator: esNode.currentNode.operator,
217 value: esNode.value()
218 };
219 _this.espathToPair[esNode.espath] = pair;
220 }
221 });
222 traversal.on('render', function (writer) {
223 var pairs = [];
224 forEach(keys(_this.espathToPair), function (espath) {
225 var pair = _this.espathToPair[espath];
226 if (pair.left && pair.right) {
227 pairs.push(pair);
228 }
229 });
230 forEach(pairs, function (pair) {
231 _this.compare(pair, writer);
232 });
233 });
234};
235
236BinaryExpressionRenderer.prototype.compare = function (pair, writer) {
237 if (isStringDiffTarget(pair)) {
238 this.showStringDiff(pair, writer);
239 } else {
240 this.showExpectedAndActual(pair, writer);
241 }
242};
243
244BinaryExpressionRenderer.prototype.showExpectedAndActual = function (pair, writer) {
245 writer.write('');
246 writer.write('[' + typeName(pair.right.value) + '] ' + pair.right.code);
247 writer.write('=> ' + this.stringify(pair.right.value));
248 writer.write('[' + typeName(pair.left.value) + '] ' + pair.left.code);
249 writer.write('=> ' + this.stringify(pair.left.value));
250};
251
252BinaryExpressionRenderer.prototype.showStringDiff = function (pair, writer) {
253 writer.write('');
254 writer.write('--- [string] ' + pair.right.code);
255 writer.write('+++ [string] ' + pair.left.code);
256 writer.write(this.diff(pair.right.value, pair.left.value, this.config));
257};
258
259function isTargetBinaryExpression (esNode) {
260 return esNode &&
261 esNode.currentNode.type === syntax.BinaryExpression &&
262 (esNode.currentNode.operator === '===' || esNode.currentNode.operator === '==') &&
263 esNode.isCaptured() &&
264 !(esNode.value());
265}
266
267function isStringDiffTarget(pair) {
268 return typeof pair.left.value === 'string' && typeof pair.right.value === 'string';
269}
270
271module.exports = BinaryExpressionRenderer;
272
273},{"array-foreach":17,"estraverse":22,"object-keys":29,"type-name":35}],4:[function(_dereq_,module,exports){
274'use strict';
275
276var forEach = _dereq_('array-foreach');
277
278function DiagramRenderer (config) {
279 this.config = config;
280 this.events = [];
281 this.stringify = config.stringify;
282 this.widthOf = config.widthOf;
283 this.initialVertivalBarLength = 1;
284}
285
286DiagramRenderer.prototype.init = function (traversal) {
287 var _this = this;
288 traversal.on('start', function (context) {
289 _this.context = context;
290 _this.assertionLine = context.source.content;
291 _this.initializeRows();
292 });
293 traversal.on('esnode', function (esNode) {
294 if (!esNode.isCaptured()) {
295 return;
296 }
297 _this.events.push({value: esNode.value(), loc: esNode.location()});
298 });
299 traversal.on('render', function (writer) {
300 _this.events.sort(rightToLeft);
301 _this.constructRows(_this.events);
302 forEach(_this.rows, function (columns) {
303 writer.write(columns.join(''));
304 });
305 });
306};
307
308DiagramRenderer.prototype.initializeRows = function () {
309 this.rows = [];
310 for (var i = 0; i <= this.initialVertivalBarLength; i += 1) {
311 this.addOneMoreRow();
312 }
313};
314
315DiagramRenderer.prototype.newRowFor = function (assertionLine) {
316 return createRow(this.widthOf(assertionLine), ' ');
317};
318
319DiagramRenderer.prototype.addOneMoreRow = function () {
320 this.rows.push(this.newRowFor(this.assertionLine));
321};
322
323DiagramRenderer.prototype.lastRow = function () {
324 return this.rows[this.rows.length - 1];
325};
326
327DiagramRenderer.prototype.renderVerticalBarAt = function (columnIndex) {
328 var i, lastRowIndex = this.rows.length - 1;
329 for (i = 0; i < lastRowIndex; i += 1) {
330 this.rows[i].splice(columnIndex, 1, '|');
331 }
332};
333
334DiagramRenderer.prototype.renderValueAt = function (columnIndex, dumpedValue) {
335 var i, width = this.widthOf(dumpedValue);
336 for (i = 0; i < width; i += 1) {
337 this.lastRow().splice(columnIndex + i, 1, dumpedValue.charAt(i));
338 }
339};
340
341DiagramRenderer.prototype.isOverlapped = function (prevCapturing, nextCaputuring, dumpedValue) {
342 return (typeof prevCapturing !== 'undefined') && this.startColumnFor(prevCapturing) <= (this.startColumnFor(nextCaputuring) + this.widthOf(dumpedValue));
343};
344
345DiagramRenderer.prototype.constructRows = function (capturedEvents) {
346 var that = this;
347 var prevCaptured;
348 forEach(capturedEvents, function (captured) {
349 var dumpedValue = that.stringify(captured.value);
350 if (that.isOverlapped(prevCaptured, captured, dumpedValue)) {
351 that.addOneMoreRow();
352 }
353 that.renderVerticalBarAt(that.startColumnFor(captured));
354 that.renderValueAt(that.startColumnFor(captured), dumpedValue);
355 prevCaptured = captured;
356 });
357};
358
359DiagramRenderer.prototype.startColumnFor = function (captured) {
360 return this.widthOf(this.assertionLine.slice(0, captured.loc.start.column));
361};
362
363function createRow (numCols, initial) {
364 var row = [], i;
365 for(i = 0; i < numCols; i += 1) {
366 row[i] = initial;
367 }
368 return row;
369}
370
371function rightToLeft (a, b) {
372 return b.loc.start.column - a.loc.start.column;
373}
374
375module.exports = DiagramRenderer;
376
377},{"array-foreach":17}],5:[function(_dereq_,module,exports){
378'use strict';
379
380function FileRenderer (config) {
381}
382
383FileRenderer.prototype.init = function (traversal) {
384 var filepath, lineNumber;
385 traversal.on('start', function (context) {
386 filepath = context.source.filepath;
387 lineNumber = context.source.line;
388 });
389 traversal.on('render', function (writer) {
390 if (filepath) {
391 writer.write('# ' + [filepath, lineNumber].join(':'));
392 } else {
393 writer.write('# at line: ' + lineNumber);
394 }
395 });
396};
397
398module.exports = FileRenderer;
399
400},{}],6:[function(_dereq_,module,exports){
401'use strict';
402
403var stringifier = _dereq_('stringifier');
404var stringWidth = _dereq_('./string-width');
405var StringWriter = _dereq_('./string-writer');
406var ContextTraversal = _dereq_('./traverse');
407var udiff = _dereq_('./udiff');
408var defaultOptions = _dereq_('./default-options');
409var typeName = _dereq_('type-name');
410var extend = _dereq_('xtend');
411var map = _dereq_('array-map');
412
413var AssertionRenderer = _dereq_('./built-in/assertion');
414var FileRenderer = _dereq_('./built-in/file');
415var DiagramRenderer = _dereq_('./built-in/diagram');
416var BinaryExpressionRenderer = _dereq_('./built-in/binary-expression');
417
418// "Browserify can only analyze static requires. It is not in the scope of browserify to handle dynamic requires."
419// https://github.com/substack/node-browserify/issues/377
420var defaultRendererClasses = {
421 './built-in/file': FileRenderer,
422 './built-in/assertion': AssertionRenderer,
423 './built-in/diagram': DiagramRenderer,
424 './built-in/binary-expression': BinaryExpressionRenderer
425};
426
427function toRendererClass (rendererName) {
428 var RendererClass;
429 if (typeName(rendererName) === 'function') {
430 RendererClass = rendererName;
431 } else if (typeName(rendererName) === 'string') {
432 if (defaultRendererClasses[rendererName]) {
433 RendererClass = defaultRendererClasses[rendererName];
434 } else {
435 RendererClass = _dereq_(rendererName);
436 }
437 }
438 return RendererClass;
439}
440
441function configure (options) {
442 var config = extend(defaultOptions(), options);
443 if (typeof config.widthOf !== 'function') {
444 config.widthOf = stringWidth(extend(config));
445 }
446 if (typeof config.stringify !== 'function') {
447 config.stringify = stringifier(extend(config));
448 }
449 if (typeof config.diff !== 'function') {
450 config.diff = udiff(extend(config));
451 }
452 if (!config.writerClass) {
453 config.writerClass = StringWriter;
454 }
455 return config;
456}
457
458function create (options) {
459 var config = configure(options);
460 var rendererClasses = map(config.renderers, toRendererClass);
461 return function (context) {
462 var traversal = new ContextTraversal(context);
463 var writer = new config.writerClass(extend(config));
464 var renderers = map(rendererClasses, function (RendererClass) {
465 var renderer;
466 if (RendererClass.length === 2) {
467 renderer = new RendererClass(traversal, extend(config));
468 } else {
469 renderer = new RendererClass(extend(config));
470 renderer.init(traversal);
471 }
472 return renderer;
473 });
474 traversal.emit('start', context);
475 traversal.traverse();
476 traversal.emit('render', writer);
477 writer.write('');
478 renderers.length = 0;
479 return writer.flush();
480 };
481}
482
483create.renderers = {
484 AssertionRenderer: AssertionRenderer,
485 FileRenderer: FileRenderer,
486 DiagramRenderer: DiagramRenderer,
487 BinaryExpressionRenderer: BinaryExpressionRenderer
488};
489create.defaultOptions = defaultOptions;
490create.stringWidth = stringWidth;
491module.exports = create;
492
493},{"./built-in/assertion":2,"./built-in/binary-expression":3,"./built-in/diagram":4,"./built-in/file":5,"./default-options":7,"./string-width":10,"./string-writer":11,"./traverse":12,"./udiff":13,"array-map":18,"stringifier":32,"type-name":35,"xtend":38}],7:[function(_dereq_,module,exports){
494'use strict';
495
496module.exports = function defaultOptions () {
497 return {
498 lineDiffThreshold: 5,
499 maxDepth: 1,
500 outputOffset: 2,
501 anonymous: 'Object',
502 circular: '#@Circular#',
503 lineSeparator: '\n',
504 ambiguousEastAsianCharWidth: 2,
505 renderers: [
506 './built-in/file',
507 './built-in/assertion',
508 './built-in/diagram',
509 './built-in/binary-expression'
510 ]
511 };
512};
513
514},{}],8:[function(_dereq_,module,exports){
515'use strict';
516
517var syntax = _dereq_('estraverse').Syntax;
518var locationOf = _dereq_('./location');
519
520function EsNode (path, currentNode, parentNode, espathToValue, jsCode, tokens) {
521 if (path) {
522 this.espath = path.join('/');
523 this.parentEspath = path.slice(0, path.length - 1).join('/');
524 this.currentProp = path[path.length - 1];
525 } else {
526 this.espath = '';
527 this.parentEspath = '';
528 this.currentProp = null;
529 }
530 this.currentNode = currentNode;
531 this.parentNode = parentNode;
532 this.parentEsNode = null;
533 this.espathToValue = espathToValue;
534 this.jsCode = jsCode;
535 this.tokens = tokens;
536}
537
538EsNode.prototype.setParent = function (parentEsNode) {
539 this.parentEsNode = parentEsNode;
540};
541
542EsNode.prototype.getParent = function () {
543 return this.parentEsNode;
544};
545
546EsNode.prototype.code = function () {
547 return this.jsCode.slice(this.currentNode.loc.start.column, this.currentNode.loc.end.column);
548};
549
550EsNode.prototype.value = function () {
551 if (this.currentNode.type === syntax.Literal) {
552 return this.currentNode.value;
553 }
554 return this.espathToValue[this.espath];
555};
556
557EsNode.prototype.isCaptured = function () {
558 return this.espathToValue.hasOwnProperty(this.espath);
559};
560
561EsNode.prototype.location = function () {
562 return locationOf(this.currentNode, this.tokens);
563};
564
565module.exports = EsNode;
566
567},{"./location":9,"estraverse":22}],9:[function(_dereq_,module,exports){
568'use strict';
569
570var syntax = _dereq_('estraverse').Syntax;
571
572function locationOf(currentNode, tokens) {
573 switch(currentNode.type) {
574 case syntax.MemberExpression:
575 return propertyLocationOf(currentNode, tokens);
576 case syntax.CallExpression:
577 if (currentNode.callee.type === syntax.MemberExpression) {
578 return propertyLocationOf(currentNode.callee, tokens);
579 }
580 break;
581 case syntax.BinaryExpression:
582 case syntax.LogicalExpression:
583 case syntax.AssignmentExpression:
584 return infixOperatorLocationOf(currentNode, tokens);
585 default:
586 break;
587 }
588 return currentNode.loc;
589}
590
591function propertyLocationOf(memberExpression, tokens) {
592 var prop = memberExpression.property;
593 var token;
594 if (!memberExpression.computed) {
595 return prop.loc;
596 }
597 token = findLeftBracketTokenOf(memberExpression, tokens);
598 return token ? token.loc : prop.loc;
599}
600
601// calculate location of infix operator for BinaryExpression, AssignmentExpression and LogicalExpression.
602function infixOperatorLocationOf (expression, tokens) {
603 var token = findOperatorTokenOf(expression, tokens);
604 return token ? token.loc : expression.left.loc;
605}
606
607function findLeftBracketTokenOf(expression, tokens) {
608 var fromLine = expression.loc.start.line;
609 var toLine = expression.property.loc.start.line;
610 var fromColumn = expression.property.loc.start.column;
611 return searchToken(tokens, fromLine, toLine, function (token, index) {
612 var prevToken;
613 if (token.loc.start.column === fromColumn) {
614 prevToken = tokens[index - 1];
615 // if (prevToken.type === 'Punctuator' && prevToken.value === '[') { // esprima
616 if (prevToken.type.label === '[') { // acorn
617 return prevToken;
618 }
619 }
620 return undefined;
621 });
622}
623
624function findOperatorTokenOf(expression, tokens) {
625 var fromLine = expression.left.loc.end.line;
626 var toLine = expression.right.loc.start.line;
627 var fromColumn = expression.left.loc.end.column;
628 var toColumn = expression.right.loc.start.column;
629 return searchToken(tokens, fromLine, toLine, function (token, index) {
630 if (fromColumn < token.loc.start.column &&
631 token.loc.end.column < toColumn &&
632 token.value === expression.operator) {
633 return token;
634 }
635 return undefined;
636 });
637}
638
639function searchToken(tokens, fromLine, toLine, predicate) {
640 var i, token, found;
641 for(i = 0; i < tokens.length; i += 1) {
642 token = tokens[i];
643 if (token.loc.start.line < fromLine) {
644 continue;
645 }
646 if (toLine < token.loc.end.line) {
647 break;
648 }
649 found = predicate(token, i);
650 if (found) {
651 return found;
652 }
653 }
654 return undefined;
655}
656
657module.exports = locationOf;
658
659},{"estraverse":22}],10:[function(_dereq_,module,exports){
660'use strict';
661
662var eaw = _dereq_('eastasianwidth');
663
664function stringWidth (config) {
665 var ambiguousCharWidth = (config && config.ambiguousEastAsianCharWidth) || 1;
666 return function widthOf (str) {
667 var i, code, width = 0;
668 for(i = 0; i < str.length; i+=1) {
669 code = eaw.eastAsianWidth(str.charAt(i));
670 switch(code) {
671 case 'F':
672 case 'W':
673 width += 2;
674 break;
675 case 'H':
676 case 'Na':
677 case 'N':
678 width += 1;
679 break;
680 case 'A':
681 width += ambiguousCharWidth;
682 break;
683 }
684 }
685 return width;
686 };
687}
688
689module.exports = stringWidth;
690
691},{"eastasianwidth":21}],11:[function(_dereq_,module,exports){
692'use strict';
693
694function spacerStr (len) {
695 var str = '';
696 for(var i = 0; i < len; i += 1) {
697 str += ' ';
698 }
699 return str;
700}
701
702function StringWriter (config) {
703 this.lines = [];
704 this.lineSeparator = config.lineSeparator;
705 this.regex = new RegExp(this.lineSeparator, 'g');
706 this.spacer = spacerStr(config.outputOffset);
707}
708
709StringWriter.prototype.write = function (str) {
710 this.lines.push(this.spacer + str.replace(this.regex, this.lineSeparator + this.spacer));
711};
712
713StringWriter.prototype.flush = function () {
714 var str = this.lines.join(this.lineSeparator);
715 this.lines.length = 0;
716 return str;
717};
718
719module.exports = StringWriter;
720
721},{}],12:[function(_dereq_,module,exports){
722'use strict';
723
724var estraverse = _dereq_('estraverse');
725var parser = _dereq_('acorn');
726_dereq_('acorn-es7-plugin')(parser);
727var EventEmitter = _dereq_('events').EventEmitter;
728var inherits = _dereq_('util').inherits;
729var EsNode = _dereq_('./esnode');
730var forEach = _dereq_('array-foreach');
731var reduce = _dereq_('array-reduce');
732
733function ContextTraversal (context) {
734 this.context = context;
735 EventEmitter.call(this);
736}
737inherits(ContextTraversal, EventEmitter);
738
739ContextTraversal.prototype.traverse = function () {
740 var _this = this;
741 forEach(this.context.args, function (arg) {
742 onEachEsNode(arg, _this.context.source, function (esNode) {
743 _this.emit('esnode', esNode);
744 });
745 });
746};
747
748function onEachEsNode(arg, source, callback) {
749 var parseResult = parse(source);
750 var tokens = parseResult.tokens;
751 var espathToValue = reduce(arg.events, function (accum, ev) {
752 accum[ev.espath] = ev.value;
753 return accum;
754 }, {});
755 var nodeStack = [];
756 estraverse.traverse(parseResult.expression, {
757 enter: function (currentNode, parentNode) {
758 var esNode = new EsNode(this.path(), currentNode, parentNode, espathToValue, source.content, tokens);
759 if (1 < nodeStack.length) {
760 esNode.setParent(nodeStack[nodeStack.length - 1]);
761 }
762 nodeStack.push(esNode);
763 callback(esNode);
764 },
765 leave: function (currentNode, parentNode) {
766 nodeStack.pop();
767 }
768 });
769}
770
771function parserOptions(tokens) {
772 return {
773 sourceType: 'module',
774 ecmaVersion: 7,
775 locations: true,
776 ranges: true,
777 onToken: tokens,
778 plugins: {asyncawait: true}
779 };
780}
781
782function wrappedInGenerator(jsCode) {
783 return 'function *wrapper() {\n' + jsCode + '\n}';
784}
785
786function wrappedInAsync(jsCode) {
787 return 'async function wrapper() {\n' + jsCode + '\n}';
788}
789
790function parse(source) {
791 var ast;
792 var tokens = [];
793
794 function doParse(wrapper) {
795 var content = wrapper ? wrapper(source.content) : source.content;
796 ast = parser.parse(content, parserOptions(tokens));
797 if (wrapper) {
798 ast = ast.body[0].body;
799 }
800 }
801
802 if (source.async) {
803 doParse(wrappedInAsync);
804 } else if (source.generator) {
805 doParse(wrappedInGenerator);
806 } else {
807 doParse();
808 }
809
810 return {
811 tokens: tokens,
812 expression: ast.body[0].expression
813 };
814}
815
816module.exports = ContextTraversal;
817
818},{"./esnode":8,"acorn":15,"acorn-es7-plugin":14,"array-foreach":17,"array-reduce":20,"estraverse":22,"events":24,"util":37}],13:[function(_dereq_,module,exports){
819'use strict';
820
821var DiffMatchPatch = _dereq_('googlediff');
822var dmp = new DiffMatchPatch();
823
824function udiff (config) {
825 return function diff (text1, text2) {
826 var patch;
827 if (config && shouldUseLineLevelDiff(text1, config)) {
828 patch = udiffLines(text1, text2);
829 } else {
830 patch = udiffChars(text1, text2);
831 }
832 return decodeURIComponent(patch);
833 };
834}
835
836function shouldUseLineLevelDiff (text, config) {
837 return config.lineDiffThreshold < text.split(/\r\n|\r|\n/).length;
838}
839
840function udiffLines(text1, text2) {
841 /*jshint camelcase: false */
842 var a = dmp.diff_linesToChars_(text1, text2);
843 var diffs = dmp.diff_main(a.chars1, a.chars2, false);
844 dmp.diff_charsToLines_(diffs, a.lineArray);
845 dmp.diff_cleanupSemantic(diffs);
846 return dmp.patch_toText(dmp.patch_make(text1, diffs));
847}
848
849function udiffChars (text1, text2) {
850 /*jshint camelcase: false */
851 var diffs = dmp.diff_main(text1, text2, false);
852 dmp.diff_cleanupSemantic(diffs);
853 return dmp.patch_toText(dmp.patch_make(text1, diffs));
854}
855
856module.exports = udiff;
857
858},{"googlediff":25}],14:[function(_dereq_,module,exports){
859var NotAsync = {} ;
860var asyncExit = /^async[\t ]+(return|throw)/ ;
861var asyncFunction = /^async[\t ]+function/ ;
862var atomOrPropertyOrLabel = /^\s*[:;]/ ;
863var asyncAtEndOfLine = /^async[\t ]*\n/ ;
864
865/* Return the object holding the parser's 'State'. This is different between acorn ('this')
866 * and babylon ('this.state') */
867function state(p) {
868 if (('state' in p) && p.state.constructor && p.state.constructor.name==='State')
869 return p.state ; // Probably babylon
870 return p ; // Probably acorn
871}
872
873/* Create a new parser derived from the specified parser, so that in the
874 * event of an error we can back out and try again */
875function subParse(parser, pos, extensions) {
876 // NB: The Babylon constructor does NOT expect 'pos' as an argument, and so
877 // the input needs truncation at the start position, however at present
878 // this doesn't work nicely as all the node location/start/end values
879 // are therefore offset. Consequently, this plug-in is NOT currently working
880 // with the (undocumented) Babylon plug-in interface.
881 var p = new parser.constructor(parser.options, parser.input, pos);
882 if (extensions)
883 for (var k in extensions)
884 p[k] = extensions[k] ;
885
886 var src = state(parser) ;
887 var dest = state(p) ;
888 ['inFunction','inAsyncFunction','inAsync','inGenerator','inModule'].forEach(function(k){
889 if (k in src)
890 dest[k] = src[k] ;
891 }) ;
892 p.nextToken();
893 return p;
894}
895
896function asyncAwaitPlugin (parser,options){
897 var es7check = function(){} ;
898
899 parser.extend("initialContext",function(base){
900 return function(){
901 if (this.options.ecmaVersion < 7) {
902 es7check = function(node) {
903 parser.raise(node.start,"async/await keywords only available when ecmaVersion>=7") ;
904 } ;
905 }
906 this.reservedWords = new RegExp(this.reservedWords.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
907 this.reservedWordsStrict = new RegExp(this.reservedWordsStrict.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
908 this.reservedWordsStrictBind = new RegExp(this.reservedWordsStrictBind.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")) ;
909 return base.apply(this,arguments);
910 }
911 }) ;
912
913 parser.extend("parseStatement",function(base){
914 return function (declaration, topLevel) {
915 var st = state(this) ;
916 var start = st.start;
917 var startLoc = st.startLoc;
918 if (st.type.label==='name') {
919 if (asyncFunction.test(st.input.slice(st.start))) {
920 var wasAsync = st.inAsyncFunction ;
921 try {
922 st.inAsyncFunction = true ;
923 this.next() ;
924 var r = this.parseStatement(declaration, topLevel) ;
925 r.async = true ;
926 r.start = start;
927 r.loc && (r.loc.start = startLoc);
928 return r ;
929 } finally {
930 st.inAsyncFunction = wasAsync ;
931 }
932 } else if ((typeof options==="object" && options.asyncExits) && asyncExit.test(st.input.slice(st.start))) {
933 // NON-STANDARD EXTENSION iff. options.asyncExits is set, the
934 // extensions 'async return <expr>?' and 'async throw <expr>?'
935 // are enabled. In each case they are the standard ESTree nodes
936 // with the flag 'async:true'
937 this.next() ;
938 var r = this.parseStatement(declaration, topLevel) ;
939 r.async = true ;
940 r.start = start;
941 r.loc && (r.loc.start = startLoc);
942 return r ;
943 }
944 }
945 return base.apply(this,arguments);
946 }
947 }) ;
948
949 parser.extend("parseExprAtom",function(base){
950 return function(refShorthandDefaultPos){
951 var st = state(this) ;
952 var start = st.start ;
953 var startLoc = st.startLoc;
954 var rhs,r = base.apply(this,arguments);
955 if (r.type==='Identifier') {
956 if (r.name==='async' && !asyncAtEndOfLine.test(st.input.slice(start))) {
957 // Is this really an async function?
958 var isAsync = st.inAsyncFunction ;
959 try {
960 st.inAsyncFunction = true ;
961 var pp = this ;
962 var inBody = false ;
963
964 var parseHooks = {
965 parseFunctionBody:function(){
966 try {
967 var wasInBody = inBody ;
968 inBody = true ;
969 return pp.parseFunctionBody.apply(this,arguments) ;
970 } finally {
971 inBody = wasInBody ;
972 }
973 },
974 raise:function(){
975 try {
976 return pp.raise.apply(this,arguments) ;
977 } catch(ex) {
978 throw inBody?ex:NotAsync ;
979 }
980 }
981 } ;
982
983 rhs = subParse(this,st.start,parseHooks).parseExpression() ;
984 if (rhs.type==='SequenceExpression')
985 rhs = rhs.expressions[0] ;
986 if (rhs.type==='FunctionExpression' || rhs.type==='FunctionDeclaration' || rhs.type==='ArrowFunctionExpression') {
987 rhs.async = true ;
988 rhs.start = start;
989 rhs.loc && (rhs.loc.start = startLoc);
990 st.pos = rhs.end;
991 this.next();
992 es7check(rhs) ;
993 return rhs ;
994 }
995 } catch (ex) {
996 if (ex!==NotAsync)
997 throw ex ;
998 }
999 finally {
1000 st.inAsyncFunction = isAsync ;
1001 }
1002 }
1003 else if (r.name==='await') {
1004 var n = this.startNodeAt(r.start, r.loc && r.loc.start);
1005 if (st.inAsyncFunction) {
1006 rhs = this.parseExprSubscripts() ;
1007 n.operator = 'await' ;
1008 n.argument = rhs ;
1009 n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
1010 es7check(n) ;
1011 return n ;
1012 } else
1013 // NON-STANDARD EXTENSION iff. options.awaitAnywhere is true,
1014 // an 'AwaitExpression' is allowed anywhere the token 'await'
1015 // could not be an identifier with the name 'await'.
1016
1017 // Look-ahead to see if this is really a property or label called async or await
1018 if (st.input.slice(r.end).match(atomOrPropertyOrLabel))
1019 return r ; // This is a valid property name or label
1020
1021 if (typeof options==="object" && options.awaitAnywhere) {
1022 start = st.start ;
1023 rhs = subParse(this,start-4).parseExprSubscripts() ;
1024 if (rhs.end<=start) {
1025 rhs = subParse(this,start).parseExprSubscripts() ;
1026 n.operator = 'await' ;
1027 n.argument = rhs ;
1028 n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
1029 st.pos = rhs.end;
1030 this.next();
1031 es7check(n) ;
1032 return n ;
1033 }
1034 }
1035 }
1036 }
1037 return r ;
1038 }
1039 }) ;
1040
1041 parser.extend('finishNodeAt',function(base){
1042 return function(node,type,pos,loc) {
1043 if (node.__asyncValue) {
1044 delete node.__asyncValue ;
1045 node.value.async = true ;
1046 }
1047 return base.apply(this,arguments) ;
1048 }
1049 }) ;
1050
1051 parser.extend('finishNode',function(base){
1052 return function(node,type) {
1053 if (node.__asyncValue) {
1054 delete node.__asyncValue ;
1055 node.value.async = true ;
1056 }
1057 return base.apply(this,arguments) ;
1058 }
1059 }) ;
1060
1061 parser.extend("parsePropertyName",function(base){
1062 return function (prop) {
1063 var st = state(this) ;
1064 var key = base.apply(this,arguments) ;
1065 if (key.type === "Identifier" && key.name === "async") {
1066 // Look-ahead to see if this is really a property or label called async or await
1067 if (!st.input.slice(key.end).match(atomOrPropertyOrLabel)){
1068 es7check(prop) ;
1069 key = base.apply(this,arguments) ;
1070 if (key.type==='Identifier') {
1071 if (key.name==='constructor')
1072 this.raise(key.start,"'constructor()' cannot be be async") ;
1073 else if (key.name==='set')
1074 this.raise(key.start,"'set <member>(value)' cannot be be async") ;
1075 }
1076 prop.__asyncValue = true ;
1077 }
1078 }
1079 return key;
1080 };
1081 }) ;
1082}
1083
1084module.exports = function(acorn) {
1085 acorn.plugins.asyncawait = asyncAwaitPlugin ;
1086}
1087
1088},{}],15:[function(_dereq_,module,exports){
1089(function (global){
1090(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.acorn = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
1091// A recursive descent parser operates by defining functions for all
1092// syntactic elements, and recursively calling those, each function
1093// advancing the input stream and returning an AST node. Precedence
1094// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
1095// instead of `(!x)[1]` is handled by the fact that the parser
1096// function that parses unary prefix operators is called first, and
1097// in turn calls the function that parses `[]` subscripts — that
1098// way, it'll receive the node for `x[1]` already parsed, and wraps
1099// *that* in the unary operator node.
1100//
1101// Acorn uses an [operator precedence parser][opp] to handle binary
1102// operator precedence, because it is much more compact than using
1103// the technique outlined above, which uses different, nesting
1104// functions to specify precedence, for all of the ten binary
1105// precedence levels that JavaScript defines.
1106//
1107// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
1108
1109"use strict";
1110
1111var _tokentype = _dereq_("./tokentype");
1112
1113var _state = _dereq_("./state");
1114
1115var pp = _state.Parser.prototype;
1116
1117// Check if property name clashes with already added.
1118// Object/class getters and setters are not allowed to clash —
1119// either with each other or with an init property — and in
1120// strict mode, init properties are also not allowed to be repeated.
1121
1122pp.checkPropClash = function (prop, propHash) {
1123 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
1124 var key = prop.key;var name = undefined;
1125 switch (key.type) {
1126 case "Identifier":
1127 name = key.name;break;
1128 case "Literal":
1129 name = String(key.value);break;
1130 default:
1131 return;
1132 }
1133 var kind = prop.kind;
1134
1135 if (this.options.ecmaVersion >= 6) {
1136 if (name === "__proto__" && kind === "init") {
1137 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
1138 propHash.proto = true;
1139 }
1140 return;
1141 }
1142 name = "$" + name;
1143 var other = propHash[name];
1144 if (other) {
1145 var isGetSet = kind !== "init";
1146 if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
1147 } else {
1148 other = propHash[name] = {
1149 init: false,
1150 get: false,
1151 set: false
1152 };
1153 }
1154 other[kind] = true;
1155};
1156
1157// ### Expression parsing
1158
1159// These nest, from the most general expression type at the top to
1160// 'atomic', nondivisible expression types at the bottom. Most of
1161// the functions will simply let the function(s) below them parse,
1162// and, *if* the syntactic construct they handle is present, wrap
1163// the AST node that the inner parser gave them in another node.
1164
1165// Parse a full expression. The optional arguments are used to
1166// forbid the `in` operator (in for loops initalization expressions)
1167// and provide reference for storing '=' operator inside shorthand
1168// property assignment in contexts where both object expression
1169// and object pattern might appear (so it's possible to raise
1170// delayed syntax error at correct position).
1171
1172pp.parseExpression = function (noIn, refDestructuringErrors) {
1173 var startPos = this.start,
1174 startLoc = this.startLoc;
1175 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
1176 if (this.type === _tokentype.types.comma) {
1177 var node = this.startNodeAt(startPos, startLoc);
1178 node.expressions = [expr];
1179 while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
1180 return this.finishNode(node, "SequenceExpression");
1181 }
1182 return expr;
1183};
1184
1185// Parse an assignment expression. This includes applications of
1186// operators like `+=`.
1187
1188pp.parseMaybeAssign = function (noIn, refDestructuringErrors, afterLeftParse) {
1189 if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield();
1190
1191 var validateDestructuring = false;
1192 if (!refDestructuringErrors) {
1193 refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
1194 validateDestructuring = true;
1195 }
1196 var startPos = this.start,
1197 startLoc = this.startLoc;
1198 if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start;
1199 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
1200 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
1201 if (this.type.isAssign) {
1202 if (validateDestructuring) this.checkPatternErrors(refDestructuringErrors, true);
1203 var node = this.startNodeAt(startPos, startLoc);
1204 node.operator = this.value;
1205 node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left;
1206 refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly
1207 this.checkLVal(left);
1208 this.next();
1209 node.right = this.parseMaybeAssign(noIn);
1210 return this.finishNode(node, "AssignmentExpression");
1211 } else {
1212 if (validateDestructuring) this.checkExpressionErrors(refDestructuringErrors, true);
1213 }
1214 return left;
1215};
1216
1217// Parse a ternary conditional (`?:`) operator.
1218
1219pp.parseMaybeConditional = function (noIn, refDestructuringErrors) {
1220 var startPos = this.start,
1221 startLoc = this.startLoc;
1222 var expr = this.parseExprOps(noIn, refDestructuringErrors);
1223 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
1224 if (this.eat(_tokentype.types.question)) {
1225 var node = this.startNodeAt(startPos, startLoc);
1226 node.test = expr;
1227 node.consequent = this.parseMaybeAssign();
1228 this.expect(_tokentype.types.colon);
1229 node.alternate = this.parseMaybeAssign(noIn);
1230 return this.finishNode(node, "ConditionalExpression");
1231 }
1232 return expr;
1233};
1234
1235// Start the precedence parser.
1236
1237pp.parseExprOps = function (noIn, refDestructuringErrors) {
1238 var startPos = this.start,
1239 startLoc = this.startLoc;
1240 var expr = this.parseMaybeUnary(refDestructuringErrors);
1241 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
1242 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
1243};
1244
1245// Parse binary operators with the operator precedence parsing
1246// algorithm. `left` is the left-hand side of the operator.
1247// `minPrec` provides context that allows the function to stop and
1248// defer further parser to one of its callers when it encounters an
1249// operator that has a lower precedence than the set it is parsing.
1250
1251pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
1252 var prec = this.type.binop;
1253 if (prec != null && (!noIn || this.type !== _tokentype.types._in)) {
1254 if (prec > minPrec) {
1255 var node = this.startNodeAt(leftStartPos, leftStartLoc);
1256 node.left = left;
1257 node.operator = this.value;
1258 var op = this.type;
1259 this.next();
1260 var startPos = this.start,
1261 startLoc = this.startLoc;
1262 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
1263 this.finishNode(node, op === _tokentype.types.logicalOR || op === _tokentype.types.logicalAND ? "LogicalExpression" : "BinaryExpression");
1264 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
1265 }
1266 }
1267 return left;
1268};
1269
1270// Parse unary operators, both prefix and postfix.
1271
1272pp.parseMaybeUnary = function (refDestructuringErrors) {
1273 if (this.type.prefix) {
1274 var node = this.startNode(),
1275 update = this.type === _tokentype.types.incDec;
1276 node.operator = this.value;
1277 node.prefix = true;
1278 this.next();
1279 node.argument = this.parseMaybeUnary();
1280 this.checkExpressionErrors(refDestructuringErrors, true);
1281 if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode");
1282 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
1283 }
1284 var startPos = this.start,
1285 startLoc = this.startLoc;
1286 var expr = this.parseExprSubscripts(refDestructuringErrors);
1287 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
1288 while (this.type.postfix && !this.canInsertSemicolon()) {
1289 var node = this.startNodeAt(startPos, startLoc);
1290 node.operator = this.value;
1291 node.prefix = false;
1292 node.argument = expr;
1293 this.checkLVal(expr);
1294 this.next();
1295 expr = this.finishNode(node, "UpdateExpression");
1296 }
1297 return expr;
1298};
1299
1300// Parse call, dot, and `[]`-subscript expressions.
1301
1302pp.parseExprSubscripts = function (refDestructuringErrors) {
1303 var startPos = this.start,
1304 startLoc = this.startLoc;
1305 var expr = this.parseExprAtom(refDestructuringErrors);
1306 var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
1307 if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr;
1308 return this.parseSubscripts(expr, startPos, startLoc);
1309};
1310
1311pp.parseSubscripts = function (base, startPos, startLoc, noCalls) {
1312 for (;;) {
1313 if (this.eat(_tokentype.types.dot)) {
1314 var node = this.startNodeAt(startPos, startLoc);
1315 node.object = base;
1316 node.property = this.parseIdent(true);
1317 node.computed = false;
1318 base = this.finishNode(node, "MemberExpression");
1319 } else if (this.eat(_tokentype.types.bracketL)) {
1320 var node = this.startNodeAt(startPos, startLoc);
1321 node.object = base;
1322 node.property = this.parseExpression();
1323 node.computed = true;
1324 this.expect(_tokentype.types.bracketR);
1325 base = this.finishNode(node, "MemberExpression");
1326 } else if (!noCalls && this.eat(_tokentype.types.parenL)) {
1327 var node = this.startNodeAt(startPos, startLoc);
1328 node.callee = base;
1329 node.arguments = this.parseExprList(_tokentype.types.parenR, false);
1330 base = this.finishNode(node, "CallExpression");
1331 } else if (this.type === _tokentype.types.backQuote) {
1332 var node = this.startNodeAt(startPos, startLoc);
1333 node.tag = base;
1334 node.quasi = this.parseTemplate();
1335 base = this.finishNode(node, "TaggedTemplateExpression");
1336 } else {
1337 return base;
1338 }
1339 }
1340};
1341
1342// Parse an atomic expression — either a single token that is an
1343// expression, an expression started by a keyword like `function` or
1344// `new`, or an expression wrapped in punctuation like `()`, `[]`,
1345// or `{}`.
1346
1347pp.parseExprAtom = function (refDestructuringErrors) {
1348 var node = undefined,
1349 canBeArrow = this.potentialArrowAt == this.start;
1350 switch (this.type) {
1351 case _tokentype.types._super:
1352 if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
1353 case _tokentype.types._this:
1354 var type = this.type === _tokentype.types._this ? "ThisExpression" : "Super";
1355 node = this.startNode();
1356 this.next();
1357 return this.finishNode(node, type);
1358
1359 case _tokentype.types._yield:
1360 if (this.inGenerator) this.unexpected();
1361
1362 case _tokentype.types.name:
1363 var startPos = this.start,
1364 startLoc = this.startLoc;
1365 var id = this.parseIdent(this.type !== _tokentype.types.name);
1366 if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]);
1367 return id;
1368
1369 case _tokentype.types.regexp:
1370 var value = this.value;
1371 node = this.parseLiteral(value.value);
1372 node.regex = { pattern: value.pattern, flags: value.flags };
1373 return node;
1374
1375 case _tokentype.types.num:case _tokentype.types.string:
1376 return this.parseLiteral(this.value);
1377
1378 case _tokentype.types._null:case _tokentype.types._true:case _tokentype.types._false:
1379 node = this.startNode();
1380 node.value = this.type === _tokentype.types._null ? null : this.type === _tokentype.types._true;
1381 node.raw = this.type.keyword;
1382 this.next();
1383 return this.finishNode(node, "Literal");
1384
1385 case _tokentype.types.parenL:
1386 return this.parseParenAndDistinguishExpression(canBeArrow);
1387
1388 case _tokentype.types.bracketL:
1389 node = this.startNode();
1390 this.next();
1391 // check whether this is array comprehension or regular array
1392 if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) {
1393 return this.parseComprehension(node, false);
1394 }
1395 node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refDestructuringErrors);
1396 return this.finishNode(node, "ArrayExpression");
1397
1398 case _tokentype.types.braceL:
1399 return this.parseObj(false, refDestructuringErrors);
1400
1401 case _tokentype.types._function:
1402 node = this.startNode();
1403 this.next();
1404 return this.parseFunction(node, false);
1405
1406 case _tokentype.types._class:
1407 return this.parseClass(this.startNode(), false);
1408
1409 case _tokentype.types._new:
1410 return this.parseNew();
1411
1412 case _tokentype.types.backQuote:
1413 return this.parseTemplate();
1414
1415 default:
1416 this.unexpected();
1417 }
1418};
1419
1420pp.parseLiteral = function (value) {
1421 var node = this.startNode();
1422 node.value = value;
1423 node.raw = this.input.slice(this.start, this.end);
1424 this.next();
1425 return this.finishNode(node, "Literal");
1426};
1427
1428pp.parseParenExpression = function () {
1429 this.expect(_tokentype.types.parenL);
1430 var val = this.parseExpression();
1431 this.expect(_tokentype.types.parenR);
1432 return val;
1433};
1434
1435pp.parseParenAndDistinguishExpression = function (canBeArrow) {
1436 var startPos = this.start,
1437 startLoc = this.startLoc,
1438 val = undefined;
1439 if (this.options.ecmaVersion >= 6) {
1440 this.next();
1441
1442 if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) {
1443 return this.parseComprehension(this.startNodeAt(startPos, startLoc), true);
1444 }
1445
1446 var innerStartPos = this.start,
1447 innerStartLoc = this.startLoc;
1448 var exprList = [],
1449 first = true;
1450 var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 },
1451 spreadStart = undefined,
1452 innerParenStart = undefined;
1453 while (this.type !== _tokentype.types.parenR) {
1454 first ? first = false : this.expect(_tokentype.types.comma);
1455 if (this.type === _tokentype.types.ellipsis) {
1456 spreadStart = this.start;
1457 exprList.push(this.parseParenItem(this.parseRest()));
1458 break;
1459 } else {
1460 if (this.type === _tokentype.types.parenL && !innerParenStart) {
1461 innerParenStart = this.start;
1462 }
1463 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
1464 }
1465 }
1466 var innerEndPos = this.start,
1467 innerEndLoc = this.startLoc;
1468 this.expect(_tokentype.types.parenR);
1469
1470 if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) {
1471 this.checkPatternErrors(refDestructuringErrors, true);
1472 if (innerParenStart) this.unexpected(innerParenStart);
1473 return this.parseParenArrowList(startPos, startLoc, exprList);
1474 }
1475
1476 if (!exprList.length) this.unexpected(this.lastTokStart);
1477 if (spreadStart) this.unexpected(spreadStart);
1478 this.checkExpressionErrors(refDestructuringErrors, true);
1479
1480 if (exprList.length > 1) {
1481 val = this.startNodeAt(innerStartPos, innerStartLoc);
1482 val.expressions = exprList;
1483 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
1484 } else {
1485 val = exprList[0];
1486 }
1487 } else {
1488 val = this.parseParenExpression();
1489 }
1490
1491 if (this.options.preserveParens) {
1492 var par = this.startNodeAt(startPos, startLoc);
1493 par.expression = val;
1494 return this.finishNode(par, "ParenthesizedExpression");
1495 } else {
1496 return val;
1497 }
1498};
1499
1500pp.parseParenItem = function (item) {
1501 return item;
1502};
1503
1504pp.parseParenArrowList = function (startPos, startLoc, exprList) {
1505 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
1506};
1507
1508// New's precedence is slightly tricky. It must allow its argument
1509// to be a `[]` or dot subscript expression, but not a call — at
1510// least, not without wrapping it in parentheses. Thus, it uses the
1511
1512var empty = [];
1513
1514pp.parseNew = function () {
1515 var node = this.startNode();
1516 var meta = this.parseIdent(true);
1517 if (this.options.ecmaVersion >= 6 && this.eat(_tokentype.types.dot)) {
1518 node.meta = meta;
1519 node.property = this.parseIdent(true);
1520 if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
1521 if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions");
1522 return this.finishNode(node, "MetaProperty");
1523 }
1524 var startPos = this.start,
1525 startLoc = this.startLoc;
1526 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
1527 if (this.eat(_tokentype.types.parenL)) node.arguments = this.parseExprList(_tokentype.types.parenR, false);else node.arguments = empty;
1528 return this.finishNode(node, "NewExpression");
1529};
1530
1531// Parse template expression.
1532
1533pp.parseTemplateElement = function () {
1534 var elem = this.startNode();
1535 elem.value = {
1536 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
1537 cooked: this.value
1538 };
1539 this.next();
1540 elem.tail = this.type === _tokentype.types.backQuote;
1541 return this.finishNode(elem, "TemplateElement");
1542};
1543
1544pp.parseTemplate = function () {
1545 var node = this.startNode();
1546 this.next();
1547 node.expressions = [];
1548 var curElt = this.parseTemplateElement();
1549 node.quasis = [curElt];
1550 while (!curElt.tail) {
1551 this.expect(_tokentype.types.dollarBraceL);
1552 node.expressions.push(this.parseExpression());
1553 this.expect(_tokentype.types.braceR);
1554 node.quasis.push(curElt = this.parseTemplateElement());
1555 }
1556 this.next();
1557 return this.finishNode(node, "TemplateLiteral");
1558};
1559
1560// Parse an object literal or binding pattern.
1561
1562pp.parseObj = function (isPattern, refDestructuringErrors) {
1563 var node = this.startNode(),
1564 first = true,
1565 propHash = {};
1566 node.properties = [];
1567 this.next();
1568 while (!this.eat(_tokentype.types.braceR)) {
1569 if (!first) {
1570 this.expect(_tokentype.types.comma);
1571 if (this.afterTrailingComma(_tokentype.types.braceR)) break;
1572 } else first = false;
1573
1574 var prop = this.startNode(),
1575 isGenerator = undefined,
1576 startPos = undefined,
1577 startLoc = undefined;
1578 if (this.options.ecmaVersion >= 6) {
1579 prop.method = false;
1580 prop.shorthand = false;
1581 if (isPattern || refDestructuringErrors) {
1582 startPos = this.start;
1583 startLoc = this.startLoc;
1584 }
1585 if (!isPattern) isGenerator = this.eat(_tokentype.types.star);
1586 }
1587 this.parsePropertyName(prop);
1588 this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors);
1589 this.checkPropClash(prop, propHash);
1590 node.properties.push(this.finishNode(prop, "Property"));
1591 }
1592 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
1593};
1594
1595pp.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) {
1596 if (this.eat(_tokentype.types.colon)) {
1597 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
1598 prop.kind = "init";
1599 } else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) {
1600 if (isPattern) this.unexpected();
1601 prop.kind = "init";
1602 prop.method = true;
1603 prop.value = this.parseMethod(isGenerator);
1604 } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type != _tokentype.types.comma && this.type != _tokentype.types.braceR)) {
1605 if (isGenerator || isPattern) this.unexpected();
1606 prop.kind = prop.key.name;
1607 this.parsePropertyName(prop);
1608 prop.value = this.parseMethod(false);
1609 var paramCount = prop.kind === "get" ? 0 : 1;
1610 if (prop.value.params.length !== paramCount) {
1611 var start = prop.value.start;
1612 if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
1613 }
1614 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
1615 prop.kind = "init";
1616 if (isPattern) {
1617 if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
1618 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
1619 } else if (this.type === _tokentype.types.eq && refDestructuringErrors) {
1620 if (!refDestructuringErrors.shorthandAssign) refDestructuringErrors.shorthandAssign = this.start;
1621 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
1622 } else {
1623 prop.value = prop.key;
1624 }
1625 prop.shorthand = true;
1626 } else this.unexpected();
1627};
1628
1629pp.parsePropertyName = function (prop) {
1630 if (this.options.ecmaVersion >= 6) {
1631 if (this.eat(_tokentype.types.bracketL)) {
1632 prop.computed = true;
1633 prop.key = this.parseMaybeAssign();
1634 this.expect(_tokentype.types.bracketR);
1635 return prop.key;
1636 } else {
1637 prop.computed = false;
1638 }
1639 }
1640 return prop.key = this.type === _tokentype.types.num || this.type === _tokentype.types.string ? this.parseExprAtom() : this.parseIdent(true);
1641};
1642
1643// Initialize empty function node.
1644
1645pp.initFunction = function (node) {
1646 node.id = null;
1647 if (this.options.ecmaVersion >= 6) {
1648 node.generator = false;
1649 node.expression = false;
1650 }
1651};
1652
1653// Parse object or class method.
1654
1655pp.parseMethod = function (isGenerator) {
1656 var node = this.startNode();
1657 this.initFunction(node);
1658 this.expect(_tokentype.types.parenL);
1659 node.params = this.parseBindingList(_tokentype.types.parenR, false, false);
1660 if (this.options.ecmaVersion >= 6) node.generator = isGenerator;
1661 this.parseFunctionBody(node, false);
1662 return this.finishNode(node, "FunctionExpression");
1663};
1664
1665// Parse arrow function expression with given parameters.
1666
1667pp.parseArrowExpression = function (node, params) {
1668 this.initFunction(node);
1669 node.params = this.toAssignableList(params, true);
1670 this.parseFunctionBody(node, true);
1671 return this.finishNode(node, "ArrowFunctionExpression");
1672};
1673
1674// Parse function body and check parameters.
1675
1676pp.parseFunctionBody = function (node, isArrowFunction) {
1677 var isExpression = isArrowFunction && this.type !== _tokentype.types.braceL;
1678
1679 if (isExpression) {
1680 node.body = this.parseMaybeAssign();
1681 node.expression = true;
1682 } else {
1683 // Start a new scope with regard to labels and the `inFunction`
1684 // flag (restore them to their old value afterwards).
1685 var oldInFunc = this.inFunction,
1686 oldInGen = this.inGenerator,
1687 oldLabels = this.labels;
1688 this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
1689 node.body = this.parseBlock(true);
1690 node.expression = false;
1691 this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
1692 }
1693
1694 // If this is a strict mode function, verify that argument names
1695 // are not repeated, and it does not try to bind the words `eval`
1696 // or `arguments`.
1697 if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
1698 var oldStrict = this.strict;
1699 this.strict = true;
1700 if (node.id) this.checkLVal(node.id, true);
1701 this.checkParams(node);
1702 this.strict = oldStrict;
1703 } else if (isArrowFunction) {
1704 this.checkParams(node);
1705 }
1706};
1707
1708// Checks function params for various disallowed patterns such as using "eval"
1709// or "arguments" and duplicate parameters.
1710
1711pp.checkParams = function (node) {
1712 var nameHash = {};
1713 for (var i = 0; i < node.params.length; i++) {
1714 this.checkLVal(node.params[i], true, nameHash);
1715 }
1716};
1717
1718// Parses a comma-separated list of expressions, and returns them as
1719// an array. `close` is the token type that ends the list, and
1720// `allowEmpty` can be turned on to allow subsequent commas with
1721// nothing in between them to be parsed as `null` (which is needed
1722// for array literals).
1723
1724pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
1725 var elts = [],
1726 first = true;
1727 while (!this.eat(close)) {
1728 if (!first) {
1729 this.expect(_tokentype.types.comma);
1730 if (this.type === close && refDestructuringErrors && !refDestructuringErrors.trailingComma) {
1731 refDestructuringErrors.trailingComma = this.lastTokStart;
1732 }
1733 if (allowTrailingComma && this.afterTrailingComma(close)) break;
1734 } else first = false;
1735
1736 var elt = undefined;
1737 if (allowEmpty && this.type === _tokentype.types.comma) elt = null;else if (this.type === _tokentype.types.ellipsis) elt = this.parseSpread(refDestructuringErrors);else elt = this.parseMaybeAssign(false, refDestructuringErrors);
1738 elts.push(elt);
1739 }
1740 return elts;
1741};
1742
1743// Parse the next token as an identifier. If `liberal` is true (used
1744// when parsing properties), it will also convert keywords into
1745// identifiers.
1746
1747pp.parseIdent = function (liberal) {
1748 var node = this.startNode();
1749 if (liberal && this.options.allowReserved == "never") liberal = false;
1750 if (this.type === _tokentype.types.name) {
1751 if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
1752 node.name = this.value;
1753 } else if (liberal && this.type.keyword) {
1754 node.name = this.type.keyword;
1755 } else {
1756 this.unexpected();
1757 }
1758 this.next();
1759 return this.finishNode(node, "Identifier");
1760};
1761
1762// Parses yield expression inside generator.
1763
1764pp.parseYield = function () {
1765 var node = this.startNode();
1766 this.next();
1767 if (this.type == _tokentype.types.semi || this.canInsertSemicolon() || this.type != _tokentype.types.star && !this.type.startsExpr) {
1768 node.delegate = false;
1769 node.argument = null;
1770 } else {
1771 node.delegate = this.eat(_tokentype.types.star);
1772 node.argument = this.parseMaybeAssign();
1773 }
1774 return this.finishNode(node, "YieldExpression");
1775};
1776
1777// Parses array and generator comprehensions.
1778
1779pp.parseComprehension = function (node, isGenerator) {
1780 node.blocks = [];
1781 while (this.type === _tokentype.types._for) {
1782 var block = this.startNode();
1783 this.next();
1784 this.expect(_tokentype.types.parenL);
1785 block.left = this.parseBindingAtom();
1786 this.checkLVal(block.left, true);
1787 this.expectContextual("of");
1788 block.right = this.parseExpression();
1789 this.expect(_tokentype.types.parenR);
1790 node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
1791 }
1792 node.filter = this.eat(_tokentype.types._if) ? this.parseParenExpression() : null;
1793 node.body = this.parseExpression();
1794 this.expect(isGenerator ? _tokentype.types.parenR : _tokentype.types.bracketR);
1795 node.generator = isGenerator;
1796 return this.finishNode(node, "ComprehensionExpression");
1797};
1798
1799},{"./state":10,"./tokentype":14}],2:[function(_dereq_,module,exports){
1800// This is a trick taken from Esprima. It turns out that, on
1801// non-Chrome browsers, to check whether a string is in a set, a
1802// predicate containing a big ugly `switch` statement is faster than
1803// a regular expression, and on Chrome the two are about on par.
1804// This function uses `eval` (non-lexical) to produce such a
1805// predicate from a space-separated string of words.
1806//
1807// It starts by sorting the words by length.
1808
1809// Reserved word lists for various dialects of the language
1810
1811"use strict";
1812
1813exports.__esModule = true;
1814exports.isIdentifierStart = isIdentifierStart;
1815exports.isIdentifierChar = isIdentifierChar;
1816var reservedWords = {
1817 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1818 5: "class enum extends super const export import",
1819 6: "enum",
1820 strict: "implements interface let package private protected public static yield",
1821 strictBind: "eval arguments"
1822};
1823
1824exports.reservedWords = reservedWords;
1825// And the keywords
1826
1827var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1828
1829var keywords = {
1830 5: ecma5AndLessKeywords,
1831 6: ecma5AndLessKeywords + " let const class extends export import yield super"
1832};
1833
1834exports.keywords = keywords;
1835// ## Character categories
1836
1837// Big ugly regular expressions that match characters in the
1838// whitespace, identifier, and identifier-start categories. These
1839// are only applied when a character is found to actually have a
1840// code point above 128.
1841// Generated by `bin/generate-identifier-regex.js`.
1842
1843var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";
1844var nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";
1845
1846var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1847var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1848
1849nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1850
1851// These are a run-length and offset encoded representation of the
1852// >0xffff code points that are a valid part of identifiers. The
1853// offset starts at 0x10000, and each pair of numbers represents an
1854// offset to the next range, and then a size of the range. They were
1855// generated by tools/generate-identifier-regex.js
1856var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 99, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 98, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 1340, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 16355, 541];
1857var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 4305, 6, 792618, 239];
1858
1859// This has a complexity linear to the value of the code. The
1860// assumption is that looking up astral identifier characters is
1861// rare.
1862function isInAstralSet(code, set) {
1863 var pos = 0x10000;
1864 for (var i = 0; i < set.length; i += 2) {
1865 pos += set[i];
1866 if (pos > code) return false;
1867 pos += set[i + 1];
1868 if (pos >= code) return true;
1869 }
1870}
1871
1872// Test whether a given character code starts an identifier.
1873
1874function isIdentifierStart(code, astral) {
1875 if (code < 65) return code === 36;
1876 if (code < 91) return true;
1877 if (code < 97) return code === 95;
1878 if (code < 123) return true;
1879 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
1880 if (astral === false) return false;
1881 return isInAstralSet(code, astralIdentifierStartCodes);
1882}
1883
1884// Test whether a given character is part of an identifier.
1885
1886function isIdentifierChar(code, astral) {
1887 if (code < 48) return code === 36;
1888 if (code < 58) return true;
1889 if (code < 65) return false;
1890 if (code < 91) return true;
1891 if (code < 97) return code === 95;
1892 if (code < 123) return true;
1893 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
1894 if (astral === false) return false;
1895 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1896}
1897
1898},{}],3:[function(_dereq_,module,exports){
1899// Acorn is a tiny, fast JavaScript parser written in JavaScript.
1900//
1901// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
1902// various contributors and released under an MIT license.
1903//
1904// Git repositories for Acorn are available at
1905//
1906// http://marijnhaverbeke.nl/git/acorn
1907// https://github.com/ternjs/acorn.git
1908//
1909// Please use the [github bug tracker][ghbt] to report issues.
1910//
1911// [ghbt]: https://github.com/ternjs/acorn/issues
1912//
1913// This file defines the main parser interface. The library also comes
1914// with a [error-tolerant parser][dammit] and an
1915// [abstract syntax tree walker][walk], defined in other files.
1916//
1917// [dammit]: acorn_loose.js
1918// [walk]: util/walk.js
1919
1920"use strict";
1921
1922exports.__esModule = true;
1923exports.parse = parse;
1924exports.parseExpressionAt = parseExpressionAt;
1925exports.tokenizer = tokenizer;
1926
1927var _state = _dereq_("./state");
1928
1929_dereq_("./parseutil");
1930
1931_dereq_("./statement");
1932
1933_dereq_("./lval");
1934
1935_dereq_("./expression");
1936
1937_dereq_("./location");
1938
1939exports.Parser = _state.Parser;
1940exports.plugins = _state.plugins;
1941
1942var _options = _dereq_("./options");
1943
1944exports.defaultOptions = _options.defaultOptions;
1945
1946var _locutil = _dereq_("./locutil");
1947
1948exports.Position = _locutil.Position;
1949exports.SourceLocation = _locutil.SourceLocation;
1950exports.getLineInfo = _locutil.getLineInfo;
1951
1952var _node = _dereq_("./node");
1953
1954exports.Node = _node.Node;
1955
1956var _tokentype = _dereq_("./tokentype");
1957
1958exports.TokenType = _tokentype.TokenType;
1959exports.tokTypes = _tokentype.types;
1960
1961var _tokencontext = _dereq_("./tokencontext");
1962
1963exports.TokContext = _tokencontext.TokContext;
1964exports.tokContexts = _tokencontext.types;
1965
1966var _identifier = _dereq_("./identifier");
1967
1968exports.isIdentifierChar = _identifier.isIdentifierChar;
1969exports.isIdentifierStart = _identifier.isIdentifierStart;
1970
1971var _tokenize = _dereq_("./tokenize");
1972
1973exports.Token = _tokenize.Token;
1974
1975var _whitespace = _dereq_("./whitespace");
1976
1977exports.isNewLine = _whitespace.isNewLine;
1978exports.lineBreak = _whitespace.lineBreak;
1979exports.lineBreakG = _whitespace.lineBreakG;
1980var version = "2.6.4";
1981
1982exports.version = version;
1983// The main exported interface (under `self.acorn` when in the
1984// browser) is a `parse` function that takes a code string and
1985// returns an abstract syntax tree as specified by [Mozilla parser
1986// API][api].
1987//
1988// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
1989
1990function parse(input, options) {
1991 return new _state.Parser(options, input).parse();
1992}
1993
1994// This function tries to parse a single expression at a given
1995// offset in a string. Useful for parsing mixed-language formats
1996// that embed JavaScript expressions.
1997
1998function parseExpressionAt(input, pos, options) {
1999 var p = new _state.Parser(options, input, pos);
2000 p.nextToken();
2001 return p.parseExpression();
2002}
2003
2004// Acorn is organized as a tokenizer and a recursive-descent parser.
2005// The `tokenizer` export provides an interface to the tokenizer.
2006
2007function tokenizer(input, options) {
2008 return new _state.Parser(options, input);
2009}
2010
2011},{"./expression":1,"./identifier":2,"./location":4,"./locutil":5,"./lval":6,"./node":7,"./options":8,"./parseutil":9,"./state":10,"./statement":11,"./tokencontext":12,"./tokenize":13,"./tokentype":14,"./whitespace":16}],4:[function(_dereq_,module,exports){
2012"use strict";
2013
2014var _state = _dereq_("./state");
2015
2016var _locutil = _dereq_("./locutil");
2017
2018var pp = _state.Parser.prototype;
2019
2020// This function is used to raise exceptions on parse errors. It
2021// takes an offset integer (into the current `input`) to indicate
2022// the location of the error, attaches the position to the end
2023// of the error message, and then raises a `SyntaxError` with that
2024// message.
2025
2026pp.raise = function (pos, message) {
2027 var loc = _locutil.getLineInfo(this.input, pos);
2028 message += " (" + loc.line + ":" + loc.column + ")";
2029 var err = new SyntaxError(message);
2030 err.pos = pos;err.loc = loc;err.raisedAt = this.pos;
2031 throw err;
2032};
2033
2034pp.curPosition = function () {
2035 if (this.options.locations) {
2036 return new _locutil.Position(this.curLine, this.pos - this.lineStart);
2037 }
2038};
2039
2040},{"./locutil":5,"./state":10}],5:[function(_dereq_,module,exports){
2041"use strict";
2042
2043exports.__esModule = true;
2044exports.getLineInfo = getLineInfo;
2045
2046function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2047
2048var _whitespace = _dereq_("./whitespace");
2049
2050// These are used when `options.locations` is on, for the
2051// `startLoc` and `endLoc` properties.
2052
2053var Position = (function () {
2054 function Position(line, col) {
2055 _classCallCheck(this, Position);
2056
2057 this.line = line;
2058 this.column = col;
2059 }
2060
2061 Position.prototype.offset = function offset(n) {
2062 return new Position(this.line, this.column + n);
2063 };
2064
2065 return Position;
2066})();
2067
2068exports.Position = Position;
2069
2070var SourceLocation = function SourceLocation(p, start, end) {
2071 _classCallCheck(this, SourceLocation);
2072
2073 this.start = start;
2074 this.end = end;
2075 if (p.sourceFile !== null) this.source = p.sourceFile;
2076}
2077
2078// The `getLineInfo` function is mostly useful when the
2079// `locations` option is off (for performance reasons) and you
2080// want to find the line/column position for a given character
2081// offset. `input` should be the code string that the offset refers
2082// into.
2083
2084;
2085
2086exports.SourceLocation = SourceLocation;
2087
2088function getLineInfo(input, offset) {
2089 for (var line = 1, cur = 0;;) {
2090 _whitespace.lineBreakG.lastIndex = cur;
2091 var match = _whitespace.lineBreakG.exec(input);
2092 if (match && match.index < offset) {
2093 ++line;
2094 cur = match.index + match[0].length;
2095 } else {
2096 return new Position(line, offset - cur);
2097 }
2098 }
2099}
2100
2101},{"./whitespace":16}],6:[function(_dereq_,module,exports){
2102"use strict";
2103
2104var _tokentype = _dereq_("./tokentype");
2105
2106var _state = _dereq_("./state");
2107
2108var _util = _dereq_("./util");
2109
2110var pp = _state.Parser.prototype;
2111
2112// Convert existing expression atom to assignable pattern
2113// if possible.
2114
2115pp.toAssignable = function (node, isBinding) {
2116 if (this.options.ecmaVersion >= 6 && node) {
2117 switch (node.type) {
2118 case "Identifier":
2119 case "ObjectPattern":
2120 case "ArrayPattern":
2121 break;
2122
2123 case "ObjectExpression":
2124 node.type = "ObjectPattern";
2125 for (var i = 0; i < node.properties.length; i++) {
2126 var prop = node.properties[i];
2127 if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
2128 this.toAssignable(prop.value, isBinding);
2129 }
2130 break;
2131
2132 case "ArrayExpression":
2133 node.type = "ArrayPattern";
2134 this.toAssignableList(node.elements, isBinding);
2135 break;
2136
2137 case "AssignmentExpression":
2138 if (node.operator === "=") {
2139 node.type = "AssignmentPattern";
2140 delete node.operator;
2141 // falls through to AssignmentPattern
2142 } else {
2143 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
2144 break;
2145 }
2146
2147 case "AssignmentPattern":
2148 if (node.right.type === "YieldExpression") this.raise(node.right.start, "Yield expression cannot be a default value");
2149 break;
2150
2151 case "ParenthesizedExpression":
2152 node.expression = this.toAssignable(node.expression, isBinding);
2153 break;
2154
2155 case "MemberExpression":
2156 if (!isBinding) break;
2157
2158 default:
2159 this.raise(node.start, "Assigning to rvalue");
2160 }
2161 }
2162 return node;
2163};
2164
2165// Convert list of expression atoms to binding list.
2166
2167pp.toAssignableList = function (exprList, isBinding) {
2168 var end = exprList.length;
2169 if (end) {
2170 var last = exprList[end - 1];
2171 if (last && last.type == "RestElement") {
2172 --end;
2173 } else if (last && last.type == "SpreadElement") {
2174 last.type = "RestElement";
2175 var arg = last.argument;
2176 this.toAssignable(arg, isBinding);
2177 if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
2178 --end;
2179 }
2180
2181 if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start);
2182 }
2183 for (var i = 0; i < end; i++) {
2184 var elt = exprList[i];
2185 if (elt) this.toAssignable(elt, isBinding);
2186 }
2187 return exprList;
2188};
2189
2190// Parses spread element.
2191
2192pp.parseSpread = function (refDestructuringErrors) {
2193 var node = this.startNode();
2194 this.next();
2195 node.argument = this.parseMaybeAssign(refDestructuringErrors);
2196 return this.finishNode(node, "SpreadElement");
2197};
2198
2199pp.parseRest = function (allowNonIdent) {
2200 var node = this.startNode();
2201 this.next();
2202
2203 // RestElement inside of a function parameter must be an identifier
2204 if (allowNonIdent) node.argument = this.type === _tokentype.types.name ? this.parseIdent() : this.unexpected();else node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected();
2205
2206 return this.finishNode(node, "RestElement");
2207};
2208
2209// Parses lvalue (assignable) atom.
2210
2211pp.parseBindingAtom = function () {
2212 if (this.options.ecmaVersion < 6) return this.parseIdent();
2213 switch (this.type) {
2214 case _tokentype.types.name:
2215 return this.parseIdent();
2216
2217 case _tokentype.types.bracketL:
2218 var node = this.startNode();
2219 this.next();
2220 node.elements = this.parseBindingList(_tokentype.types.bracketR, true, true);
2221 return this.finishNode(node, "ArrayPattern");
2222
2223 case _tokentype.types.braceL:
2224 return this.parseObj(true);
2225
2226 default:
2227 this.unexpected();
2228 }
2229};
2230
2231pp.parseBindingList = function (close, allowEmpty, allowTrailingComma, allowNonIdent) {
2232 var elts = [],
2233 first = true;
2234 while (!this.eat(close)) {
2235 if (first) first = false;else this.expect(_tokentype.types.comma);
2236 if (allowEmpty && this.type === _tokentype.types.comma) {
2237 elts.push(null);
2238 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
2239 break;
2240 } else if (this.type === _tokentype.types.ellipsis) {
2241 var rest = this.parseRest(allowNonIdent);
2242 this.parseBindingListItem(rest);
2243 elts.push(rest);
2244 this.expect(close);
2245 break;
2246 } else {
2247 var elem = this.parseMaybeDefault(this.start, this.startLoc);
2248 this.parseBindingListItem(elem);
2249 elts.push(elem);
2250 }
2251 }
2252 return elts;
2253};
2254
2255pp.parseBindingListItem = function (param) {
2256 return param;
2257};
2258
2259// Parses assignment pattern around given atom if possible.
2260
2261pp.parseMaybeDefault = function (startPos, startLoc, left) {
2262 left = left || this.parseBindingAtom();
2263 if (this.options.ecmaVersion < 6 || !this.eat(_tokentype.types.eq)) return left;
2264 var node = this.startNodeAt(startPos, startLoc);
2265 node.left = left;
2266 node.right = this.parseMaybeAssign();
2267 return this.finishNode(node, "AssignmentPattern");
2268};
2269
2270// Verify that a node is an lval — something that can be assigned
2271// to.
2272
2273pp.checkLVal = function (expr, isBinding, checkClashes) {
2274 switch (expr.type) {
2275 case "Identifier":
2276 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
2277 if (checkClashes) {
2278 if (_util.has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash");
2279 checkClashes[expr.name] = true;
2280 }
2281 break;
2282
2283 case "MemberExpression":
2284 if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
2285 break;
2286
2287 case "ObjectPattern":
2288 for (var i = 0; i < expr.properties.length; i++) {
2289 this.checkLVal(expr.properties[i].value, isBinding, checkClashes);
2290 }break;
2291
2292 case "ArrayPattern":
2293 for (var i = 0; i < expr.elements.length; i++) {
2294 var elem = expr.elements[i];
2295 if (elem) this.checkLVal(elem, isBinding, checkClashes);
2296 }
2297 break;
2298
2299 case "AssignmentPattern":
2300 this.checkLVal(expr.left, isBinding, checkClashes);
2301 break;
2302
2303 case "RestElement":
2304 this.checkLVal(expr.argument, isBinding, checkClashes);
2305 break;
2306
2307 case "ParenthesizedExpression":
2308 this.checkLVal(expr.expression, isBinding, checkClashes);
2309 break;
2310
2311 default:
2312 this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
2313 }
2314};
2315
2316},{"./state":10,"./tokentype":14,"./util":15}],7:[function(_dereq_,module,exports){
2317"use strict";
2318
2319exports.__esModule = true;
2320
2321function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2322
2323var _state = _dereq_("./state");
2324
2325var _locutil = _dereq_("./locutil");
2326
2327var Node = function Node(parser, pos, loc) {
2328 _classCallCheck(this, Node);
2329
2330 this.type = "";
2331 this.start = pos;
2332 this.end = 0;
2333 if (parser.options.locations) this.loc = new _locutil.SourceLocation(parser, loc);
2334 if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
2335 if (parser.options.ranges) this.range = [pos, 0];
2336}
2337
2338// Start an AST node, attaching a start offset.
2339
2340;
2341
2342exports.Node = Node;
2343var pp = _state.Parser.prototype;
2344
2345pp.startNode = function () {
2346 return new Node(this, this.start, this.startLoc);
2347};
2348
2349pp.startNodeAt = function (pos, loc) {
2350 return new Node(this, pos, loc);
2351};
2352
2353// Finish an AST node, adding `type` and `end` properties.
2354
2355function finishNodeAt(node, type, pos, loc) {
2356 node.type = type;
2357 node.end = pos;
2358 if (this.options.locations) node.loc.end = loc;
2359 if (this.options.ranges) node.range[1] = pos;
2360 return node;
2361}
2362
2363pp.finishNode = function (node, type) {
2364 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
2365};
2366
2367// Finish node at given position
2368
2369pp.finishNodeAt = function (node, type, pos, loc) {
2370 return finishNodeAt.call(this, node, type, pos, loc);
2371};
2372
2373},{"./locutil":5,"./state":10}],8:[function(_dereq_,module,exports){
2374"use strict";
2375
2376exports.__esModule = true;
2377exports.getOptions = getOptions;
2378
2379var _util = _dereq_("./util");
2380
2381var _locutil = _dereq_("./locutil");
2382
2383// A second optional argument can be given to further configure
2384// the parser process. These options are recognized:
2385
2386var defaultOptions = {
2387 // `ecmaVersion` indicates the ECMAScript version to parse. Must
2388 // be either 3, or 5, or 6. This influences support for strict
2389 // mode, the set of reserved words, support for getters and
2390 // setters and other features.
2391 ecmaVersion: 5,
2392 // Source type ("script" or "module") for different semantics
2393 sourceType: "script",
2394 // `onInsertedSemicolon` can be a callback that will be called
2395 // when a semicolon is automatically inserted. It will be passed
2396 // th position of the comma as an offset, and if `locations` is
2397 // enabled, it is given the location as a `{line, column}` object
2398 // as second argument.
2399 onInsertedSemicolon: null,
2400 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
2401 // trailing commas.
2402 onTrailingComma: null,
2403 // By default, reserved words are only enforced if ecmaVersion >= 5.
2404 // Set `allowReserved` to a boolean value to explicitly turn this on
2405 // an off. When this option has the value "never", reserved words
2406 // and keywords can also not be used as property names.
2407 allowReserved: null,
2408 // When enabled, a return at the top level is not considered an
2409 // error.
2410 allowReturnOutsideFunction: false,
2411 // When enabled, import/export statements are not constrained to
2412 // appearing at the top of the program.
2413 allowImportExportEverywhere: false,
2414 // When enabled, hashbang directive in the beginning of file
2415 // is allowed and treated as a line comment.
2416 allowHashBang: false,
2417 // When `locations` is on, `loc` properties holding objects with
2418 // `start` and `end` properties in `{line, column}` form (with
2419 // line being 1-based and column 0-based) will be attached to the
2420 // nodes.
2421 locations: false,
2422 // A function can be passed as `onToken` option, which will
2423 // cause Acorn to call that function with object in the same
2424 // format as tokens returned from `tokenizer().getToken()`. Note
2425 // that you are not allowed to call the parser from the
2426 // callback—that will corrupt its internal state.
2427 onToken: null,
2428 // A function can be passed as `onComment` option, which will
2429 // cause Acorn to call that function with `(block, text, start,
2430 // end)` parameters whenever a comment is skipped. `block` is a
2431 // boolean indicating whether this is a block (`/* */`) comment,
2432 // `text` is the content of the comment, and `start` and `end` are
2433 // character offsets that denote the start and end of the comment.
2434 // When the `locations` option is on, two more parameters are
2435 // passed, the full `{line, column}` locations of the start and
2436 // end of the comments. Note that you are not allowed to call the
2437 // parser from the callback—that will corrupt its internal state.
2438 onComment: null,
2439 // Nodes have their start and end characters offsets recorded in
2440 // `start` and `end` properties (directly on the node, rather than
2441 // the `loc` object, which holds line/column data. To also add a
2442 // [semi-standardized][range] `range` property holding a `[start,
2443 // end]` array with the same numbers, set the `ranges` option to
2444 // `true`.
2445 //
2446 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
2447 ranges: false,
2448 // It is possible to parse multiple files into a single AST by
2449 // passing the tree produced by parsing the first file as
2450 // `program` option in subsequent parses. This will add the
2451 // toplevel forms of the parsed file to the `Program` (top) node
2452 // of an existing parse tree.
2453 program: null,
2454 // When `locations` is on, you can pass this to record the source
2455 // file in every node's `loc` object.
2456 sourceFile: null,
2457 // This value, if given, is stored in every node, whether
2458 // `locations` is on or off.
2459 directSourceFile: null,
2460 // When enabled, parenthesized expressions are represented by
2461 // (non-standard) ParenthesizedExpression nodes
2462 preserveParens: false,
2463 plugins: {}
2464};
2465
2466exports.defaultOptions = defaultOptions;
2467// Interpret and default an options object
2468
2469function getOptions(opts) {
2470 var options = {};
2471 for (var opt in defaultOptions) {
2472 options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
2473 }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
2474
2475 if (_util.isArray(options.onToken)) {
2476 (function () {
2477 var tokens = options.onToken;
2478 options.onToken = function (token) {
2479 return tokens.push(token);
2480 };
2481 })();
2482 }
2483 if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);
2484
2485 return options;
2486}
2487
2488function pushComment(options, array) {
2489 return function (block, text, start, end, startLoc, endLoc) {
2490 var comment = {
2491 type: block ? 'Block' : 'Line',
2492 value: text,
2493 start: start,
2494 end: end
2495 };
2496 if (options.locations) comment.loc = new _locutil.SourceLocation(this, startLoc, endLoc);
2497 if (options.ranges) comment.range = [start, end];
2498 array.push(comment);
2499 };
2500}
2501
2502},{"./locutil":5,"./util":15}],9:[function(_dereq_,module,exports){
2503"use strict";
2504
2505var _tokentype = _dereq_("./tokentype");
2506
2507var _state = _dereq_("./state");
2508
2509var _whitespace = _dereq_("./whitespace");
2510
2511var pp = _state.Parser.prototype;
2512
2513// ## Parser utilities
2514
2515// Test whether a statement node is the string literal `"use strict"`.
2516
2517pp.isUseStrict = function (stmt) {
2518 return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict";
2519};
2520
2521// Predicate that tests whether the next token is of the given
2522// type, and if yes, consumes it as a side effect.
2523
2524pp.eat = function (type) {
2525 if (this.type === type) {
2526 this.next();
2527 return true;
2528 } else {
2529 return false;
2530 }
2531};
2532
2533// Tests whether parsed token is a contextual keyword.
2534
2535pp.isContextual = function (name) {
2536 return this.type === _tokentype.types.name && this.value === name;
2537};
2538
2539// Consumes contextual keyword if possible.
2540
2541pp.eatContextual = function (name) {
2542 return this.value === name && this.eat(_tokentype.types.name);
2543};
2544
2545// Asserts that following token is given contextual keyword.
2546
2547pp.expectContextual = function (name) {
2548 if (!this.eatContextual(name)) this.unexpected();
2549};
2550
2551// Test whether a semicolon can be inserted at the current position.
2552
2553pp.canInsertSemicolon = function () {
2554 return this.type === _tokentype.types.eof || this.type === _tokentype.types.braceR || _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
2555};
2556
2557pp.insertSemicolon = function () {
2558 if (this.canInsertSemicolon()) {
2559 if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
2560 return true;
2561 }
2562};
2563
2564// Consume a semicolon, or, failing that, see if we are allowed to
2565// pretend that there is a semicolon at this position.
2566
2567pp.semicolon = function () {
2568 if (!this.eat(_tokentype.types.semi) && !this.insertSemicolon()) this.unexpected();
2569};
2570
2571pp.afterTrailingComma = function (tokType) {
2572 if (this.type == tokType) {
2573 if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
2574 this.next();
2575 return true;
2576 }
2577};
2578
2579// Expect a token of a given type. If found, consume it, otherwise,
2580// raise an unexpected token error.
2581
2582pp.expect = function (type) {
2583 this.eat(type) || this.unexpected();
2584};
2585
2586// Raise an unexpected token error.
2587
2588pp.unexpected = function (pos) {
2589 this.raise(pos != null ? pos : this.start, "Unexpected token");
2590};
2591
2592pp.checkPatternErrors = function (refDestructuringErrors, andThrow) {
2593 var pos = refDestructuringErrors && refDestructuringErrors.trailingComma;
2594 if (!andThrow) return !!pos;
2595 if (pos) this.raise(pos, "Trailing comma is not permitted in destructuring patterns");
2596};
2597
2598pp.checkExpressionErrors = function (refDestructuringErrors, andThrow) {
2599 var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign;
2600 if (!andThrow) return !!pos;
2601 if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns");
2602};
2603
2604},{"./state":10,"./tokentype":14,"./whitespace":16}],10:[function(_dereq_,module,exports){
2605"use strict";
2606
2607exports.__esModule = true;
2608
2609function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2610
2611var _identifier = _dereq_("./identifier");
2612
2613var _tokentype = _dereq_("./tokentype");
2614
2615var _whitespace = _dereq_("./whitespace");
2616
2617var _options = _dereq_("./options");
2618
2619// Registered plugins
2620var plugins = {};
2621
2622exports.plugins = plugins;
2623function keywordRegexp(words) {
2624 return new RegExp("^(" + words.replace(/ /g, "|") + ")$");
2625}
2626
2627var Parser = (function () {
2628 function Parser(options, input, startPos) {
2629 _classCallCheck(this, Parser);
2630
2631 this.options = options = _options.getOptions(options);
2632 this.sourceFile = options.sourceFile;
2633 this.keywords = keywordRegexp(_identifier.keywords[options.ecmaVersion >= 6 ? 6 : 5]);
2634 var reserved = options.allowReserved ? "" : _identifier.reservedWords[options.ecmaVersion] + (options.sourceType == "module" ? " await" : "");
2635 this.reservedWords = keywordRegexp(reserved);
2636 var reservedStrict = (reserved ? reserved + " " : "") + _identifier.reservedWords.strict;
2637 this.reservedWordsStrict = keywordRegexp(reservedStrict);
2638 this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + _identifier.reservedWords.strictBind);
2639 this.input = String(input);
2640
2641 // Used to signal to callers of `readWord1` whether the word
2642 // contained any escape sequences. This is needed because words with
2643 // escape sequences must not be interpreted as keywords.
2644 this.containsEsc = false;
2645
2646 // Load plugins
2647 this.loadPlugins(options.plugins);
2648
2649 // Set up token state
2650
2651 // The current position of the tokenizer in the input.
2652 if (startPos) {
2653 this.pos = startPos;
2654 this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
2655 this.curLine = this.input.slice(0, this.lineStart).split(_whitespace.lineBreak).length;
2656 } else {
2657 this.pos = this.lineStart = 0;
2658 this.curLine = 1;
2659 }
2660
2661 // Properties of the current token:
2662 // Its type
2663 this.type = _tokentype.types.eof;
2664 // For tokens that include more information than their type, the value
2665 this.value = null;
2666 // Its start and end offset
2667 this.start = this.end = this.pos;
2668 // And, if locations are used, the {line, column} object
2669 // corresponding to those offsets
2670 this.startLoc = this.endLoc = this.curPosition();
2671
2672 // Position information for the previous token
2673 this.lastTokEndLoc = this.lastTokStartLoc = null;
2674 this.lastTokStart = this.lastTokEnd = this.pos;
2675
2676 // The context stack is used to superficially track syntactic
2677 // context to predict whether a regular expression is allowed in a
2678 // given position.
2679 this.context = this.initialContext();
2680 this.exprAllowed = true;
2681
2682 // Figure out if it's a module code.
2683 this.strict = this.inModule = options.sourceType === "module";
2684
2685 // Used to signify the start of a potential arrow function
2686 this.potentialArrowAt = -1;
2687
2688 // Flags to track whether we are in a function, a generator.
2689 this.inFunction = this.inGenerator = false;
2690 // Labels in scope.
2691 this.labels = [];
2692
2693 // If enabled, skip leading hashbang line.
2694 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2);
2695 }
2696
2697 // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
2698
2699 Parser.prototype.isKeyword = function isKeyword(word) {
2700 return this.keywords.test(word);
2701 };
2702
2703 Parser.prototype.isReservedWord = function isReservedWord(word) {
2704 return this.reservedWords.test(word);
2705 };
2706
2707 Parser.prototype.extend = function extend(name, f) {
2708 this[name] = f(this[name]);
2709 };
2710
2711 Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
2712 for (var _name in pluginConfigs) {
2713 var plugin = plugins[_name];
2714 if (!plugin) throw new Error("Plugin '" + _name + "' not found");
2715 plugin(this, pluginConfigs[_name]);
2716 }
2717 };
2718
2719 Parser.prototype.parse = function parse() {
2720 var node = this.options.program || this.startNode();
2721 this.nextToken();
2722 return this.parseTopLevel(node);
2723 };
2724
2725 return Parser;
2726})();
2727
2728exports.Parser = Parser;
2729
2730},{"./identifier":2,"./options":8,"./tokentype":14,"./whitespace":16}],11:[function(_dereq_,module,exports){
2731"use strict";
2732
2733var _tokentype = _dereq_("./tokentype");
2734
2735var _state = _dereq_("./state");
2736
2737var _whitespace = _dereq_("./whitespace");
2738
2739var pp = _state.Parser.prototype;
2740
2741// ### Statement parsing
2742
2743// Parse a program. Initializes the parser, reads any number of
2744// statements, and wraps them in a Program node. Optionally takes a
2745// `program` argument. If present, the statements will be appended
2746// to its body instead of creating a new node.
2747
2748pp.parseTopLevel = function (node) {
2749 var first = true;
2750 if (!node.body) node.body = [];
2751 while (this.type !== _tokentype.types.eof) {
2752 var stmt = this.parseStatement(true, true);
2753 node.body.push(stmt);
2754 if (first) {
2755 if (this.isUseStrict(stmt)) this.setStrict(true);
2756 first = false;
2757 }
2758 }
2759 this.next();
2760 if (this.options.ecmaVersion >= 6) {
2761 node.sourceType = this.options.sourceType;
2762 }
2763 return this.finishNode(node, "Program");
2764};
2765
2766var loopLabel = { kind: "loop" },
2767 switchLabel = { kind: "switch" };
2768
2769// Parse a single statement.
2770//
2771// If expecting a statement and finding a slash operator, parse a
2772// regular expression literal. This is to handle cases like
2773// `if (foo) /blah/.exec(foo)`, where looking at the previous token
2774// does not help.
2775
2776pp.parseStatement = function (declaration, topLevel) {
2777 var starttype = this.type,
2778 node = this.startNode();
2779
2780 // Most types of statements are recognized by the keyword they
2781 // start with. Many are trivial to parse, some require a bit of
2782 // complexity.
2783
2784 switch (starttype) {
2785 case _tokentype.types._break:case _tokentype.types._continue:
2786 return this.parseBreakContinueStatement(node, starttype.keyword);
2787 case _tokentype.types._debugger:
2788 return this.parseDebuggerStatement(node);
2789 case _tokentype.types._do:
2790 return this.parseDoStatement(node);
2791 case _tokentype.types._for:
2792 return this.parseForStatement(node);
2793 case _tokentype.types._function:
2794 if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
2795 return this.parseFunctionStatement(node);
2796 case _tokentype.types._class:
2797 if (!declaration) this.unexpected();
2798 return this.parseClass(node, true);
2799 case _tokentype.types._if:
2800 return this.parseIfStatement(node);
2801 case _tokentype.types._return:
2802 return this.parseReturnStatement(node);
2803 case _tokentype.types._switch:
2804 return this.parseSwitchStatement(node);
2805 case _tokentype.types._throw:
2806 return this.parseThrowStatement(node);
2807 case _tokentype.types._try:
2808 return this.parseTryStatement(node);
2809 case _tokentype.types._let:case _tokentype.types._const:
2810 if (!declaration) this.unexpected(); // NOTE: falls through to _var
2811 case _tokentype.types._var:
2812 return this.parseVarStatement(node, starttype);
2813 case _tokentype.types._while:
2814 return this.parseWhileStatement(node);
2815 case _tokentype.types._with:
2816 return this.parseWithStatement(node);
2817 case _tokentype.types.braceL:
2818 return this.parseBlock();
2819 case _tokentype.types.semi:
2820 return this.parseEmptyStatement(node);
2821 case _tokentype.types._export:
2822 case _tokentype.types._import:
2823 if (!this.options.allowImportExportEverywhere) {
2824 if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
2825 if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
2826 }
2827 return starttype === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node);
2828
2829 // If the statement does not start with a statement keyword or a
2830 // brace, it's an ExpressionStatement or LabeledStatement. We
2831 // simply start parsing an expression, and afterwards, if the
2832 // next token is a colon and the expression was a simple
2833 // Identifier node, we switch to interpreting it as a label.
2834 default:
2835 var maybeName = this.value,
2836 expr = this.parseExpression();
2837 if (starttype === _tokentype.types.name && expr.type === "Identifier" && this.eat(_tokentype.types.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
2838 }
2839};
2840
2841pp.parseBreakContinueStatement = function (node, keyword) {
2842 var isBreak = keyword == "break";
2843 this.next();
2844 if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== _tokentype.types.name) this.unexpected();else {
2845 node.label = this.parseIdent();
2846 this.semicolon();
2847 }
2848
2849 // Verify that there is an actual destination to break or
2850 // continue to.
2851 for (var i = 0; i < this.labels.length; ++i) {
2852 var lab = this.labels[i];
2853 if (node.label == null || lab.name === node.label.name) {
2854 if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
2855 if (node.label && isBreak) break;
2856 }
2857 }
2858 if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
2859 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
2860};
2861
2862pp.parseDebuggerStatement = function (node) {
2863 this.next();
2864 this.semicolon();
2865 return this.finishNode(node, "DebuggerStatement");
2866};
2867
2868pp.parseDoStatement = function (node) {
2869 this.next();
2870 this.labels.push(loopLabel);
2871 node.body = this.parseStatement(false);
2872 this.labels.pop();
2873 this.expect(_tokentype.types._while);
2874 node.test = this.parseParenExpression();
2875 if (this.options.ecmaVersion >= 6) this.eat(_tokentype.types.semi);else this.semicolon();
2876 return this.finishNode(node, "DoWhileStatement");
2877};
2878
2879// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
2880// loop is non-trivial. Basically, we have to parse the init `var`
2881// statement or expression, disallowing the `in` operator (see
2882// the second parameter to `parseExpression`), and then check
2883// whether the next token is `in` or `of`. When there is no init
2884// part (semicolon immediately after the opening parenthesis), it
2885// is a regular `for` loop.
2886
2887pp.parseForStatement = function (node) {
2888 this.next();
2889 this.labels.push(loopLabel);
2890 this.expect(_tokentype.types.parenL);
2891 if (this.type === _tokentype.types.semi) return this.parseFor(node, null);
2892 if (this.type === _tokentype.types._var || this.type === _tokentype.types._let || this.type === _tokentype.types._const) {
2893 var _init = this.startNode(),
2894 varKind = this.type;
2895 this.next();
2896 this.parseVar(_init, true, varKind);
2897 this.finishNode(_init, "VariableDeclaration");
2898 if ((this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== _tokentype.types._var && _init.declarations[0].init)) return this.parseForIn(node, _init);
2899 return this.parseFor(node, _init);
2900 }
2901 var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
2902 var init = this.parseExpression(true, refDestructuringErrors);
2903 if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
2904 this.checkPatternErrors(refDestructuringErrors, true);
2905 this.toAssignable(init);
2906 this.checkLVal(init);
2907 return this.parseForIn(node, init);
2908 } else {
2909 this.checkExpressionErrors(refDestructuringErrors, true);
2910 }
2911 return this.parseFor(node, init);
2912};
2913
2914pp.parseFunctionStatement = function (node) {
2915 this.next();
2916 return this.parseFunction(node, true);
2917};
2918
2919pp.parseIfStatement = function (node) {
2920 this.next();
2921 node.test = this.parseParenExpression();
2922 node.consequent = this.parseStatement(false);
2923 node.alternate = this.eat(_tokentype.types._else) ? this.parseStatement(false) : null;
2924 return this.finishNode(node, "IfStatement");
2925};
2926
2927pp.parseReturnStatement = function (node) {
2928 if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
2929 this.next();
2930
2931 // In `return` (and `break`/`continue`), the keywords with
2932 // optional arguments, we eagerly look for a semicolon or the
2933 // possibility to insert one.
2934
2935 if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.argument = null;else {
2936 node.argument = this.parseExpression();this.semicolon();
2937 }
2938 return this.finishNode(node, "ReturnStatement");
2939};
2940
2941pp.parseSwitchStatement = function (node) {
2942 this.next();
2943 node.discriminant = this.parseParenExpression();
2944 node.cases = [];
2945 this.expect(_tokentype.types.braceL);
2946 this.labels.push(switchLabel);
2947
2948 // Statements under must be grouped (by label) in SwitchCase
2949 // nodes. `cur` is used to keep the node that we are currently
2950 // adding statements to.
2951
2952 for (var cur, sawDefault = false; this.type != _tokentype.types.braceR;) {
2953 if (this.type === _tokentype.types._case || this.type === _tokentype.types._default) {
2954 var isCase = this.type === _tokentype.types._case;
2955 if (cur) this.finishNode(cur, "SwitchCase");
2956 node.cases.push(cur = this.startNode());
2957 cur.consequent = [];
2958 this.next();
2959 if (isCase) {
2960 cur.test = this.parseExpression();
2961 } else {
2962 if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
2963 sawDefault = true;
2964 cur.test = null;
2965 }
2966 this.expect(_tokentype.types.colon);
2967 } else {
2968 if (!cur) this.unexpected();
2969 cur.consequent.push(this.parseStatement(true));
2970 }
2971 }
2972 if (cur) this.finishNode(cur, "SwitchCase");
2973 this.next(); // Closing brace
2974 this.labels.pop();
2975 return this.finishNode(node, "SwitchStatement");
2976};
2977
2978pp.parseThrowStatement = function (node) {
2979 this.next();
2980 if (_whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
2981 node.argument = this.parseExpression();
2982 this.semicolon();
2983 return this.finishNode(node, "ThrowStatement");
2984};
2985
2986// Reused empty array added for node fields that are always empty.
2987
2988var empty = [];
2989
2990pp.parseTryStatement = function (node) {
2991 this.next();
2992 node.block = this.parseBlock();
2993 node.handler = null;
2994 if (this.type === _tokentype.types._catch) {
2995 var clause = this.startNode();
2996 this.next();
2997 this.expect(_tokentype.types.parenL);
2998 clause.param = this.parseBindingAtom();
2999 this.checkLVal(clause.param, true);
3000 this.expect(_tokentype.types.parenR);
3001 clause.body = this.parseBlock();
3002 node.handler = this.finishNode(clause, "CatchClause");
3003 }
3004 node.finalizer = this.eat(_tokentype.types._finally) ? this.parseBlock() : null;
3005 if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
3006 return this.finishNode(node, "TryStatement");
3007};
3008
3009pp.parseVarStatement = function (node, kind) {
3010 this.next();
3011 this.parseVar(node, false, kind);
3012 this.semicolon();
3013 return this.finishNode(node, "VariableDeclaration");
3014};
3015
3016pp.parseWhileStatement = function (node) {
3017 this.next();
3018 node.test = this.parseParenExpression();
3019 this.labels.push(loopLabel);
3020 node.body = this.parseStatement(false);
3021 this.labels.pop();
3022 return this.finishNode(node, "WhileStatement");
3023};
3024
3025pp.parseWithStatement = function (node) {
3026 if (this.strict) this.raise(this.start, "'with' in strict mode");
3027 this.next();
3028 node.object = this.parseParenExpression();
3029 node.body = this.parseStatement(false);
3030 return this.finishNode(node, "WithStatement");
3031};
3032
3033pp.parseEmptyStatement = function (node) {
3034 this.next();
3035 return this.finishNode(node, "EmptyStatement");
3036};
3037
3038pp.parseLabeledStatement = function (node, maybeName, expr) {
3039 for (var i = 0; i < this.labels.length; ++i) {
3040 if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
3041 }var kind = this.type.isLoop ? "loop" : this.type === _tokentype.types._switch ? "switch" : null;
3042 for (var i = this.labels.length - 1; i >= 0; i--) {
3043 var label = this.labels[i];
3044 if (label.statementStart == node.start) {
3045 label.statementStart = this.start;
3046 label.kind = kind;
3047 } else break;
3048 }
3049 this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
3050 node.body = this.parseStatement(true);
3051 this.labels.pop();
3052 node.label = expr;
3053 return this.finishNode(node, "LabeledStatement");
3054};
3055
3056pp.parseExpressionStatement = function (node, expr) {
3057 node.expression = expr;
3058 this.semicolon();
3059 return this.finishNode(node, "ExpressionStatement");
3060};
3061
3062// Parse a semicolon-enclosed block of statements, handling `"use
3063// strict"` declarations when `allowStrict` is true (used for
3064// function bodies).
3065
3066pp.parseBlock = function (allowStrict) {
3067 var node = this.startNode(),
3068 first = true,
3069 oldStrict = undefined;
3070 node.body = [];
3071 this.expect(_tokentype.types.braceL);
3072 while (!this.eat(_tokentype.types.braceR)) {
3073 var stmt = this.parseStatement(true);
3074 node.body.push(stmt);
3075 if (first && allowStrict && this.isUseStrict(stmt)) {
3076 oldStrict = this.strict;
3077 this.setStrict(this.strict = true);
3078 }
3079 first = false;
3080 }
3081 if (oldStrict === false) this.setStrict(false);
3082 return this.finishNode(node, "BlockStatement");
3083};
3084
3085// Parse a regular `for` loop. The disambiguation code in
3086// `parseStatement` will already have parsed the init statement or
3087// expression.
3088
3089pp.parseFor = function (node, init) {
3090 node.init = init;
3091 this.expect(_tokentype.types.semi);
3092 node.test = this.type === _tokentype.types.semi ? null : this.parseExpression();
3093 this.expect(_tokentype.types.semi);
3094 node.update = this.type === _tokentype.types.parenR ? null : this.parseExpression();
3095 this.expect(_tokentype.types.parenR);
3096 node.body = this.parseStatement(false);
3097 this.labels.pop();
3098 return this.finishNode(node, "ForStatement");
3099};
3100
3101// Parse a `for`/`in` and `for`/`of` loop, which are almost
3102// same from parser's perspective.
3103
3104pp.parseForIn = function (node, init) {
3105 var type = this.type === _tokentype.types._in ? "ForInStatement" : "ForOfStatement";
3106 this.next();
3107 node.left = init;
3108 node.right = this.parseExpression();
3109 this.expect(_tokentype.types.parenR);
3110 node.body = this.parseStatement(false);
3111 this.labels.pop();
3112 return this.finishNode(node, type);
3113};
3114
3115// Parse a list of variable declarations.
3116
3117pp.parseVar = function (node, isFor, kind) {
3118 node.declarations = [];
3119 node.kind = kind.keyword;
3120 for (;;) {
3121 var decl = this.startNode();
3122 this.parseVarId(decl);
3123 if (this.eat(_tokentype.types.eq)) {
3124 decl.init = this.parseMaybeAssign(isFor);
3125 } else if (kind === _tokentype.types._const && !(this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
3126 this.unexpected();
3127 } else if (decl.id.type != "Identifier" && !(isFor && (this.type === _tokentype.types._in || this.isContextual("of")))) {
3128 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
3129 } else {
3130 decl.init = null;
3131 }
3132 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
3133 if (!this.eat(_tokentype.types.comma)) break;
3134 }
3135 return node;
3136};
3137
3138pp.parseVarId = function (decl) {
3139 decl.id = this.parseBindingAtom();
3140 this.checkLVal(decl.id, true);
3141};
3142
3143// Parse a function declaration or literal (depending on the
3144// `isStatement` parameter).
3145
3146pp.parseFunction = function (node, isStatement, allowExpressionBody) {
3147 this.initFunction(node);
3148 if (this.options.ecmaVersion >= 6) node.generator = this.eat(_tokentype.types.star);
3149 if (isStatement || this.type === _tokentype.types.name) node.id = this.parseIdent();
3150 this.parseFunctionParams(node);
3151 this.parseFunctionBody(node, allowExpressionBody);
3152 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
3153};
3154
3155pp.parseFunctionParams = function (node) {
3156 this.expect(_tokentype.types.parenL);
3157 node.params = this.parseBindingList(_tokentype.types.parenR, false, false, true);
3158};
3159
3160// Parse a class declaration or literal (depending on the
3161// `isStatement` parameter).
3162
3163pp.parseClass = function (node, isStatement) {
3164 this.next();
3165 this.parseClassId(node, isStatement);
3166 this.parseClassSuper(node);
3167 var classBody = this.startNode();
3168 var hadConstructor = false;
3169 classBody.body = [];
3170 this.expect(_tokentype.types.braceL);
3171 while (!this.eat(_tokentype.types.braceR)) {
3172 if (this.eat(_tokentype.types.semi)) continue;
3173 var method = this.startNode();
3174 var isGenerator = this.eat(_tokentype.types.star);
3175 var isMaybeStatic = this.type === _tokentype.types.name && this.value === "static";
3176 this.parsePropertyName(method);
3177 method["static"] = isMaybeStatic && this.type !== _tokentype.types.parenL;
3178 if (method["static"]) {
3179 if (isGenerator) this.unexpected();
3180 isGenerator = this.eat(_tokentype.types.star);
3181 this.parsePropertyName(method);
3182 }
3183 method.kind = "method";
3184 var isGetSet = false;
3185 if (!method.computed) {
3186 var key = method.key;
3187
3188 if (!isGenerator && key.type === "Identifier" && this.type !== _tokentype.types.parenL && (key.name === "get" || key.name === "set")) {
3189 isGetSet = true;
3190 method.kind = key.name;
3191 key = this.parsePropertyName(method);
3192 }
3193 if (!method["static"] && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
3194 if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
3195 if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
3196 if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
3197 method.kind = "constructor";
3198 hadConstructor = true;
3199 }
3200 }
3201 this.parseClassMethod(classBody, method, isGenerator);
3202 if (isGetSet) {
3203 var paramCount = method.kind === "get" ? 0 : 1;
3204 if (method.value.params.length !== paramCount) {
3205 var start = method.value.start;
3206 if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
3207 }
3208 }
3209 }
3210 node.body = this.finishNode(classBody, "ClassBody");
3211 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
3212};
3213
3214pp.parseClassMethod = function (classBody, method, isGenerator) {
3215 method.value = this.parseMethod(isGenerator);
3216 classBody.body.push(this.finishNode(method, "MethodDefinition"));
3217};
3218
3219pp.parseClassId = function (node, isStatement) {
3220 node.id = this.type === _tokentype.types.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
3221};
3222
3223pp.parseClassSuper = function (node) {
3224 node.superClass = this.eat(_tokentype.types._extends) ? this.parseExprSubscripts() : null;
3225};
3226
3227// Parses module export declaration.
3228
3229pp.parseExport = function (node) {
3230 this.next();
3231 // export * from '...'
3232 if (this.eat(_tokentype.types.star)) {
3233 this.expectContextual("from");
3234 node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
3235 this.semicolon();
3236 return this.finishNode(node, "ExportAllDeclaration");
3237 }
3238 if (this.eat(_tokentype.types._default)) {
3239 // export default ...
3240 var expr = this.parseMaybeAssign();
3241 var needsSemi = true;
3242 if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
3243 needsSemi = false;
3244 if (expr.id) {
3245 expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
3246 }
3247 }
3248 node.declaration = expr;
3249 if (needsSemi) this.semicolon();
3250 return this.finishNode(node, "ExportDefaultDeclaration");
3251 }
3252 // export var|const|let|function|class ...
3253 if (this.shouldParseExportStatement()) {
3254 node.declaration = this.parseStatement(true);
3255 node.specifiers = [];
3256 node.source = null;
3257 } else {
3258 // export { x, y as z } [from '...']
3259 node.declaration = null;
3260 node.specifiers = this.parseExportSpecifiers();
3261 if (this.eatContextual("from")) {
3262 node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
3263 } else {
3264 // check for keywords used as local names
3265 for (var i = 0; i < node.specifiers.length; i++) {
3266 if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) {
3267 this.unexpected(node.specifiers[i].local.start);
3268 }
3269 }
3270
3271 node.source = null;
3272 }
3273 this.semicolon();
3274 }
3275 return this.finishNode(node, "ExportNamedDeclaration");
3276};
3277
3278pp.shouldParseExportStatement = function () {
3279 return this.type.keyword;
3280};
3281
3282// Parses a comma-separated list of module exports.
3283
3284pp.parseExportSpecifiers = function () {
3285 var nodes = [],
3286 first = true;
3287 // export { x, y as z } [from '...']
3288 this.expect(_tokentype.types.braceL);
3289 while (!this.eat(_tokentype.types.braceR)) {
3290 if (!first) {
3291 this.expect(_tokentype.types.comma);
3292 if (this.afterTrailingComma(_tokentype.types.braceR)) break;
3293 } else first = false;
3294
3295 var node = this.startNode();
3296 node.local = this.parseIdent(this.type === _tokentype.types._default);
3297 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
3298 nodes.push(this.finishNode(node, "ExportSpecifier"));
3299 }
3300 return nodes;
3301};
3302
3303// Parses import declaration.
3304
3305pp.parseImport = function (node) {
3306 this.next();
3307 // import '...'
3308 if (this.type === _tokentype.types.string) {
3309 node.specifiers = empty;
3310 node.source = this.parseExprAtom();
3311 } else {
3312 node.specifiers = this.parseImportSpecifiers();
3313 this.expectContextual("from");
3314 node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
3315 }
3316 this.semicolon();
3317 return this.finishNode(node, "ImportDeclaration");
3318};
3319
3320// Parses a comma-separated list of module imports.
3321
3322pp.parseImportSpecifiers = function () {
3323 var nodes = [],
3324 first = true;
3325 if (this.type === _tokentype.types.name) {
3326 // import defaultObj, { x, y as z } from '...'
3327 var node = this.startNode();
3328 node.local = this.parseIdent();
3329 this.checkLVal(node.local, true);
3330 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
3331 if (!this.eat(_tokentype.types.comma)) return nodes;
3332 }
3333 if (this.type === _tokentype.types.star) {
3334 var node = this.startNode();
3335 this.next();
3336 this.expectContextual("as");
3337 node.local = this.parseIdent();
3338 this.checkLVal(node.local, true);
3339 nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"));
3340 return nodes;
3341 }
3342 this.expect(_tokentype.types.braceL);
3343 while (!this.eat(_tokentype.types.braceR)) {
3344 if (!first) {
3345 this.expect(_tokentype.types.comma);
3346 if (this.afterTrailingComma(_tokentype.types.braceR)) break;
3347 } else first = false;
3348
3349 var node = this.startNode();
3350 node.imported = this.parseIdent(true);
3351 node.local = this.eatContextual("as") ? this.parseIdent() : node.imported;
3352 this.checkLVal(node.local, true);
3353 nodes.push(this.finishNode(node, "ImportSpecifier"));
3354 }
3355 return nodes;
3356};
3357
3358},{"./state":10,"./tokentype":14,"./whitespace":16}],12:[function(_dereq_,module,exports){
3359// The algorithm used to determine whether a regexp can appear at a
3360// given point in the program is loosely based on sweet.js' approach.
3361// See https://github.com/mozilla/sweet.js/wiki/design
3362
3363"use strict";
3364
3365exports.__esModule = true;
3366
3367function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3368
3369var _state = _dereq_("./state");
3370
3371var _tokentype = _dereq_("./tokentype");
3372
3373var _whitespace = _dereq_("./whitespace");
3374
3375var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
3376 _classCallCheck(this, TokContext);
3377
3378 this.token = token;
3379 this.isExpr = !!isExpr;
3380 this.preserveSpace = !!preserveSpace;
3381 this.override = override;
3382};
3383
3384exports.TokContext = TokContext;
3385var types = {
3386 b_stat: new TokContext("{", false),
3387 b_expr: new TokContext("{", true),
3388 b_tmpl: new TokContext("${", true),
3389 p_stat: new TokContext("(", false),
3390 p_expr: new TokContext("(", true),
3391 q_tmpl: new TokContext("`", true, true, function (p) {
3392 return p.readTmplToken();
3393 }),
3394 f_expr: new TokContext("function", true)
3395};
3396
3397exports.types = types;
3398var pp = _state.Parser.prototype;
3399
3400pp.initialContext = function () {
3401 return [types.b_stat];
3402};
3403
3404pp.braceIsBlock = function (prevType) {
3405 if (prevType === _tokentype.types.colon) {
3406 var _parent = this.curContext();
3407 if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr;
3408 }
3409 if (prevType === _tokentype.types._return) return _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
3410 if (prevType === _tokentype.types._else || prevType === _tokentype.types.semi || prevType === _tokentype.types.eof || prevType === _tokentype.types.parenR) return true;
3411 if (prevType == _tokentype.types.braceL) return this.curContext() === types.b_stat;
3412 return !this.exprAllowed;
3413};
3414
3415pp.updateContext = function (prevType) {
3416 var update = undefined,
3417 type = this.type;
3418 if (type.keyword && prevType == _tokentype.types.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
3419};
3420
3421// Token-specific context update code
3422
3423_tokentype.types.parenR.updateContext = _tokentype.types.braceR.updateContext = function () {
3424 if (this.context.length == 1) {
3425 this.exprAllowed = true;
3426 return;
3427 }
3428 var out = this.context.pop();
3429 if (out === types.b_stat && this.curContext() === types.f_expr) {
3430 this.context.pop();
3431 this.exprAllowed = false;
3432 } else if (out === types.b_tmpl) {
3433 this.exprAllowed = true;
3434 } else {
3435 this.exprAllowed = !out.isExpr;
3436 }
3437};
3438
3439_tokentype.types.braceL.updateContext = function (prevType) {
3440 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
3441 this.exprAllowed = true;
3442};
3443
3444_tokentype.types.dollarBraceL.updateContext = function () {
3445 this.context.push(types.b_tmpl);
3446 this.exprAllowed = true;
3447};
3448
3449_tokentype.types.parenL.updateContext = function (prevType) {
3450 var statementParens = prevType === _tokentype.types._if || prevType === _tokentype.types._for || prevType === _tokentype.types._with || prevType === _tokentype.types._while;
3451 this.context.push(statementParens ? types.p_stat : types.p_expr);
3452 this.exprAllowed = true;
3453};
3454
3455_tokentype.types.incDec.updateContext = function () {
3456 // tokExprAllowed stays unchanged
3457};
3458
3459_tokentype.types._function.updateContext = function () {
3460 if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
3461 this.exprAllowed = false;
3462};
3463
3464_tokentype.types.backQuote.updateContext = function () {
3465 if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
3466 this.exprAllowed = false;
3467};
3468
3469},{"./state":10,"./tokentype":14,"./whitespace":16}],13:[function(_dereq_,module,exports){
3470"use strict";
3471
3472exports.__esModule = true;
3473
3474function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3475
3476var _identifier = _dereq_("./identifier");
3477
3478var _tokentype = _dereq_("./tokentype");
3479
3480var _state = _dereq_("./state");
3481
3482var _locutil = _dereq_("./locutil");
3483
3484var _whitespace = _dereq_("./whitespace");
3485
3486// Object type used to represent tokens. Note that normally, tokens
3487// simply exist as properties on the parser object. This is only
3488// used for the onToken callback and the external tokenizer.
3489
3490var Token = function Token(p) {
3491 _classCallCheck(this, Token);
3492
3493 this.type = p.type;
3494 this.value = p.value;
3495 this.start = p.start;
3496 this.end = p.end;
3497 if (p.options.locations) this.loc = new _locutil.SourceLocation(p, p.startLoc, p.endLoc);
3498 if (p.options.ranges) this.range = [p.start, p.end];
3499}
3500
3501// ## Tokenizer
3502
3503;
3504
3505exports.Token = Token;
3506var pp = _state.Parser.prototype;
3507
3508// Are we running under Rhino?
3509var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
3510
3511// Move to the next token
3512
3513pp.next = function () {
3514 if (this.options.onToken) this.options.onToken(new Token(this));
3515
3516 this.lastTokEnd = this.end;
3517 this.lastTokStart = this.start;
3518 this.lastTokEndLoc = this.endLoc;
3519 this.lastTokStartLoc = this.startLoc;
3520 this.nextToken();
3521};
3522
3523pp.getToken = function () {
3524 this.next();
3525 return new Token(this);
3526};
3527
3528// If we're in an ES6 environment, make parsers iterable
3529if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () {
3530 var self = this;
3531 return { next: function next() {
3532 var token = self.getToken();
3533 return {
3534 done: token.type === _tokentype.types.eof,
3535 value: token
3536 };
3537 } };
3538};
3539
3540// Toggle strict mode. Re-reads the next number or string to please
3541// pedantic tests (`"use strict"; 010;` should fail).
3542
3543pp.setStrict = function (strict) {
3544 this.strict = strict;
3545 if (this.type !== _tokentype.types.num && this.type !== _tokentype.types.string) return;
3546 this.pos = this.start;
3547 if (this.options.locations) {
3548 while (this.pos < this.lineStart) {
3549 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
3550 --this.curLine;
3551 }
3552 }
3553 this.nextToken();
3554};
3555
3556pp.curContext = function () {
3557 return this.context[this.context.length - 1];
3558};
3559
3560// Read a single token, updating the parser object's token-related
3561// properties.
3562
3563pp.nextToken = function () {
3564 var curContext = this.curContext();
3565 if (!curContext || !curContext.preserveSpace) this.skipSpace();
3566
3567 this.start = this.pos;
3568 if (this.options.locations) this.startLoc = this.curPosition();
3569 if (this.pos >= this.input.length) return this.finishToken(_tokentype.types.eof);
3570
3571 if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
3572};
3573
3574pp.readToken = function (code) {
3575 // Identifier or keyword. '\uXXXX' sequences are allowed in
3576 // identifiers, so '\' also dispatches to that.
3577 if (_identifier.isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
3578
3579 return this.getTokenFromCode(code);
3580};
3581
3582pp.fullCharCodeAtPos = function () {
3583 var code = this.input.charCodeAt(this.pos);
3584 if (code <= 0xd7ff || code >= 0xe000) return code;
3585 var next = this.input.charCodeAt(this.pos + 1);
3586 return (code << 10) + next - 0x35fdc00;
3587};
3588
3589pp.skipBlockComment = function () {
3590 var startLoc = this.options.onComment && this.curPosition();
3591 var start = this.pos,
3592 end = this.input.indexOf("*/", this.pos += 2);
3593 if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
3594 this.pos = end + 2;
3595 if (this.options.locations) {
3596 _whitespace.lineBreakG.lastIndex = start;
3597 var match = undefined;
3598 while ((match = _whitespace.lineBreakG.exec(this.input)) && match.index < this.pos) {
3599 ++this.curLine;
3600 this.lineStart = match.index + match[0].length;
3601 }
3602 }
3603 if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
3604};
3605
3606pp.skipLineComment = function (startSkip) {
3607 var start = this.pos;
3608 var startLoc = this.options.onComment && this.curPosition();
3609 var ch = this.input.charCodeAt(this.pos += startSkip);
3610 while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
3611 ++this.pos;
3612 ch = this.input.charCodeAt(this.pos);
3613 }
3614 if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
3615};
3616
3617// Called at the start of the parse and after every token. Skips
3618// whitespace and comments, and.
3619
3620pp.skipSpace = function () {
3621 loop: while (this.pos < this.input.length) {
3622 var ch = this.input.charCodeAt(this.pos);
3623 switch (ch) {
3624 case 32:case 160:
3625 // ' '
3626 ++this.pos;
3627 break;
3628 case 13:
3629 if (this.input.charCodeAt(this.pos + 1) === 10) {
3630 ++this.pos;
3631 }
3632 case 10:case 8232:case 8233:
3633 ++this.pos;
3634 if (this.options.locations) {
3635 ++this.curLine;
3636 this.lineStart = this.pos;
3637 }
3638 break;
3639 case 47:
3640 // '/'
3641 switch (this.input.charCodeAt(this.pos + 1)) {
3642 case 42:
3643 // '*'
3644 this.skipBlockComment();
3645 break;
3646 case 47:
3647 this.skipLineComment(2);
3648 break;
3649 default:
3650 break loop;
3651 }
3652 break;
3653 default:
3654 if (ch > 8 && ch < 14 || ch >= 5760 && _whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) {
3655 ++this.pos;
3656 } else {
3657 break loop;
3658 }
3659 }
3660 }
3661};
3662
3663// Called at the end of every token. Sets `end`, `val`, and
3664// maintains `context` and `exprAllowed`, and skips the space after
3665// the token, so that the next one's `start` will point at the
3666// right position.
3667
3668pp.finishToken = function (type, val) {
3669 this.end = this.pos;
3670 if (this.options.locations) this.endLoc = this.curPosition();
3671 var prevType = this.type;
3672 this.type = type;
3673 this.value = val;
3674
3675 this.updateContext(prevType);
3676};
3677
3678// ### Token reading
3679
3680// This is the function that is called to fetch the next token. It
3681// is somewhat obscure, because it works in character codes rather
3682// than characters, and because operator parsing has been inlined
3683// into it.
3684//
3685// All in the name of speed.
3686//
3687pp.readToken_dot = function () {
3688 var next = this.input.charCodeAt(this.pos + 1);
3689 if (next >= 48 && next <= 57) return this.readNumber(true);
3690 var next2 = this.input.charCodeAt(this.pos + 2);
3691 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
3692 // 46 = dot '.'
3693 this.pos += 3;
3694 return this.finishToken(_tokentype.types.ellipsis);
3695 } else {
3696 ++this.pos;
3697 return this.finishToken(_tokentype.types.dot);
3698 }
3699};
3700
3701pp.readToken_slash = function () {
3702 // '/'
3703 var next = this.input.charCodeAt(this.pos + 1);
3704 if (this.exprAllowed) {
3705 ++this.pos;return this.readRegexp();
3706 }
3707 if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
3708 return this.finishOp(_tokentype.types.slash, 1);
3709};
3710
3711pp.readToken_mult_modulo = function (code) {
3712 // '%*'
3713 var next = this.input.charCodeAt(this.pos + 1);
3714 if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
3715 return this.finishOp(code === 42 ? _tokentype.types.star : _tokentype.types.modulo, 1);
3716};
3717
3718pp.readToken_pipe_amp = function (code) {
3719 // '|&'
3720 var next = this.input.charCodeAt(this.pos + 1);
3721 if (next === code) return this.finishOp(code === 124 ? _tokentype.types.logicalOR : _tokentype.types.logicalAND, 2);
3722 if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
3723 return this.finishOp(code === 124 ? _tokentype.types.bitwiseOR : _tokentype.types.bitwiseAND, 1);
3724};
3725
3726pp.readToken_caret = function () {
3727 // '^'
3728 var next = this.input.charCodeAt(this.pos + 1);
3729 if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
3730 return this.finishOp(_tokentype.types.bitwiseXOR, 1);
3731};
3732
3733pp.readToken_plus_min = function (code) {
3734 // '+-'
3735 var next = this.input.charCodeAt(this.pos + 1);
3736 if (next === code) {
3737 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
3738 // A `-->` line comment
3739 this.skipLineComment(3);
3740 this.skipSpace();
3741 return this.nextToken();
3742 }
3743 return this.finishOp(_tokentype.types.incDec, 2);
3744 }
3745 if (next === 61) return this.finishOp(_tokentype.types.assign, 2);
3746 return this.finishOp(_tokentype.types.plusMin, 1);
3747};
3748
3749pp.readToken_lt_gt = function (code) {
3750 // '<>'
3751 var next = this.input.charCodeAt(this.pos + 1);
3752 var size = 1;
3753 if (next === code) {
3754 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
3755 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(_tokentype.types.assign, size + 1);
3756 return this.finishOp(_tokentype.types.bitShift, size);
3757 }
3758 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
3759 if (this.inModule) this.unexpected();
3760 // `<!--`, an XML-style comment that should be interpreted as a line comment
3761 this.skipLineComment(4);
3762 this.skipSpace();
3763 return this.nextToken();
3764 }
3765 if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
3766 return this.finishOp(_tokentype.types.relational, size);
3767};
3768
3769pp.readToken_eq_excl = function (code) {
3770 // '=!'
3771 var next = this.input.charCodeAt(this.pos + 1);
3772 if (next === 61) return this.finishOp(_tokentype.types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
3773 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
3774 // '=>'
3775 this.pos += 2;
3776 return this.finishToken(_tokentype.types.arrow);
3777 }
3778 return this.finishOp(code === 61 ? _tokentype.types.eq : _tokentype.types.prefix, 1);
3779};
3780
3781pp.getTokenFromCode = function (code) {
3782 switch (code) {
3783 // The interpretation of a dot depends on whether it is followed
3784 // by a digit or another two dots.
3785 case 46:
3786 // '.'
3787 return this.readToken_dot();
3788
3789 // Punctuation tokens.
3790 case 40:
3791 ++this.pos;return this.finishToken(_tokentype.types.parenL);
3792 case 41:
3793 ++this.pos;return this.finishToken(_tokentype.types.parenR);
3794 case 59:
3795 ++this.pos;return this.finishToken(_tokentype.types.semi);
3796 case 44:
3797 ++this.pos;return this.finishToken(_tokentype.types.comma);
3798 case 91:
3799 ++this.pos;return this.finishToken(_tokentype.types.bracketL);
3800 case 93:
3801 ++this.pos;return this.finishToken(_tokentype.types.bracketR);
3802 case 123:
3803 ++this.pos;return this.finishToken(_tokentype.types.braceL);
3804 case 125:
3805 ++this.pos;return this.finishToken(_tokentype.types.braceR);
3806 case 58:
3807 ++this.pos;return this.finishToken(_tokentype.types.colon);
3808 case 63:
3809 ++this.pos;return this.finishToken(_tokentype.types.question);
3810
3811 case 96:
3812 // '`'
3813 if (this.options.ecmaVersion < 6) break;
3814 ++this.pos;
3815 return this.finishToken(_tokentype.types.backQuote);
3816
3817 case 48:
3818 // '0'
3819 var next = this.input.charCodeAt(this.pos + 1);
3820 if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
3821 if (this.options.ecmaVersion >= 6) {
3822 if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
3823 if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
3824 }
3825 // Anything else beginning with a digit is an integer, octal
3826 // number, or float.
3827 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
3828 // 1-9
3829 return this.readNumber(false);
3830
3831 // Quotes produce strings.
3832 case 34:case 39:
3833 // '"', "'"
3834 return this.readString(code);
3835
3836 // Operators are parsed inline in tiny state machines. '=' (61) is
3837 // often referred to. `finishOp` simply skips the amount of
3838 // characters it is given as second argument, and returns a token
3839 // of the type given by its first argument.
3840
3841 case 47:
3842 // '/'
3843 return this.readToken_slash();
3844
3845 case 37:case 42:
3846 // '%*'
3847 return this.readToken_mult_modulo(code);
3848
3849 case 124:case 38:
3850 // '|&'
3851 return this.readToken_pipe_amp(code);
3852
3853 case 94:
3854 // '^'
3855 return this.readToken_caret();
3856
3857 case 43:case 45:
3858 // '+-'
3859 return this.readToken_plus_min(code);
3860
3861 case 60:case 62:
3862 // '<>'
3863 return this.readToken_lt_gt(code);
3864
3865 case 61:case 33:
3866 // '=!'
3867 return this.readToken_eq_excl(code);
3868
3869 case 126:
3870 // '~'
3871 return this.finishOp(_tokentype.types.prefix, 1);
3872 }
3873
3874 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
3875};
3876
3877pp.finishOp = function (type, size) {
3878 var str = this.input.slice(this.pos, this.pos + size);
3879 this.pos += size;
3880 return this.finishToken(type, str);
3881};
3882
3883// Parse a regular expression. Some context-awareness is necessary,
3884// since a '/' inside a '[]' set does not end the expression.
3885
3886function tryCreateRegexp(src, flags, throwErrorAt, parser) {
3887 try {
3888 return new RegExp(src, flags);
3889 } catch (e) {
3890 if (throwErrorAt !== undefined) {
3891 if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
3892 throw e;
3893 }
3894 }
3895}
3896
3897var regexpUnicodeSupport = !!tryCreateRegexp("￿", "u");
3898
3899pp.readRegexp = function () {
3900 var _this = this;
3901
3902 var escaped = undefined,
3903 inClass = undefined,
3904 start = this.pos;
3905 for (;;) {
3906 if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
3907 var ch = this.input.charAt(this.pos);
3908 if (_whitespace.lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
3909 if (!escaped) {
3910 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;
3911 escaped = ch === "\\";
3912 } else escaped = false;
3913 ++this.pos;
3914 }
3915 var content = this.input.slice(start, this.pos);
3916 ++this.pos;
3917 // Need to use `readWord1` because '\uXXXX' sequences are allowed
3918 // here (don't ask).
3919 var mods = this.readWord1();
3920 var tmp = content;
3921 if (mods) {
3922 var validFlags = /^[gmsiy]*$/;
3923 if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
3924 if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
3925 if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
3926 // Replace each astral symbol and every Unicode escape sequence that
3927 // possibly represents an astral symbol or a paired surrogate with a
3928 // single ASCII symbol to avoid throwing on regular expressions that
3929 // are only valid in combination with the `/u` flag.
3930 // Note: replacing with the ASCII symbol `x` might cause false
3931 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
3932 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
3933 // be replaced by `[x-b]` which throws an error.
3934 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
3935 code = Number("0x" + code);
3936 if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
3937 return "x";
3938 });
3939 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
3940 }
3941 }
3942 // Detect invalid regular expressions.
3943 var value = null;
3944 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
3945 // so don't do detection if we are running under Rhino
3946 if (!isRhino) {
3947 tryCreateRegexp(tmp, undefined, start, this);
3948 // Get a regular expression object for this pattern-flag pair, or `null` in
3949 // case the current environment doesn't support the flags it uses.
3950 value = tryCreateRegexp(content, mods);
3951 }
3952 return this.finishToken(_tokentype.types.regexp, { pattern: content, flags: mods, value: value });
3953};
3954
3955// Read an integer in the given radix. Return null if zero digits
3956// were read, the integer value otherwise. When `len` is given, this
3957// will return `null` unless the integer has exactly `len` digits.
3958
3959pp.readInt = function (radix, len) {
3960 var start = this.pos,
3961 total = 0;
3962 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
3963 var code = this.input.charCodeAt(this.pos),
3964 val = undefined;
3965 if (code >= 97) val = code - 97 + 10; // a
3966 else if (code >= 65) val = code - 65 + 10; // A
3967 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
3968 else val = Infinity;
3969 if (val >= radix) break;
3970 ++this.pos;
3971 total = total * radix + val;
3972 }
3973 if (this.pos === start || len != null && this.pos - start !== len) return null;
3974
3975 return total;
3976};
3977
3978pp.readRadixNumber = function (radix) {
3979 this.pos += 2; // 0x
3980 var val = this.readInt(radix);
3981 if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
3982 if (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3983 return this.finishToken(_tokentype.types.num, val);
3984};
3985
3986// Read an integer, octal integer, or floating-point number.
3987
3988pp.readNumber = function (startsWithDot) {
3989 var start = this.pos,
3990 isFloat = false,
3991 octal = this.input.charCodeAt(this.pos) === 48;
3992 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
3993 var next = this.input.charCodeAt(this.pos);
3994 if (next === 46) {
3995 // '.'
3996 ++this.pos;
3997 this.readInt(10);
3998 isFloat = true;
3999 next = this.input.charCodeAt(this.pos);
4000 }
4001 if (next === 69 || next === 101) {
4002 // 'eE'
4003 next = this.input.charCodeAt(++this.pos);
4004 if (next === 43 || next === 45) ++this.pos; // '+-'
4005 if (this.readInt(10) === null) this.raise(start, "Invalid number");
4006 isFloat = true;
4007 }
4008 if (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
4009
4010 var str = this.input.slice(start, this.pos),
4011 val = undefined;
4012 if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number");else val = parseInt(str, 8);
4013 return this.finishToken(_tokentype.types.num, val);
4014};
4015
4016// Read a string value, interpreting backslash-escapes.
4017
4018pp.readCodePoint = function () {
4019 var ch = this.input.charCodeAt(this.pos),
4020 code = undefined;
4021
4022 if (ch === 123) {
4023 if (this.options.ecmaVersion < 6) this.unexpected();
4024 var codePos = ++this.pos;
4025 code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
4026 ++this.pos;
4027 if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
4028 } else {
4029 code = this.readHexChar(4);
4030 }
4031 return code;
4032};
4033
4034function codePointToString(code) {
4035 // UTF-16 Decoding
4036 if (code <= 0xFFFF) return String.fromCharCode(code);
4037 code -= 0x10000;
4038 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
4039}
4040
4041pp.readString = function (quote) {
4042 var out = "",
4043 chunkStart = ++this.pos;
4044 for (;;) {
4045 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
4046 var ch = this.input.charCodeAt(this.pos);
4047 if (ch === quote) break;
4048 if (ch === 92) {
4049 // '\'
4050 out += this.input.slice(chunkStart, this.pos);
4051 out += this.readEscapedChar(false);
4052 chunkStart = this.pos;
4053 } else {
4054 if (_whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
4055 ++this.pos;
4056 }
4057 }
4058 out += this.input.slice(chunkStart, this.pos++);
4059 return this.finishToken(_tokentype.types.string, out);
4060};
4061
4062// Reads template string tokens.
4063
4064pp.readTmplToken = function () {
4065 var out = "",
4066 chunkStart = this.pos;
4067 for (;;) {
4068 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
4069 var ch = this.input.charCodeAt(this.pos);
4070 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
4071 // '`', '${'
4072 if (this.pos === this.start && this.type === _tokentype.types.template) {
4073 if (ch === 36) {
4074 this.pos += 2;
4075 return this.finishToken(_tokentype.types.dollarBraceL);
4076 } else {
4077 ++this.pos;
4078 return this.finishToken(_tokentype.types.backQuote);
4079 }
4080 }
4081 out += this.input.slice(chunkStart, this.pos);
4082 return this.finishToken(_tokentype.types.template, out);
4083 }
4084 if (ch === 92) {
4085 // '\'
4086 out += this.input.slice(chunkStart, this.pos);
4087 out += this.readEscapedChar(true);
4088 chunkStart = this.pos;
4089 } else if (_whitespace.isNewLine(ch)) {
4090 out += this.input.slice(chunkStart, this.pos);
4091 ++this.pos;
4092 switch (ch) {
4093 case 13:
4094 if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
4095 case 10:
4096 out += "\n";
4097 break;
4098 default:
4099 out += String.fromCharCode(ch);
4100 break;
4101 }
4102 if (this.options.locations) {
4103 ++this.curLine;
4104 this.lineStart = this.pos;
4105 }
4106 chunkStart = this.pos;
4107 } else {
4108 ++this.pos;
4109 }
4110 }
4111};
4112
4113// Used to read escaped characters
4114
4115pp.readEscapedChar = function (inTemplate) {
4116 var ch = this.input.charCodeAt(++this.pos);
4117 ++this.pos;
4118 switch (ch) {
4119 case 110:
4120 return "\n"; // 'n' -> '\n'
4121 case 114:
4122 return "\r"; // 'r' -> '\r'
4123 case 120:
4124 return String.fromCharCode(this.readHexChar(2)); // 'x'
4125 case 117:
4126 return codePointToString(this.readCodePoint()); // 'u'
4127 case 116:
4128 return "\t"; // 't' -> '\t'
4129 case 98:
4130 return "\b"; // 'b' -> '\b'
4131 case 118:
4132 return "\u000b"; // 'v' -> '\u000b'
4133 case 102:
4134 return "\f"; // 'f' -> '\f'
4135 case 13:
4136 if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
4137 case 10:
4138 // ' \n'
4139 if (this.options.locations) {
4140 this.lineStart = this.pos;++this.curLine;
4141 }
4142 return "";
4143 default:
4144 if (ch >= 48 && ch <= 55) {
4145 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
4146 var octal = parseInt(octalStr, 8);
4147 if (octal > 255) {
4148 octalStr = octalStr.slice(0, -1);
4149 octal = parseInt(octalStr, 8);
4150 }
4151 if (octal > 0 && (this.strict || inTemplate)) {
4152 this.raise(this.pos - 2, "Octal literal in strict mode");
4153 }
4154 this.pos += octalStr.length - 1;
4155 return String.fromCharCode(octal);
4156 }
4157 return String.fromCharCode(ch);
4158 }
4159};
4160
4161// Used to read character escape sequences ('\x', '\u', '\U').
4162
4163pp.readHexChar = function (len) {
4164 var codePos = this.pos;
4165 var n = this.readInt(16, len);
4166 if (n === null) this.raise(codePos, "Bad character escape sequence");
4167 return n;
4168};
4169
4170// Read an identifier, and return it as a string. Sets `this.containsEsc`
4171// to whether the word contained a '\u' escape.
4172//
4173// Incrementally adds only escaped chars, adding other chunks as-is
4174// as a micro-optimization.
4175
4176pp.readWord1 = function () {
4177 this.containsEsc = false;
4178 var word = "",
4179 first = true,
4180 chunkStart = this.pos;
4181 var astral = this.options.ecmaVersion >= 6;
4182 while (this.pos < this.input.length) {
4183 var ch = this.fullCharCodeAtPos();
4184 if (_identifier.isIdentifierChar(ch, astral)) {
4185 this.pos += ch <= 0xffff ? 1 : 2;
4186 } else if (ch === 92) {
4187 // "\"
4188 this.containsEsc = true;
4189 word += this.input.slice(chunkStart, this.pos);
4190 var escStart = this.pos;
4191 if (this.input.charCodeAt(++this.pos) != 117) // "u"
4192 this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
4193 ++this.pos;
4194 var esc = this.readCodePoint();
4195 if (!(first ? _identifier.isIdentifierStart : _identifier.isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
4196 word += codePointToString(esc);
4197 chunkStart = this.pos;
4198 } else {
4199 break;
4200 }
4201 first = false;
4202 }
4203 return word + this.input.slice(chunkStart, this.pos);
4204};
4205
4206// Read an identifier or keyword token. Will check for reserved
4207// words when necessary.
4208
4209pp.readWord = function () {
4210 var word = this.readWord1();
4211 var type = _tokentype.types.name;
4212 if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = _tokentype.keywords[word];
4213 return this.finishToken(type, word);
4214};
4215
4216},{"./identifier":2,"./locutil":5,"./state":10,"./tokentype":14,"./whitespace":16}],14:[function(_dereq_,module,exports){
4217// ## Token types
4218
4219// The assignment of fine-grained, information-carrying type objects
4220// allows the tokenizer to store the information it has about a
4221// token in a way that is very cheap for the parser to look up.
4222
4223// All token type variables start with an underscore, to make them
4224// easy to recognize.
4225
4226// The `beforeExpr` property is used to disambiguate between regular
4227// expressions and divisions. It is set on all token types that can
4228// be followed by an expression (thus, a slash after them would be a
4229// regular expression).
4230//
4231// The `startsExpr` property is used to check if the token ends a
4232// `yield` expression. It is set on all token types that either can
4233// directly start an expression (like a quotation mark) or can
4234// continue an expression (like the body of a string).
4235//
4236// `isLoop` marks a keyword as starting a loop, which is important
4237// to know when parsing a label, in order to allow or disallow
4238// continue jumps to that label.
4239
4240"use strict";
4241
4242exports.__esModule = true;
4243
4244function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4245
4246var TokenType = function TokenType(label) {
4247 var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
4248
4249 _classCallCheck(this, TokenType);
4250
4251 this.label = label;
4252 this.keyword = conf.keyword;
4253 this.beforeExpr = !!conf.beforeExpr;
4254 this.startsExpr = !!conf.startsExpr;
4255 this.isLoop = !!conf.isLoop;
4256 this.isAssign = !!conf.isAssign;
4257 this.prefix = !!conf.prefix;
4258 this.postfix = !!conf.postfix;
4259 this.binop = conf.binop || null;
4260 this.updateContext = null;
4261};
4262
4263exports.TokenType = TokenType;
4264
4265function binop(name, prec) {
4266 return new TokenType(name, { beforeExpr: true, binop: prec });
4267}
4268var beforeExpr = { beforeExpr: true },
4269 startsExpr = { startsExpr: true };
4270
4271var types = {
4272 num: new TokenType("num", startsExpr),
4273 regexp: new TokenType("regexp", startsExpr),
4274 string: new TokenType("string", startsExpr),
4275 name: new TokenType("name", startsExpr),
4276 eof: new TokenType("eof"),
4277
4278 // Punctuation token types.
4279 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
4280 bracketR: new TokenType("]"),
4281 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
4282 braceR: new TokenType("}"),
4283 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
4284 parenR: new TokenType(")"),
4285 comma: new TokenType(",", beforeExpr),
4286 semi: new TokenType(";", beforeExpr),
4287 colon: new TokenType(":", beforeExpr),
4288 dot: new TokenType("."),
4289 question: new TokenType("?", beforeExpr),
4290 arrow: new TokenType("=>", beforeExpr),
4291 template: new TokenType("template"),
4292 ellipsis: new TokenType("...", beforeExpr),
4293 backQuote: new TokenType("`", startsExpr),
4294 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
4295
4296 // Operators. These carry several kinds of properties to help the
4297 // parser use them properly (the presence of these properties is
4298 // what categorizes them as operators).
4299 //
4300 // `binop`, when present, specifies that this operator is a binary
4301 // operator, and will refer to its precedence.
4302 //
4303 // `prefix` and `postfix` mark the operator as a prefix or postfix
4304 // unary operator.
4305 //
4306 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
4307 // binary operators with a very low precedence, that should result
4308 // in AssignmentExpression nodes.
4309
4310 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
4311 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
4312 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
4313 prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }),
4314 logicalOR: binop("||", 1),
4315 logicalAND: binop("&&", 2),
4316 bitwiseOR: binop("|", 3),
4317 bitwiseXOR: binop("^", 4),
4318 bitwiseAND: binop("&", 5),
4319 equality: binop("==/!=", 6),
4320 relational: binop("</>", 7),
4321 bitShift: binop("<</>>", 8),
4322 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
4323 modulo: binop("%", 10),
4324 star: binop("*", 10),
4325 slash: binop("/", 10)
4326};
4327
4328exports.types = types;
4329// Map keyword names to token types.
4330
4331var keywords = {};
4332
4333exports.keywords = keywords;
4334// Succinct definitions of keyword token types
4335function kw(name) {
4336 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
4337
4338 options.keyword = name;
4339 keywords[name] = types["_" + name] = new TokenType(name, options);
4340}
4341
4342kw("break");
4343kw("case", beforeExpr);
4344kw("catch");
4345kw("continue");
4346kw("debugger");
4347kw("default", beforeExpr);
4348kw("do", { isLoop: true, beforeExpr: true });
4349kw("else", beforeExpr);
4350kw("finally");
4351kw("for", { isLoop: true });
4352kw("function", startsExpr);
4353kw("if");
4354kw("return", beforeExpr);
4355kw("switch");
4356kw("throw", beforeExpr);
4357kw("try");
4358kw("var");
4359kw("let");
4360kw("const");
4361kw("while", { isLoop: true });
4362kw("with");
4363kw("new", { beforeExpr: true, startsExpr: true });
4364kw("this", startsExpr);
4365kw("super", startsExpr);
4366kw("class");
4367kw("extends", beforeExpr);
4368kw("export");
4369kw("import");
4370kw("yield", { beforeExpr: true, startsExpr: true });
4371kw("null", startsExpr);
4372kw("true", startsExpr);
4373kw("false", startsExpr);
4374kw("in", { beforeExpr: true, binop: 7 });
4375kw("instanceof", { beforeExpr: true, binop: 7 });
4376kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
4377kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
4378kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });
4379
4380},{}],15:[function(_dereq_,module,exports){
4381"use strict";
4382
4383exports.__esModule = true;
4384exports.isArray = isArray;
4385exports.has = has;
4386
4387function isArray(obj) {
4388 return Object.prototype.toString.call(obj) === "[object Array]";
4389}
4390
4391// Checks if an object has a property.
4392
4393function has(obj, propName) {
4394 return Object.prototype.hasOwnProperty.call(obj, propName);
4395}
4396
4397},{}],16:[function(_dereq_,module,exports){
4398// Matches a whole line break (where CRLF is considered a single
4399// line break). Used to count lines.
4400
4401"use strict";
4402
4403exports.__esModule = true;
4404exports.isNewLine = isNewLine;
4405var lineBreak = /\r\n?|\n|\u2028|\u2029/;
4406exports.lineBreak = lineBreak;
4407var lineBreakG = new RegExp(lineBreak.source, "g");
4408
4409exports.lineBreakG = lineBreakG;
4410
4411function isNewLine(code) {
4412 return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
4413}
4414
4415var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
4416exports.nonASCIIwhitespace = nonASCIIwhitespace;
4417
4418},{}]},{},[3])(3)
4419});
4420}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4421},{}],16:[function(_dereq_,module,exports){
4422
4423/**
4424 * Array#filter.
4425 *
4426 * @param {Array} arr
4427 * @param {Function} fn
4428 * @param {Object=} self
4429 * @return {Array}
4430 * @throw TypeError
4431 */
4432
4433module.exports = function (arr, fn, self) {
4434 if (arr.filter) return arr.filter(fn, self);
4435 if (void 0 === arr || null === arr) throw new TypeError;
4436 if ('function' != typeof fn) throw new TypeError;
4437 var ret = [];
4438 for (var i = 0; i < arr.length; i++) {
4439 if (!hasOwn.call(arr, i)) continue;
4440 var val = arr[i];
4441 if (fn.call(self, val, i, arr)) ret.push(val);
4442 }
4443 return ret;
4444};
4445
4446var hasOwn = Object.prototype.hasOwnProperty;
4447
4448},{}],17:[function(_dereq_,module,exports){
4449/**
4450 * array-foreach
4451 * Array#forEach ponyfill for older browsers
4452 * (Ponyfill: A polyfill that doesn't overwrite the native method)
4453 *
4454 * https://github.com/twada/array-foreach
4455 *
4456 * Copyright (c) 2015 Takuto Wada
4457 * Licensed under the MIT license.
4458 * http://twada.mit-license.org/
4459 */
4460'use strict';
4461
4462module.exports = function forEach (ary, callback, thisArg) {
4463 if (ary.forEach) {
4464 ary.forEach(callback, thisArg);
4465 return;
4466 }
4467 for (var i = 0; i < ary.length; i+=1) {
4468 callback.call(thisArg, ary[i], i, ary);
4469 }
4470};
4471
4472},{}],18:[function(_dereq_,module,exports){
4473module.exports = function (xs, f) {
4474 if (xs.map) return xs.map(f);
4475 var res = [];
4476 for (var i = 0; i < xs.length; i++) {
4477 var x = xs[i];
4478 if (hasOwn.call(xs, i)) res.push(f(x, i, xs));
4479 }
4480 return res;
4481};
4482
4483var hasOwn = Object.prototype.hasOwnProperty;
4484
4485},{}],19:[function(_dereq_,module,exports){
4486/**
4487 * array-reduce-right
4488 * Array#reduceRight ponyfill for older browsers
4489 * (Ponyfill: A polyfill that doesn't overwrite the native method)
4490 *
4491 * https://github.com/twada/array-reduce-right
4492 *
4493 * Copyright (c) 2015 Takuto Wada
4494 * Licensed under the MIT license.
4495 * http://twada.mit-license.org/
4496 */
4497'use strict';
4498
4499var slice = Array.prototype.slice;
4500
4501module.exports = function reduceRight (ary, callback /*, initialValue*/) {
4502 if (ary.reduceRight) {
4503 return ary.reduceRight.apply(ary, slice.apply(arguments).slice(1));
4504 }
4505 if ('function' !== typeof callback) {
4506 throw new TypeError(callback + ' is not a function');
4507 }
4508 var t = Object(ary), len = t.length >>> 0, k = len - 1, value;
4509 if (arguments.length >= 3) {
4510 value = arguments[2];
4511 } else {
4512 while (k >= 0 && !(k in t)) {
4513 k--;
4514 }
4515 if (k < 0) {
4516 throw new TypeError('Reduce of empty array with no initial value');
4517 }
4518 value = t[k--];
4519 }
4520 for (; k >= 0; k--) {
4521 if (k in t) {
4522 value = callback(value, t[k], k, t);
4523 }
4524 }
4525 return value;
4526};
4527
4528},{}],20:[function(_dereq_,module,exports){
4529var hasOwn = Object.prototype.hasOwnProperty;
4530
4531module.exports = function (xs, f, acc) {
4532 var hasAcc = arguments.length >= 3;
4533 if (hasAcc && xs.reduce) return xs.reduce(f, acc);
4534 if (xs.reduce) return xs.reduce(f);
4535
4536 for (var i = 0; i < xs.length; i++) {
4537 if (!hasOwn.call(xs, i)) continue;
4538 if (!hasAcc) {
4539 acc = xs[i];
4540 hasAcc = true;
4541 continue;
4542 }
4543 acc = f(acc, xs[i], i);
4544 }
4545 return acc;
4546};
4547
4548},{}],21:[function(_dereq_,module,exports){
4549var eaw = {};
4550
4551if ('undefined' == typeof module) {
4552 window.eastasianwidth = eaw;
4553} else {
4554 module.exports = eaw;
4555}
4556
4557eaw.eastAsianWidth = function(character) {
4558 var x = character.charCodeAt(0);
4559 var y = (character.length == 2) ? character.charCodeAt(1) : 0;
4560 var codePoint = x;
4561 if ((0xD800 <= x && x <= 0xDBFF) && (0xDC00 <= y && y <= 0xDFFF)) {
4562 x &= 0x3FF;
4563 y &= 0x3FF;
4564 codePoint = (x << 10) | y;
4565 codePoint += 0x10000;
4566 }
4567
4568 if ((0x3000 == codePoint) ||
4569 (0xFF01 <= codePoint && codePoint <= 0xFF60) ||
4570 (0xFFE0 <= codePoint && codePoint <= 0xFFE6)) {
4571 return 'F';
4572 }
4573 if ((0x20A9 == codePoint) ||
4574 (0xFF61 <= codePoint && codePoint <= 0xFFBE) ||
4575 (0xFFC2 <= codePoint && codePoint <= 0xFFC7) ||
4576 (0xFFCA <= codePoint && codePoint <= 0xFFCF) ||
4577 (0xFFD2 <= codePoint && codePoint <= 0xFFD7) ||
4578 (0xFFDA <= codePoint && codePoint <= 0xFFDC) ||
4579 (0xFFE8 <= codePoint && codePoint <= 0xFFEE)) {
4580 return 'H';
4581 }
4582 if ((0x1100 <= codePoint && codePoint <= 0x115F) ||
4583 (0x11A3 <= codePoint && codePoint <= 0x11A7) ||
4584 (0x11FA <= codePoint && codePoint <= 0x11FF) ||
4585 (0x2329 <= codePoint && codePoint <= 0x232A) ||
4586 (0x2E80 <= codePoint && codePoint <= 0x2E99) ||
4587 (0x2E9B <= codePoint && codePoint <= 0x2EF3) ||
4588 (0x2F00 <= codePoint && codePoint <= 0x2FD5) ||
4589 (0x2FF0 <= codePoint && codePoint <= 0x2FFB) ||
4590 (0x3001 <= codePoint && codePoint <= 0x303E) ||
4591 (0x3041 <= codePoint && codePoint <= 0x3096) ||
4592 (0x3099 <= codePoint && codePoint <= 0x30FF) ||
4593 (0x3105 <= codePoint && codePoint <= 0x312D) ||
4594 (0x3131 <= codePoint && codePoint <= 0x318E) ||
4595 (0x3190 <= codePoint && codePoint <= 0x31BA) ||
4596 (0x31C0 <= codePoint && codePoint <= 0x31E3) ||
4597 (0x31F0 <= codePoint && codePoint <= 0x321E) ||
4598 (0x3220 <= codePoint && codePoint <= 0x3247) ||
4599 (0x3250 <= codePoint && codePoint <= 0x32FE) ||
4600 (0x3300 <= codePoint && codePoint <= 0x4DBF) ||
4601 (0x4E00 <= codePoint && codePoint <= 0xA48C) ||
4602 (0xA490 <= codePoint && codePoint <= 0xA4C6) ||
4603 (0xA960 <= codePoint && codePoint <= 0xA97C) ||
4604 (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
4605 (0xD7B0 <= codePoint && codePoint <= 0xD7C6) ||
4606 (0xD7CB <= codePoint && codePoint <= 0xD7FB) ||
4607 (0xF900 <= codePoint && codePoint <= 0xFAFF) ||
4608 (0xFE10 <= codePoint && codePoint <= 0xFE19) ||
4609 (0xFE30 <= codePoint && codePoint <= 0xFE52) ||
4610 (0xFE54 <= codePoint && codePoint <= 0xFE66) ||
4611 (0xFE68 <= codePoint && codePoint <= 0xFE6B) ||
4612 (0x1B000 <= codePoint && codePoint <= 0x1B001) ||
4613 (0x1F200 <= codePoint && codePoint <= 0x1F202) ||
4614 (0x1F210 <= codePoint && codePoint <= 0x1F23A) ||
4615 (0x1F240 <= codePoint && codePoint <= 0x1F248) ||
4616 (0x1F250 <= codePoint && codePoint <= 0x1F251) ||
4617 (0x20000 <= codePoint && codePoint <= 0x2F73F) ||
4618 (0x2B740 <= codePoint && codePoint <= 0x2FFFD) ||
4619 (0x30000 <= codePoint && codePoint <= 0x3FFFD)) {
4620 return 'W';
4621 }
4622 if ((0x0020 <= codePoint && codePoint <= 0x007E) ||
4623 (0x00A2 <= codePoint && codePoint <= 0x00A3) ||
4624 (0x00A5 <= codePoint && codePoint <= 0x00A6) ||
4625 (0x00AC == codePoint) ||
4626 (0x00AF == codePoint) ||
4627 (0x27E6 <= codePoint && codePoint <= 0x27ED) ||
4628 (0x2985 <= codePoint && codePoint <= 0x2986)) {
4629 return 'Na';
4630 }
4631 if ((0x00A1 == codePoint) ||
4632 (0x00A4 == codePoint) ||
4633 (0x00A7 <= codePoint && codePoint <= 0x00A8) ||
4634 (0x00AA == codePoint) ||
4635 (0x00AD <= codePoint && codePoint <= 0x00AE) ||
4636 (0x00B0 <= codePoint && codePoint <= 0x00B4) ||
4637 (0x00B6 <= codePoint && codePoint <= 0x00BA) ||
4638 (0x00BC <= codePoint && codePoint <= 0x00BF) ||
4639 (0x00C6 == codePoint) ||
4640 (0x00D0 == codePoint) ||
4641 (0x00D7 <= codePoint && codePoint <= 0x00D8) ||
4642 (0x00DE <= codePoint && codePoint <= 0x00E1) ||
4643 (0x00E6 == codePoint) ||
4644 (0x00E8 <= codePoint && codePoint <= 0x00EA) ||
4645 (0x00EC <= codePoint && codePoint <= 0x00ED) ||
4646 (0x00F0 == codePoint) ||
4647 (0x00F2 <= codePoint && codePoint <= 0x00F3) ||
4648 (0x00F7 <= codePoint && codePoint <= 0x00FA) ||
4649 (0x00FC == codePoint) ||
4650 (0x00FE == codePoint) ||
4651 (0x0101 == codePoint) ||
4652 (0x0111 == codePoint) ||
4653 (0x0113 == codePoint) ||
4654 (0x011B == codePoint) ||
4655 (0x0126 <= codePoint && codePoint <= 0x0127) ||
4656 (0x012B == codePoint) ||
4657 (0x0131 <= codePoint && codePoint <= 0x0133) ||
4658 (0x0138 == codePoint) ||
4659 (0x013F <= codePoint && codePoint <= 0x0142) ||
4660 (0x0144 == codePoint) ||
4661 (0x0148 <= codePoint && codePoint <= 0x014B) ||
4662 (0x014D == codePoint) ||
4663 (0x0152 <= codePoint && codePoint <= 0x0153) ||
4664 (0x0166 <= codePoint && codePoint <= 0x0167) ||
4665 (0x016B == codePoint) ||
4666 (0x01CE == codePoint) ||
4667 (0x01D0 == codePoint) ||
4668 (0x01D2 == codePoint) ||
4669 (0x01D4 == codePoint) ||
4670 (0x01D6 == codePoint) ||
4671 (0x01D8 == codePoint) ||
4672 (0x01DA == codePoint) ||
4673 (0x01DC == codePoint) ||
4674 (0x0251 == codePoint) ||
4675 (0x0261 == codePoint) ||
4676 (0x02C4 == codePoint) ||
4677 (0x02C7 == codePoint) ||
4678 (0x02C9 <= codePoint && codePoint <= 0x02CB) ||
4679 (0x02CD == codePoint) ||
4680 (0x02D0 == codePoint) ||
4681 (0x02D8 <= codePoint && codePoint <= 0x02DB) ||
4682 (0x02DD == codePoint) ||
4683 (0x02DF == codePoint) ||
4684 (0x0300 <= codePoint && codePoint <= 0x036F) ||
4685 (0x0391 <= codePoint && codePoint <= 0x03A1) ||
4686 (0x03A3 <= codePoint && codePoint <= 0x03A9) ||
4687 (0x03B1 <= codePoint && codePoint <= 0x03C1) ||
4688 (0x03C3 <= codePoint && codePoint <= 0x03C9) ||
4689 (0x0401 == codePoint) ||
4690 (0x0410 <= codePoint && codePoint <= 0x044F) ||
4691 (0x0451 == codePoint) ||
4692 (0x2010 == codePoint) ||
4693 (0x2013 <= codePoint && codePoint <= 0x2016) ||
4694 (0x2018 <= codePoint && codePoint <= 0x2019) ||
4695 (0x201C <= codePoint && codePoint <= 0x201D) ||
4696 (0x2020 <= codePoint && codePoint <= 0x2022) ||
4697 (0x2024 <= codePoint && codePoint <= 0x2027) ||
4698 (0x2030 == codePoint) ||
4699 (0x2032 <= codePoint && codePoint <= 0x2033) ||
4700 (0x2035 == codePoint) ||
4701 (0x203B == codePoint) ||
4702 (0x203E == codePoint) ||
4703 (0x2074 == codePoint) ||
4704 (0x207F == codePoint) ||
4705 (0x2081 <= codePoint && codePoint <= 0x2084) ||
4706 (0x20AC == codePoint) ||
4707 (0x2103 == codePoint) ||
4708 (0x2105 == codePoint) ||
4709 (0x2109 == codePoint) ||
4710 (0x2113 == codePoint) ||
4711 (0x2116 == codePoint) ||
4712 (0x2121 <= codePoint && codePoint <= 0x2122) ||
4713 (0x2126 == codePoint) ||
4714 (0x212B == codePoint) ||
4715 (0x2153 <= codePoint && codePoint <= 0x2154) ||
4716 (0x215B <= codePoint && codePoint <= 0x215E) ||
4717 (0x2160 <= codePoint && codePoint <= 0x216B) ||
4718 (0x2170 <= codePoint && codePoint <= 0x2179) ||
4719 (0x2189 == codePoint) ||
4720 (0x2190 <= codePoint && codePoint <= 0x2199) ||
4721 (0x21B8 <= codePoint && codePoint <= 0x21B9) ||
4722 (0x21D2 == codePoint) ||
4723 (0x21D4 == codePoint) ||
4724 (0x21E7 == codePoint) ||
4725 (0x2200 == codePoint) ||
4726 (0x2202 <= codePoint && codePoint <= 0x2203) ||
4727 (0x2207 <= codePoint && codePoint <= 0x2208) ||
4728 (0x220B == codePoint) ||
4729 (0x220F == codePoint) ||
4730 (0x2211 == codePoint) ||
4731 (0x2215 == codePoint) ||
4732 (0x221A == codePoint) ||
4733 (0x221D <= codePoint && codePoint <= 0x2220) ||
4734 (0x2223 == codePoint) ||
4735 (0x2225 == codePoint) ||
4736 (0x2227 <= codePoint && codePoint <= 0x222C) ||
4737 (0x222E == codePoint) ||
4738 (0x2234 <= codePoint && codePoint <= 0x2237) ||
4739 (0x223C <= codePoint && codePoint <= 0x223D) ||
4740 (0x2248 == codePoint) ||
4741 (0x224C == codePoint) ||
4742 (0x2252 == codePoint) ||
4743 (0x2260 <= codePoint && codePoint <= 0x2261) ||
4744 (0x2264 <= codePoint && codePoint <= 0x2267) ||
4745 (0x226A <= codePoint && codePoint <= 0x226B) ||
4746 (0x226E <= codePoint && codePoint <= 0x226F) ||
4747 (0x2282 <= codePoint && codePoint <= 0x2283) ||
4748 (0x2286 <= codePoint && codePoint <= 0x2287) ||
4749 (0x2295 == codePoint) ||
4750 (0x2299 == codePoint) ||
4751 (0x22A5 == codePoint) ||
4752 (0x22BF == codePoint) ||
4753 (0x2312 == codePoint) ||
4754 (0x2460 <= codePoint && codePoint <= 0x24E9) ||
4755 (0x24EB <= codePoint && codePoint <= 0x254B) ||
4756 (0x2550 <= codePoint && codePoint <= 0x2573) ||
4757 (0x2580 <= codePoint && codePoint <= 0x258F) ||
4758 (0x2592 <= codePoint && codePoint <= 0x2595) ||
4759 (0x25A0 <= codePoint && codePoint <= 0x25A1) ||
4760 (0x25A3 <= codePoint && codePoint <= 0x25A9) ||
4761 (0x25B2 <= codePoint && codePoint <= 0x25B3) ||
4762 (0x25B6 <= codePoint && codePoint <= 0x25B7) ||
4763 (0x25BC <= codePoint && codePoint <= 0x25BD) ||
4764 (0x25C0 <= codePoint && codePoint <= 0x25C1) ||
4765 (0x25C6 <= codePoint && codePoint <= 0x25C8) ||
4766 (0x25CB == codePoint) ||
4767 (0x25CE <= codePoint && codePoint <= 0x25D1) ||
4768 (0x25E2 <= codePoint && codePoint <= 0x25E5) ||
4769 (0x25EF == codePoint) ||
4770 (0x2605 <= codePoint && codePoint <= 0x2606) ||
4771 (0x2609 == codePoint) ||
4772 (0x260E <= codePoint && codePoint <= 0x260F) ||
4773 (0x2614 <= codePoint && codePoint <= 0x2615) ||
4774 (0x261C == codePoint) ||
4775 (0x261E == codePoint) ||
4776 (0x2640 == codePoint) ||
4777 (0x2642 == codePoint) ||
4778 (0x2660 <= codePoint && codePoint <= 0x2661) ||
4779 (0x2663 <= codePoint && codePoint <= 0x2665) ||
4780 (0x2667 <= codePoint && codePoint <= 0x266A) ||
4781 (0x266C <= codePoint && codePoint <= 0x266D) ||
4782 (0x266F == codePoint) ||
4783 (0x269E <= codePoint && codePoint <= 0x269F) ||
4784 (0x26BE <= codePoint && codePoint <= 0x26BF) ||
4785 (0x26C4 <= codePoint && codePoint <= 0x26CD) ||
4786 (0x26CF <= codePoint && codePoint <= 0x26E1) ||
4787 (0x26E3 == codePoint) ||
4788 (0x26E8 <= codePoint && codePoint <= 0x26FF) ||
4789 (0x273D == codePoint) ||
4790 (0x2757 == codePoint) ||
4791 (0x2776 <= codePoint && codePoint <= 0x277F) ||
4792 (0x2B55 <= codePoint && codePoint <= 0x2B59) ||
4793 (0x3248 <= codePoint && codePoint <= 0x324F) ||
4794 (0xE000 <= codePoint && codePoint <= 0xF8FF) ||
4795 (0xFE00 <= codePoint && codePoint <= 0xFE0F) ||
4796 (0xFFFD == codePoint) ||
4797 (0x1F100 <= codePoint && codePoint <= 0x1F10A) ||
4798 (0x1F110 <= codePoint && codePoint <= 0x1F12D) ||
4799 (0x1F130 <= codePoint && codePoint <= 0x1F169) ||
4800 (0x1F170 <= codePoint && codePoint <= 0x1F19A) ||
4801 (0xE0100 <= codePoint && codePoint <= 0xE01EF) ||
4802 (0xF0000 <= codePoint && codePoint <= 0xFFFFD) ||
4803 (0x100000 <= codePoint && codePoint <= 0x10FFFD)) {
4804 return 'A';
4805 }
4806
4807 return 'N';
4808};
4809
4810eaw.characterLength = function(character) {
4811 var code = this.eastAsianWidth(character);
4812 if (code == 'F' || code == 'W' || code == 'A') {
4813 return 2;
4814 } else {
4815 return 1;
4816 }
4817};
4818
4819eaw.length = function(string) {
4820 var len = 0;
4821 for (var i = 0; i < string.length; i++) {
4822 len = len + this.characterLength(string.charAt(i));
4823 }
4824 return len;
4825};
4826
4827eaw.slice = function(text, start, end) {
4828 start = start ? start : 0;
4829 end = end ? end : 1;
4830 var result = '';
4831 for (var i = 0; i < text.length; i++) {
4832 var char = text.charAt(i);
4833 var eawLen = eaw.length(result + char);
4834 if (eawLen >= 1 + start && eawLen < 1 + end) {
4835 result += char
4836 }
4837 }
4838 return result;
4839};
4840
4841},{}],22:[function(_dereq_,module,exports){
4842/*
4843 Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
4844 Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
4845
4846 Redistribution and use in source and binary forms, with or without
4847 modification, are permitted provided that the following conditions are met:
4848
4849 * Redistributions of source code must retain the above copyright
4850 notice, this list of conditions and the following disclaimer.
4851 * Redistributions in binary form must reproduce the above copyright
4852 notice, this list of conditions and the following disclaimer in the
4853 documentation and/or other materials provided with the distribution.
4854
4855 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
4856 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4857 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4858 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
4859 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
4860 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
4861 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
4862 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4863 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
4864 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4865*/
4866/*jslint vars:false, bitwise:true*/
4867/*jshint indent:4*/
4868/*global exports:true*/
4869(function clone(exports) {
4870 'use strict';
4871
4872 var Syntax,
4873 isArray,
4874 VisitorOption,
4875 VisitorKeys,
4876 objectCreate,
4877 objectKeys,
4878 BREAK,
4879 SKIP,
4880 REMOVE;
4881
4882 function ignoreJSHintError() { }
4883
4884 isArray = Array.isArray;
4885 if (!isArray) {
4886 isArray = function isArray(array) {
4887 return Object.prototype.toString.call(array) === '[object Array]';
4888 };
4889 }
4890
4891 function deepCopy(obj) {
4892 var ret = {}, key, val;
4893 for (key in obj) {
4894 if (obj.hasOwnProperty(key)) {
4895 val = obj[key];
4896 if (typeof val === 'object' && val !== null) {
4897 ret[key] = deepCopy(val);
4898 } else {
4899 ret[key] = val;
4900 }
4901 }
4902 }
4903 return ret;
4904 }
4905
4906 function shallowCopy(obj) {
4907 var ret = {}, key;
4908 for (key in obj) {
4909 if (obj.hasOwnProperty(key)) {
4910 ret[key] = obj[key];
4911 }
4912 }
4913 return ret;
4914 }
4915 ignoreJSHintError(shallowCopy);
4916
4917 // based on LLVM libc++ upper_bound / lower_bound
4918 // MIT License
4919
4920 function upperBound(array, func) {
4921 var diff, len, i, current;
4922
4923 len = array.length;
4924 i = 0;
4925
4926 while (len) {
4927 diff = len >>> 1;
4928 current = i + diff;
4929 if (func(array[current])) {
4930 len = diff;
4931 } else {
4932 i = current + 1;
4933 len -= diff + 1;
4934 }
4935 }
4936 return i;
4937 }
4938
4939 function lowerBound(array, func) {
4940 var diff, len, i, current;
4941
4942 len = array.length;
4943 i = 0;
4944
4945 while (len) {
4946 diff = len >>> 1;
4947 current = i + diff;
4948 if (func(array[current])) {
4949 i = current + 1;
4950 len -= diff + 1;
4951 } else {
4952 len = diff;
4953 }
4954 }
4955 return i;
4956 }
4957 ignoreJSHintError(lowerBound);
4958
4959 objectCreate = Object.create || (function () {
4960 function F() { }
4961
4962 return function (o) {
4963 F.prototype = o;
4964 return new F();
4965 };
4966 })();
4967
4968 objectKeys = Object.keys || function (o) {
4969 var keys = [], key;
4970 for (key in o) {
4971 keys.push(key);
4972 }
4973 return keys;
4974 };
4975
4976 function extend(to, from) {
4977 var keys = objectKeys(from), key, i, len;
4978 for (i = 0, len = keys.length; i < len; i += 1) {
4979 key = keys[i];
4980 to[key] = from[key];
4981 }
4982 return to;
4983 }
4984
4985 Syntax = {
4986 AssignmentExpression: 'AssignmentExpression',
4987 AssignmentPattern: 'AssignmentPattern',
4988 ArrayExpression: 'ArrayExpression',
4989 ArrayPattern: 'ArrayPattern',
4990 ArrowFunctionExpression: 'ArrowFunctionExpression',
4991 AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
4992 BlockStatement: 'BlockStatement',
4993 BinaryExpression: 'BinaryExpression',
4994 BreakStatement: 'BreakStatement',
4995 CallExpression: 'CallExpression',
4996 CatchClause: 'CatchClause',
4997 ClassBody: 'ClassBody',
4998 ClassDeclaration: 'ClassDeclaration',
4999 ClassExpression: 'ClassExpression',
5000 ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
5001 ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
5002 ConditionalExpression: 'ConditionalExpression',
5003 ContinueStatement: 'ContinueStatement',
5004 DebuggerStatement: 'DebuggerStatement',
5005 DirectiveStatement: 'DirectiveStatement',
5006 DoWhileStatement: 'DoWhileStatement',
5007 EmptyStatement: 'EmptyStatement',
5008 ExportAllDeclaration: 'ExportAllDeclaration',
5009 ExportDefaultDeclaration: 'ExportDefaultDeclaration',
5010 ExportNamedDeclaration: 'ExportNamedDeclaration',
5011 ExportSpecifier: 'ExportSpecifier',
5012 ExpressionStatement: 'ExpressionStatement',
5013 ForStatement: 'ForStatement',
5014 ForInStatement: 'ForInStatement',
5015 ForOfStatement: 'ForOfStatement',
5016 FunctionDeclaration: 'FunctionDeclaration',
5017 FunctionExpression: 'FunctionExpression',
5018 GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
5019 Identifier: 'Identifier',
5020 IfStatement: 'IfStatement',
5021 ImportDeclaration: 'ImportDeclaration',
5022 ImportDefaultSpecifier: 'ImportDefaultSpecifier',
5023 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
5024 ImportSpecifier: 'ImportSpecifier',
5025 Literal: 'Literal',
5026 LabeledStatement: 'LabeledStatement',
5027 LogicalExpression: 'LogicalExpression',
5028 MemberExpression: 'MemberExpression',
5029 MetaProperty: 'MetaProperty',
5030 MethodDefinition: 'MethodDefinition',
5031 ModuleSpecifier: 'ModuleSpecifier',
5032 NewExpression: 'NewExpression',
5033 ObjectExpression: 'ObjectExpression',
5034 ObjectPattern: 'ObjectPattern',
5035 Program: 'Program',
5036 Property: 'Property',
5037 RestElement: 'RestElement',
5038 ReturnStatement: 'ReturnStatement',
5039 SequenceExpression: 'SequenceExpression',
5040 SpreadElement: 'SpreadElement',
5041 Super: 'Super',
5042 SwitchStatement: 'SwitchStatement',
5043 SwitchCase: 'SwitchCase',
5044 TaggedTemplateExpression: 'TaggedTemplateExpression',
5045 TemplateElement: 'TemplateElement',
5046 TemplateLiteral: 'TemplateLiteral',
5047 ThisExpression: 'ThisExpression',
5048 ThrowStatement: 'ThrowStatement',
5049 TryStatement: 'TryStatement',
5050 UnaryExpression: 'UnaryExpression',
5051 UpdateExpression: 'UpdateExpression',
5052 VariableDeclaration: 'VariableDeclaration',
5053 VariableDeclarator: 'VariableDeclarator',
5054 WhileStatement: 'WhileStatement',
5055 WithStatement: 'WithStatement',
5056 YieldExpression: 'YieldExpression'
5057 };
5058
5059 VisitorKeys = {
5060 AssignmentExpression: ['left', 'right'],
5061 AssignmentPattern: ['left', 'right'],
5062 ArrayExpression: ['elements'],
5063 ArrayPattern: ['elements'],
5064 ArrowFunctionExpression: ['params', 'body'],
5065 AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
5066 BlockStatement: ['body'],
5067 BinaryExpression: ['left', 'right'],
5068 BreakStatement: ['label'],
5069 CallExpression: ['callee', 'arguments'],
5070 CatchClause: ['param', 'body'],
5071 ClassBody: ['body'],
5072 ClassDeclaration: ['id', 'superClass', 'body'],
5073 ClassExpression: ['id', 'superClass', 'body'],
5074 ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
5075 ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
5076 ConditionalExpression: ['test', 'consequent', 'alternate'],
5077 ContinueStatement: ['label'],
5078 DebuggerStatement: [],
5079 DirectiveStatement: [],
5080 DoWhileStatement: ['body', 'test'],
5081 EmptyStatement: [],
5082 ExportAllDeclaration: ['source'],
5083 ExportDefaultDeclaration: ['declaration'],
5084 ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
5085 ExportSpecifier: ['exported', 'local'],
5086 ExpressionStatement: ['expression'],
5087 ForStatement: ['init', 'test', 'update', 'body'],
5088 ForInStatement: ['left', 'right', 'body'],
5089 ForOfStatement: ['left', 'right', 'body'],
5090 FunctionDeclaration: ['id', 'params', 'body'],
5091 FunctionExpression: ['id', 'params', 'body'],
5092 GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
5093 Identifier: [],
5094 IfStatement: ['test', 'consequent', 'alternate'],
5095 ImportDeclaration: ['specifiers', 'source'],
5096 ImportDefaultSpecifier: ['local'],
5097 ImportNamespaceSpecifier: ['local'],
5098 ImportSpecifier: ['imported', 'local'],
5099 Literal: [],
5100 LabeledStatement: ['label', 'body'],
5101 LogicalExpression: ['left', 'right'],
5102 MemberExpression: ['object', 'property'],
5103 MetaProperty: ['meta', 'property'],
5104 MethodDefinition: ['key', 'value'],
5105 ModuleSpecifier: [],
5106 NewExpression: ['callee', 'arguments'],
5107 ObjectExpression: ['properties'],
5108 ObjectPattern: ['properties'],
5109 Program: ['body'],
5110 Property: ['key', 'value'],
5111 RestElement: [ 'argument' ],
5112 ReturnStatement: ['argument'],
5113 SequenceExpression: ['expressions'],
5114 SpreadElement: ['argument'],
5115 Super: [],
5116 SwitchStatement: ['discriminant', 'cases'],
5117 SwitchCase: ['test', 'consequent'],
5118 TaggedTemplateExpression: ['tag', 'quasi'],
5119 TemplateElement: [],
5120 TemplateLiteral: ['quasis', 'expressions'],
5121 ThisExpression: [],
5122 ThrowStatement: ['argument'],
5123 TryStatement: ['block', 'handler', 'finalizer'],
5124 UnaryExpression: ['argument'],
5125 UpdateExpression: ['argument'],
5126 VariableDeclaration: ['declarations'],
5127 VariableDeclarator: ['id', 'init'],
5128 WhileStatement: ['test', 'body'],
5129 WithStatement: ['object', 'body'],
5130 YieldExpression: ['argument']
5131 };
5132
5133 // unique id
5134 BREAK = {};
5135 SKIP = {};
5136 REMOVE = {};
5137
5138 VisitorOption = {
5139 Break: BREAK,
5140 Skip: SKIP,
5141 Remove: REMOVE
5142 };
5143
5144 function Reference(parent, key) {
5145 this.parent = parent;
5146 this.key = key;
5147 }
5148
5149 Reference.prototype.replace = function replace(node) {
5150 this.parent[this.key] = node;
5151 };
5152
5153 Reference.prototype.remove = function remove() {
5154 if (isArray(this.parent)) {
5155 this.parent.splice(this.key, 1);
5156 return true;
5157 } else {
5158 this.replace(null);
5159 return false;
5160 }
5161 };
5162
5163 function Element(node, path, wrap, ref) {
5164 this.node = node;
5165 this.path = path;
5166 this.wrap = wrap;
5167 this.ref = ref;
5168 }
5169
5170 function Controller() { }
5171
5172 // API:
5173 // return property path array from root to current node
5174 Controller.prototype.path = function path() {
5175 var i, iz, j, jz, result, element;
5176
5177 function addToPath(result, path) {
5178 if (isArray(path)) {
5179 for (j = 0, jz = path.length; j < jz; ++j) {
5180 result.push(path[j]);
5181 }
5182 } else {
5183 result.push(path);
5184 }
5185 }
5186
5187 // root node
5188 if (!this.__current.path) {
5189 return null;
5190 }
5191
5192 // first node is sentinel, second node is root element
5193 result = [];
5194 for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
5195 element = this.__leavelist[i];
5196 addToPath(result, element.path);
5197 }
5198 addToPath(result, this.__current.path);
5199 return result;
5200 };
5201
5202 // API:
5203 // return type of current node
5204 Controller.prototype.type = function () {
5205 var node = this.current();
5206 return node.type || this.__current.wrap;
5207 };
5208
5209 // API:
5210 // return array of parent elements
5211 Controller.prototype.parents = function parents() {
5212 var i, iz, result;
5213
5214 // first node is sentinel
5215 result = [];
5216 for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
5217 result.push(this.__leavelist[i].node);
5218 }
5219
5220 return result;
5221 };
5222
5223 // API:
5224 // return current node
5225 Controller.prototype.current = function current() {
5226 return this.__current.node;
5227 };
5228
5229 Controller.prototype.__execute = function __execute(callback, element) {
5230 var previous, result;
5231
5232 result = undefined;
5233
5234 previous = this.__current;
5235 this.__current = element;
5236 this.__state = null;
5237 if (callback) {
5238 result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
5239 }
5240 this.__current = previous;
5241
5242 return result;
5243 };
5244
5245 // API:
5246 // notify control skip / break
5247 Controller.prototype.notify = function notify(flag) {
5248 this.__state = flag;
5249 };
5250
5251 // API:
5252 // skip child nodes of current node
5253 Controller.prototype.skip = function () {
5254 this.notify(SKIP);
5255 };
5256
5257 // API:
5258 // break traversals
5259 Controller.prototype['break'] = function () {
5260 this.notify(BREAK);
5261 };
5262
5263 // API:
5264 // remove node
5265 Controller.prototype.remove = function () {
5266 this.notify(REMOVE);
5267 };
5268
5269 Controller.prototype.__initialize = function(root, visitor) {
5270 this.visitor = visitor;
5271 this.root = root;
5272 this.__worklist = [];
5273 this.__leavelist = [];
5274 this.__current = null;
5275 this.__state = null;
5276 this.__fallback = visitor.fallback === 'iteration';
5277 this.__keys = VisitorKeys;
5278 if (visitor.keys) {
5279 this.__keys = extend(objectCreate(this.__keys), visitor.keys);
5280 }
5281 };
5282
5283 function isNode(node) {
5284 if (node == null) {
5285 return false;
5286 }
5287 return typeof node === 'object' && typeof node.type === 'string';
5288 }
5289
5290 function isProperty(nodeType, key) {
5291 return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
5292 }
5293
5294 Controller.prototype.traverse = function traverse(root, visitor) {
5295 var worklist,
5296 leavelist,
5297 element,
5298 node,
5299 nodeType,
5300 ret,
5301 key,
5302 current,
5303 current2,
5304 candidates,
5305 candidate,
5306 sentinel;
5307
5308 this.__initialize(root, visitor);
5309
5310 sentinel = {};
5311
5312 // reference
5313 worklist = this.__worklist;
5314 leavelist = this.__leavelist;
5315
5316 // initialize
5317 worklist.push(new Element(root, null, null, null));
5318 leavelist.push(new Element(null, null, null, null));
5319
5320 while (worklist.length) {
5321 element = worklist.pop();
5322
5323 if (element === sentinel) {
5324 element = leavelist.pop();
5325
5326 ret = this.__execute(visitor.leave, element);
5327
5328 if (this.__state === BREAK || ret === BREAK) {
5329 return;
5330 }
5331 continue;
5332 }
5333
5334 if (element.node) {
5335
5336 ret = this.__execute(visitor.enter, element);
5337
5338 if (this.__state === BREAK || ret === BREAK) {
5339 return;
5340 }
5341
5342 worklist.push(sentinel);
5343 leavelist.push(element);
5344
5345 if (this.__state === SKIP || ret === SKIP) {
5346 continue;
5347 }
5348
5349 node = element.node;
5350 nodeType = node.type || element.wrap;
5351 candidates = this.__keys[nodeType];
5352 if (!candidates) {
5353 if (this.__fallback) {
5354 candidates = objectKeys(node);
5355 } else {
5356 throw new Error('Unknown node type ' + nodeType + '.');
5357 }
5358 }
5359
5360 current = candidates.length;
5361 while ((current -= 1) >= 0) {
5362 key = candidates[current];
5363 candidate = node[key];
5364 if (!candidate) {
5365 continue;
5366 }
5367
5368 if (isArray(candidate)) {
5369 current2 = candidate.length;
5370 while ((current2 -= 1) >= 0) {
5371 if (!candidate[current2]) {
5372 continue;
5373 }
5374 if (isProperty(nodeType, candidates[current])) {
5375 element = new Element(candidate[current2], [key, current2], 'Property', null);
5376 } else if (isNode(candidate[current2])) {
5377 element = new Element(candidate[current2], [key, current2], null, null);
5378 } else {
5379 continue;
5380 }
5381 worklist.push(element);
5382 }
5383 } else if (isNode(candidate)) {
5384 worklist.push(new Element(candidate, key, null, null));
5385 }
5386 }
5387 }
5388 }
5389 };
5390
5391 Controller.prototype.replace = function replace(root, visitor) {
5392 function removeElem(element) {
5393 var i,
5394 key,
5395 nextElem,
5396 parent;
5397
5398 if (element.ref.remove()) {
5399 // When the reference is an element of an array.
5400 key = element.ref.key;
5401 parent = element.ref.parent;
5402
5403 // If removed from array, then decrease following items' keys.
5404 i = worklist.length;
5405 while (i--) {
5406 nextElem = worklist[i];
5407 if (nextElem.ref && nextElem.ref.parent === parent) {
5408 if (nextElem.ref.key < key) {
5409 break;
5410 }
5411 --nextElem.ref.key;
5412 }
5413 }
5414 }
5415 }
5416
5417 var worklist,
5418 leavelist,
5419 node,
5420 nodeType,
5421 target,
5422 element,
5423 current,
5424 current2,
5425 candidates,
5426 candidate,
5427 sentinel,
5428 outer,
5429 key;
5430
5431 this.__initialize(root, visitor);
5432
5433 sentinel = {};
5434
5435 // reference
5436 worklist = this.__worklist;
5437 leavelist = this.__leavelist;
5438
5439 // initialize
5440 outer = {
5441 root: root
5442 };
5443 element = new Element(root, null, null, new Reference(outer, 'root'));
5444 worklist.push(element);
5445 leavelist.push(element);
5446
5447 while (worklist.length) {
5448 element = worklist.pop();
5449
5450 if (element === sentinel) {
5451 element = leavelist.pop();
5452
5453 target = this.__execute(visitor.leave, element);
5454
5455 // node may be replaced with null,
5456 // so distinguish between undefined and null in this place
5457 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
5458 // replace
5459 element.ref.replace(target);
5460 }
5461
5462 if (this.__state === REMOVE || target === REMOVE) {
5463 removeElem(element);
5464 }
5465
5466 if (this.__state === BREAK || target === BREAK) {
5467 return outer.root;
5468 }
5469 continue;
5470 }
5471
5472 target = this.__execute(visitor.enter, element);
5473
5474 // node may be replaced with null,
5475 // so distinguish between undefined and null in this place
5476 if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
5477 // replace
5478 element.ref.replace(target);
5479 element.node = target;
5480 }
5481
5482 if (this.__state === REMOVE || target === REMOVE) {
5483 removeElem(element);
5484 element.node = null;
5485 }
5486
5487 if (this.__state === BREAK || target === BREAK) {
5488 return outer.root;
5489 }
5490
5491 // node may be null
5492 node = element.node;
5493 if (!node) {
5494 continue;
5495 }
5496
5497 worklist.push(sentinel);
5498 leavelist.push(element);
5499
5500 if (this.__state === SKIP || target === SKIP) {
5501 continue;
5502 }
5503
5504 nodeType = node.type || element.wrap;
5505 candidates = this.__keys[nodeType];
5506 if (!candidates) {
5507 if (this.__fallback) {
5508 candidates = objectKeys(node);
5509 } else {
5510 throw new Error('Unknown node type ' + nodeType + '.');
5511 }
5512 }
5513
5514 current = candidates.length;
5515 while ((current -= 1) >= 0) {
5516 key = candidates[current];
5517 candidate = node[key];
5518 if (!candidate) {
5519 continue;
5520 }
5521
5522 if (isArray(candidate)) {
5523 current2 = candidate.length;
5524 while ((current2 -= 1) >= 0) {
5525 if (!candidate[current2]) {
5526 continue;
5527 }
5528 if (isProperty(nodeType, candidates[current])) {
5529 element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
5530 } else if (isNode(candidate[current2])) {
5531 element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
5532 } else {
5533 continue;
5534 }
5535 worklist.push(element);
5536 }
5537 } else if (isNode(candidate)) {
5538 worklist.push(new Element(candidate, key, null, new Reference(node, key)));
5539 }
5540 }
5541 }
5542
5543 return outer.root;
5544 };
5545
5546 function traverse(root, visitor) {
5547 var controller = new Controller();
5548 return controller.traverse(root, visitor);
5549 }
5550
5551 function replace(root, visitor) {
5552 var controller = new Controller();
5553 return controller.replace(root, visitor);
5554 }
5555
5556 function extendCommentRange(comment, tokens) {
5557 var target;
5558
5559 target = upperBound(tokens, function search(token) {
5560 return token.range[0] > comment.range[0];
5561 });
5562
5563 comment.extendedRange = [comment.range[0], comment.range[1]];
5564
5565 if (target !== tokens.length) {
5566 comment.extendedRange[1] = tokens[target].range[0];
5567 }
5568
5569 target -= 1;
5570 if (target >= 0) {
5571 comment.extendedRange[0] = tokens[target].range[1];
5572 }
5573
5574 return comment;
5575 }
5576
5577 function attachComments(tree, providedComments, tokens) {
5578 // At first, we should calculate extended comment ranges.
5579 var comments = [], comment, len, i, cursor;
5580
5581 if (!tree.range) {
5582 throw new Error('attachComments needs range information');
5583 }
5584
5585 // tokens array is empty, we attach comments to tree as 'leadingComments'
5586 if (!tokens.length) {
5587 if (providedComments.length) {
5588 for (i = 0, len = providedComments.length; i < len; i += 1) {
5589 comment = deepCopy(providedComments[i]);
5590 comment.extendedRange = [0, tree.range[0]];
5591 comments.push(comment);
5592 }
5593 tree.leadingComments = comments;
5594 }
5595 return tree;
5596 }
5597
5598 for (i = 0, len = providedComments.length; i < len; i += 1) {
5599 comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
5600 }
5601
5602 // This is based on John Freeman's implementation.
5603 cursor = 0;
5604 traverse(tree, {
5605 enter: function (node) {
5606 var comment;
5607
5608 while (cursor < comments.length) {
5609 comment = comments[cursor];
5610 if (comment.extendedRange[1] > node.range[0]) {
5611 break;
5612 }
5613
5614 if (comment.extendedRange[1] === node.range[0]) {
5615 if (!node.leadingComments) {
5616 node.leadingComments = [];
5617 }
5618 node.leadingComments.push(comment);
5619 comments.splice(cursor, 1);
5620 } else {
5621 cursor += 1;
5622 }
5623 }
5624
5625 // already out of owned node
5626 if (cursor === comments.length) {
5627 return VisitorOption.Break;
5628 }
5629
5630 if (comments[cursor].extendedRange[0] > node.range[1]) {
5631 return VisitorOption.Skip;
5632 }
5633 }
5634 });
5635
5636 cursor = 0;
5637 traverse(tree, {
5638 leave: function (node) {
5639 var comment;
5640
5641 while (cursor < comments.length) {
5642 comment = comments[cursor];
5643 if (node.range[1] < comment.extendedRange[0]) {
5644 break;
5645 }
5646
5647 if (node.range[1] === comment.extendedRange[0]) {
5648 if (!node.trailingComments) {
5649 node.trailingComments = [];
5650 }
5651 node.trailingComments.push(comment);
5652 comments.splice(cursor, 1);
5653 } else {
5654 cursor += 1;
5655 }
5656 }
5657
5658 // already out of owned node
5659 if (cursor === comments.length) {
5660 return VisitorOption.Break;
5661 }
5662
5663 if (comments[cursor].extendedRange[0] > node.range[1]) {
5664 return VisitorOption.Skip;
5665 }
5666 }
5667 });
5668
5669 return tree;
5670 }
5671
5672 exports.version = _dereq_('./package.json').version;
5673 exports.Syntax = Syntax;
5674 exports.traverse = traverse;
5675 exports.replace = replace;
5676 exports.attachComments = attachComments;
5677 exports.VisitorKeys = VisitorKeys;
5678 exports.VisitorOption = VisitorOption;
5679 exports.Controller = Controller;
5680 exports.cloneEnvironment = function () { return clone({}); };
5681
5682 return exports;
5683}(exports));
5684/* vim: set sw=4 ts=4 et tw=80 : */
5685
5686},{"./package.json":23}],23:[function(_dereq_,module,exports){
5687module.exports={
5688 "_args": [
5689 [
5690 "estraverse@^4.1.0",
5691 "/Users/takuto/src/github.com/power-assert-js/power-assert-formatter"
5692 ]
5693 ],
5694 "_from": "estraverse@>=4.1.0 <5.0.0",
5695 "_id": "estraverse@4.1.1",
5696 "_inCache": true,
5697 "_installable": true,
5698 "_location": "/estraverse",
5699 "_nodeVersion": "4.1.1",
5700 "_npmUser": {
5701 "email": "utatane.tea@gmail.com",
5702 "name": "constellation"
5703 },
5704 "_npmVersion": "2.14.4",
5705 "_phantomChildren": {},
5706 "_requested": {
5707 "name": "estraverse",
5708 "raw": "estraverse@^4.1.0",
5709 "rawSpec": "^4.1.0",
5710 "scope": null,
5711 "spec": ">=4.1.0 <5.0.0",
5712 "type": "range"
5713 },
5714 "_requiredBy": [
5715 "/",
5716 "/escallmatch",
5717 "/espower",
5718 "/esrecurse"
5719 ],
5720 "_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.1.1.tgz",
5721 "_shasum": "f6caca728933a850ef90661d0e17982ba47111a2",
5722 "_shrinkwrap": null,
5723 "_spec": "estraverse@^4.1.0",
5724 "_where": "/Users/takuto/src/github.com/power-assert-js/power-assert-formatter",
5725 "bugs": {
5726 "url": "https://github.com/estools/estraverse/issues"
5727 },
5728 "dependencies": {},
5729 "description": "ECMAScript JS AST traversal functions",
5730 "devDependencies": {
5731 "chai": "^2.1.1",
5732 "coffee-script": "^1.8.0",
5733 "espree": "^1.11.0",
5734 "gulp": "^3.8.10",
5735 "gulp-bump": "^0.2.2",
5736 "gulp-filter": "^2.0.0",
5737 "gulp-git": "^1.0.1",
5738 "gulp-tag-version": "^1.2.1",
5739 "jshint": "^2.5.6",
5740 "mocha": "^2.1.0"
5741 },
5742 "directories": {},
5743 "dist": {
5744 "shasum": "f6caca728933a850ef90661d0e17982ba47111a2",
5745 "tarball": "http://registry.npmjs.org/estraverse/-/estraverse-4.1.1.tgz"
5746 },
5747 "engines": {
5748 "node": ">=0.10.0"
5749 },
5750 "gitHead": "bbcccbfe98296585e4311c8755e1d00dcd581e3c",
5751 "homepage": "https://github.com/estools/estraverse",
5752 "license": "BSD-2-Clause",
5753 "main": "estraverse.js",
5754 "maintainers": [
5755 {
5756 "name": "constellation",
5757 "email": "utatane.tea@gmail.com"
5758 },
5759 {
5760 "name": "michaelficarra",
5761 "email": "npm@michael.ficarra.me"
5762 },
5763 {
5764 "name": "nzakas",
5765 "email": "nicholas@nczconsulting.com"
5766 }
5767 ],
5768 "name": "estraverse",
5769 "optionalDependencies": {},
5770 "readme": "ERROR: No README data found!",
5771 "repository": {
5772 "type": "git",
5773 "url": "git+ssh://git@github.com/estools/estraverse.git"
5774 },
5775 "scripts": {
5776 "lint": "jshint estraverse.js",
5777 "test": "npm run-script lint && npm run-script unit-test",
5778 "unit-test": "mocha --compilers coffee:coffee-script/register"
5779 },
5780 "version": "4.1.1"
5781}
5782
5783},{}],24:[function(_dereq_,module,exports){
5784// Copyright Joyent, Inc. and other Node contributors.
5785//
5786// Permission is hereby granted, free of charge, to any person obtaining a
5787// copy of this software and associated documentation files (the
5788// "Software"), to deal in the Software without restriction, including
5789// without limitation the rights to use, copy, modify, merge, publish,
5790// distribute, sublicense, and/or sell copies of the Software, and to permit
5791// persons to whom the Software is furnished to do so, subject to the
5792// following conditions:
5793//
5794// The above copyright notice and this permission notice shall be included
5795// in all copies or substantial portions of the Software.
5796//
5797// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5798// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5799// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5800// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5801// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5802// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5803// USE OR OTHER DEALINGS IN THE SOFTWARE.
5804
5805function EventEmitter() {
5806 this._events = this._events || {};
5807 this._maxListeners = this._maxListeners || undefined;
5808}
5809module.exports = EventEmitter;
5810
5811// Backwards-compat with node 0.10.x
5812EventEmitter.EventEmitter = EventEmitter;
5813
5814EventEmitter.prototype._events = undefined;
5815EventEmitter.prototype._maxListeners = undefined;
5816
5817// By default EventEmitters will print a warning if more than 10 listeners are
5818// added to it. This is a useful default which helps finding memory leaks.
5819EventEmitter.defaultMaxListeners = 10;
5820
5821// Obviously not all Emitters should be limited to 10. This function allows
5822// that to be increased. Set to zero for unlimited.
5823EventEmitter.prototype.setMaxListeners = function(n) {
5824 if (!isNumber(n) || n < 0 || isNaN(n))
5825 throw TypeError('n must be a positive number');
5826 this._maxListeners = n;
5827 return this;
5828};
5829
5830EventEmitter.prototype.emit = function(type) {
5831 var er, handler, len, args, i, listeners;
5832
5833 if (!this._events)
5834 this._events = {};
5835
5836 // If there is no 'error' event listener then throw.
5837 if (type === 'error') {
5838 if (!this._events.error ||
5839 (isObject(this._events.error) && !this._events.error.length)) {
5840 er = arguments[1];
5841 if (er instanceof Error) {
5842 throw er; // Unhandled 'error' event
5843 }
5844 throw TypeError('Uncaught, unspecified "error" event.');
5845 }
5846 }
5847
5848 handler = this._events[type];
5849
5850 if (isUndefined(handler))
5851 return false;
5852
5853 if (isFunction(handler)) {
5854 switch (arguments.length) {
5855 // fast cases
5856 case 1:
5857 handler.call(this);
5858 break;
5859 case 2:
5860 handler.call(this, arguments[1]);
5861 break;
5862 case 3:
5863 handler.call(this, arguments[1], arguments[2]);
5864 break;
5865 // slower
5866 default:
5867 len = arguments.length;
5868 args = new Array(len - 1);
5869 for (i = 1; i < len; i++)
5870 args[i - 1] = arguments[i];
5871 handler.apply(this, args);
5872 }
5873 } else if (isObject(handler)) {
5874 len = arguments.length;
5875 args = new Array(len - 1);
5876 for (i = 1; i < len; i++)
5877 args[i - 1] = arguments[i];
5878
5879 listeners = handler.slice();
5880 len = listeners.length;
5881 for (i = 0; i < len; i++)
5882 listeners[i].apply(this, args);
5883 }
5884
5885 return true;
5886};
5887
5888EventEmitter.prototype.addListener = function(type, listener) {
5889 var m;
5890
5891 if (!isFunction(listener))
5892 throw TypeError('listener must be a function');
5893
5894 if (!this._events)
5895 this._events = {};
5896
5897 // To avoid recursion in the case that type === "newListener"! Before
5898 // adding it to the listeners, first emit "newListener".
5899 if (this._events.newListener)
5900 this.emit('newListener', type,
5901 isFunction(listener.listener) ?
5902 listener.listener : listener);
5903
5904 if (!this._events[type])
5905 // Optimize the case of one listener. Don't need the extra array object.
5906 this._events[type] = listener;
5907 else if (isObject(this._events[type]))
5908 // If we've already got an array, just append.
5909 this._events[type].push(listener);
5910 else
5911 // Adding the second element, need to change to array.
5912 this._events[type] = [this._events[type], listener];
5913
5914 // Check for listener leak
5915 if (isObject(this._events[type]) && !this._events[type].warned) {
5916 var m;
5917 if (!isUndefined(this._maxListeners)) {
5918 m = this._maxListeners;
5919 } else {
5920 m = EventEmitter.defaultMaxListeners;
5921 }
5922
5923 if (m && m > 0 && this._events[type].length > m) {
5924 this._events[type].warned = true;
5925 console.error('(node) warning: possible EventEmitter memory ' +
5926 'leak detected. %d listeners added. ' +
5927 'Use emitter.setMaxListeners() to increase limit.',
5928 this._events[type].length);
5929 if (typeof console.trace === 'function') {
5930 // not supported in IE 10
5931 console.trace();
5932 }
5933 }
5934 }
5935
5936 return this;
5937};
5938
5939EventEmitter.prototype.on = EventEmitter.prototype.addListener;
5940
5941EventEmitter.prototype.once = function(type, listener) {
5942 if (!isFunction(listener))
5943 throw TypeError('listener must be a function');
5944
5945 var fired = false;
5946
5947 function g() {
5948 this.removeListener(type, g);
5949
5950 if (!fired) {
5951 fired = true;
5952 listener.apply(this, arguments);
5953 }
5954 }
5955
5956 g.listener = listener;
5957 this.on(type, g);
5958
5959 return this;
5960};
5961
5962// emits a 'removeListener' event iff the listener was removed
5963EventEmitter.prototype.removeListener = function(type, listener) {
5964 var list, position, length, i;
5965
5966 if (!isFunction(listener))
5967 throw TypeError('listener must be a function');
5968
5969 if (!this._events || !this._events[type])
5970 return this;
5971
5972 list = this._events[type];
5973 length = list.length;
5974 position = -1;
5975
5976 if (list === listener ||
5977 (isFunction(list.listener) && list.listener === listener)) {
5978 delete this._events[type];
5979 if (this._events.removeListener)
5980 this.emit('removeListener', type, listener);
5981
5982 } else if (isObject(list)) {
5983 for (i = length; i-- > 0;) {
5984 if (list[i] === listener ||
5985 (list[i].listener && list[i].listener === listener)) {
5986 position = i;
5987 break;
5988 }
5989 }
5990
5991 if (position < 0)
5992 return this;
5993
5994 if (list.length === 1) {
5995 list.length = 0;
5996 delete this._events[type];
5997 } else {
5998 list.splice(position, 1);
5999 }
6000
6001 if (this._events.removeListener)
6002 this.emit('removeListener', type, listener);
6003 }
6004
6005 return this;
6006};
6007
6008EventEmitter.prototype.removeAllListeners = function(type) {
6009 var key, listeners;
6010
6011 if (!this._events)
6012 return this;
6013
6014 // not listening for removeListener, no need to emit
6015 if (!this._events.removeListener) {
6016 if (arguments.length === 0)
6017 this._events = {};
6018 else if (this._events[type])
6019 delete this._events[type];
6020 return this;
6021 }
6022
6023 // emit removeListener for all listeners on all events
6024 if (arguments.length === 0) {
6025 for (key in this._events) {
6026 if (key === 'removeListener') continue;
6027 this.removeAllListeners(key);
6028 }
6029 this.removeAllListeners('removeListener');
6030 this._events = {};
6031 return this;
6032 }
6033
6034 listeners = this._events[type];
6035
6036 if (isFunction(listeners)) {
6037 this.removeListener(type, listeners);
6038 } else {
6039 // LIFO order
6040 while (listeners.length)
6041 this.removeListener(type, listeners[listeners.length - 1]);
6042 }
6043 delete this._events[type];
6044
6045 return this;
6046};
6047
6048EventEmitter.prototype.listeners = function(type) {
6049 var ret;
6050 if (!this._events || !this._events[type])
6051 ret = [];
6052 else if (isFunction(this._events[type]))
6053 ret = [this._events[type]];
6054 else
6055 ret = this._events[type].slice();
6056 return ret;
6057};
6058
6059EventEmitter.listenerCount = function(emitter, type) {
6060 var ret;
6061 if (!emitter._events || !emitter._events[type])
6062 ret = 0;
6063 else if (isFunction(emitter._events[type]))
6064 ret = 1;
6065 else
6066 ret = emitter._events[type].length;
6067 return ret;
6068};
6069
6070function isFunction(arg) {
6071 return typeof arg === 'function';
6072}
6073
6074function isNumber(arg) {
6075 return typeof arg === 'number';
6076}
6077
6078function isObject(arg) {
6079 return typeof arg === 'object' && arg !== null;
6080}
6081
6082function isUndefined(arg) {
6083 return arg === void 0;
6084}
6085
6086},{}],25:[function(_dereq_,module,exports){
6087module.exports = _dereq_('./javascript/diff_match_patch_uncompressed.js').diff_match_patch;
6088
6089},{"./javascript/diff_match_patch_uncompressed.js":26}],26:[function(_dereq_,module,exports){
6090/**
6091 * Diff Match and Patch
6092 *
6093 * Copyright 2006 Google Inc.
6094 * http://code.google.com/p/google-diff-match-patch/
6095 *
6096 * Licensed under the Apache License, Version 2.0 (the "License");
6097 * you may not use this file except in compliance with the License.
6098 * You may obtain a copy of the License at
6099 *
6100 * http://www.apache.org/licenses/LICENSE-2.0
6101 *
6102 * Unless required by applicable law or agreed to in writing, software
6103 * distributed under the License is distributed on an "AS IS" BASIS,
6104 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6105 * See the License for the specific language governing permissions and
6106 * limitations under the License.
6107 */
6108
6109/**
6110 * @fileoverview Computes the difference between two texts to create a patch.
6111 * Applies the patch onto another text, allowing for errors.
6112 * @author fraser@google.com (Neil Fraser)
6113 */
6114
6115/**
6116 * Class containing the diff, match and patch methods.
6117 * @constructor
6118 */
6119function diff_match_patch() {
6120
6121 // Defaults.
6122 // Redefine these in your program to override the defaults.
6123
6124 // Number of seconds to map a diff before giving up (0 for infinity).
6125 this.Diff_Timeout = 1.0;
6126 // Cost of an empty edit operation in terms of edit characters.
6127 this.Diff_EditCost = 4;
6128 // At what point is no match declared (0.0 = perfection, 1.0 = very loose).
6129 this.Match_Threshold = 0.5;
6130 // How far to search for a match (0 = exact location, 1000+ = broad match).
6131 // A match this many characters away from the expected location will add
6132 // 1.0 to the score (0.0 is a perfect match).
6133 this.Match_Distance = 1000;
6134 // When deleting a large block of text (over ~64 characters), how close do
6135 // the contents have to be to match the expected contents. (0.0 = perfection,
6136 // 1.0 = very loose). Note that Match_Threshold controls how closely the
6137 // end points of a delete need to match.
6138 this.Patch_DeleteThreshold = 0.5;
6139 // Chunk size for context length.
6140 this.Patch_Margin = 4;
6141
6142 // The number of bits in an int.
6143 this.Match_MaxBits = 32;
6144}
6145
6146
6147// DIFF FUNCTIONS
6148
6149
6150/**
6151 * The data structure representing a diff is an array of tuples:
6152 * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
6153 * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
6154 */
6155var DIFF_DELETE = -1;
6156var DIFF_INSERT = 1;
6157var DIFF_EQUAL = 0;
6158
6159/** @typedef {{0: number, 1: string}} */
6160diff_match_patch.Diff;
6161
6162
6163/**
6164 * Find the differences between two texts. Simplifies the problem by stripping
6165 * any common prefix or suffix off the texts before diffing.
6166 * @param {string} text1 Old string to be diffed.
6167 * @param {string} text2 New string to be diffed.
6168 * @param {boolean=} opt_checklines Optional speedup flag. If present and false,
6169 * then don't run a line-level diff first to identify the changed areas.
6170 * Defaults to true, which does a faster, slightly less optimal diff.
6171 * @param {number} opt_deadline Optional time when the diff should be complete
6172 * by. Used internally for recursive calls. Users should set DiffTimeout
6173 * instead.
6174 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
6175 */
6176diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines,
6177 opt_deadline) {
6178 // Set a deadline by which time the diff must be complete.
6179 if (typeof opt_deadline == 'undefined') {
6180 if (this.Diff_Timeout <= 0) {
6181 opt_deadline = Number.MAX_VALUE;
6182 } else {
6183 opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000;
6184 }
6185 }
6186 var deadline = opt_deadline;
6187
6188 // Check for null inputs.
6189 if (text1 == null || text2 == null) {
6190 throw new Error('Null input. (diff_main)');
6191 }
6192
6193 // Check for equality (speedup).
6194 if (text1 == text2) {
6195 if (text1) {
6196 return [[DIFF_EQUAL, text1]];
6197 }
6198 return [];
6199 }
6200
6201 if (typeof opt_checklines == 'undefined') {
6202 opt_checklines = true;
6203 }
6204 var checklines = opt_checklines;
6205
6206 // Trim off common prefix (speedup).
6207 var commonlength = this.diff_commonPrefix(text1, text2);
6208 var commonprefix = text1.substring(0, commonlength);
6209 text1 = text1.substring(commonlength);
6210 text2 = text2.substring(commonlength);
6211
6212 // Trim off common suffix (speedup).
6213 commonlength = this.diff_commonSuffix(text1, text2);
6214 var commonsuffix = text1.substring(text1.length - commonlength);
6215 text1 = text1.substring(0, text1.length - commonlength);
6216 text2 = text2.substring(0, text2.length - commonlength);
6217
6218 // Compute the diff on the middle block.
6219 var diffs = this.diff_compute_(text1, text2, checklines, deadline);
6220
6221 // Restore the prefix and suffix.
6222 if (commonprefix) {
6223 diffs.unshift([DIFF_EQUAL, commonprefix]);
6224 }
6225 if (commonsuffix) {
6226 diffs.push([DIFF_EQUAL, commonsuffix]);
6227 }
6228 this.diff_cleanupMerge(diffs);
6229 return diffs;
6230};
6231
6232
6233/**
6234 * Find the differences between two texts. Assumes that the texts do not
6235 * have any common prefix or suffix.
6236 * @param {string} text1 Old string to be diffed.
6237 * @param {string} text2 New string to be diffed.
6238 * @param {boolean} checklines Speedup flag. If false, then don't run a
6239 * line-level diff first to identify the changed areas.
6240 * If true, then run a faster, slightly less optimal diff.
6241 * @param {number} deadline Time when the diff should be complete by.
6242 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
6243 * @private
6244 */
6245diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines,
6246 deadline) {
6247 var diffs;
6248
6249 if (!text1) {
6250 // Just add some text (speedup).
6251 return [[DIFF_INSERT, text2]];
6252 }
6253
6254 if (!text2) {
6255 // Just delete some text (speedup).
6256 return [[DIFF_DELETE, text1]];
6257 }
6258
6259 var longtext = text1.length > text2.length ? text1 : text2;
6260 var shorttext = text1.length > text2.length ? text2 : text1;
6261 var i = longtext.indexOf(shorttext);
6262 if (i != -1) {
6263 // Shorter text is inside the longer text (speedup).
6264 diffs = [[DIFF_INSERT, longtext.substring(0, i)],
6265 [DIFF_EQUAL, shorttext],
6266 [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
6267 // Swap insertions for deletions if diff is reversed.
6268 if (text1.length > text2.length) {
6269 diffs[0][0] = diffs[2][0] = DIFF_DELETE;
6270 }
6271 return diffs;
6272 }
6273
6274 if (shorttext.length == 1) {
6275 // Single character string.
6276 // After the previous speedup, the character can't be an equality.
6277 return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
6278 }
6279
6280 // Check to see if the problem can be split in two.
6281 var hm = this.diff_halfMatch_(text1, text2);
6282 if (hm) {
6283 // A half-match was found, sort out the return data.
6284 var text1_a = hm[0];
6285 var text1_b = hm[1];
6286 var text2_a = hm[2];
6287 var text2_b = hm[3];
6288 var mid_common = hm[4];
6289 // Send both pairs off for separate processing.
6290 var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline);
6291 var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline);
6292 // Merge the results.
6293 return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
6294 }
6295
6296 if (checklines && text1.length > 100 && text2.length > 100) {
6297 return this.diff_lineMode_(text1, text2, deadline);
6298 }
6299
6300 return this.diff_bisect_(text1, text2, deadline);
6301};
6302
6303
6304/**
6305 * Do a quick line-level diff on both strings, then rediff the parts for
6306 * greater accuracy.
6307 * This speedup can produce non-minimal diffs.
6308 * @param {string} text1 Old string to be diffed.
6309 * @param {string} text2 New string to be diffed.
6310 * @param {number} deadline Time when the diff should be complete by.
6311 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
6312 * @private
6313 */
6314diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) {
6315 // Scan the text on a line-by-line basis first.
6316 var a = this.diff_linesToChars_(text1, text2);
6317 text1 = a.chars1;
6318 text2 = a.chars2;
6319 var linearray = a.lineArray;
6320
6321 var diffs = this.diff_main(text1, text2, false, deadline);
6322
6323 // Convert the diff back to original text.
6324 this.diff_charsToLines_(diffs, linearray);
6325 // Eliminate freak matches (e.g. blank lines)
6326 this.diff_cleanupSemantic(diffs);
6327
6328 // Rediff any replacement blocks, this time character-by-character.
6329 // Add a dummy entry at the end.
6330 diffs.push([DIFF_EQUAL, '']);
6331 var pointer = 0;
6332 var count_delete = 0;
6333 var count_insert = 0;
6334 var text_delete = '';
6335 var text_insert = '';
6336 while (pointer < diffs.length) {
6337 switch (diffs[pointer][0]) {
6338 case DIFF_INSERT:
6339 count_insert++;
6340 text_insert += diffs[pointer][1];
6341 break;
6342 case DIFF_DELETE:
6343 count_delete++;
6344 text_delete += diffs[pointer][1];
6345 break;
6346 case DIFF_EQUAL:
6347 // Upon reaching an equality, check for prior redundancies.
6348 if (count_delete >= 1 && count_insert >= 1) {
6349 // Delete the offending records and add the merged ones.
6350 diffs.splice(pointer - count_delete - count_insert,
6351 count_delete + count_insert);
6352 pointer = pointer - count_delete - count_insert;
6353 var a = this.diff_main(text_delete, text_insert, false, deadline);
6354 for (var j = a.length - 1; j >= 0; j--) {
6355 diffs.splice(pointer, 0, a[j]);
6356 }
6357 pointer = pointer + a.length;
6358 }
6359 count_insert = 0;
6360 count_delete = 0;
6361 text_delete = '';
6362 text_insert = '';
6363 break;
6364 }
6365 pointer++;
6366 }
6367 diffs.pop(); // Remove the dummy entry at the end.
6368
6369 return diffs;
6370};
6371
6372
6373/**
6374 * Find the 'middle snake' of a diff, split the problem in two
6375 * and return the recursively constructed diff.
6376 * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
6377 * @param {string} text1 Old string to be diffed.
6378 * @param {string} text2 New string to be diffed.
6379 * @param {number} deadline Time at which to bail if not yet complete.
6380 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
6381 * @private
6382 */
6383diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) {
6384 // Cache the text lengths to prevent multiple calls.
6385 var text1_length = text1.length;
6386 var text2_length = text2.length;
6387 var max_d = Math.ceil((text1_length + text2_length) / 2);
6388 var v_offset = max_d;
6389 var v_length = 2 * max_d;
6390 var v1 = new Array(v_length);
6391 var v2 = new Array(v_length);
6392 // Setting all elements to -1 is faster in Chrome & Firefox than mixing
6393 // integers and undefined.
6394 for (var x = 0; x < v_length; x++) {
6395 v1[x] = -1;
6396 v2[x] = -1;
6397 }
6398 v1[v_offset + 1] = 0;
6399 v2[v_offset + 1] = 0;
6400 var delta = text1_length - text2_length;
6401 // If the total number of characters is odd, then the front path will collide
6402 // with the reverse path.
6403 var front = (delta % 2 != 0);
6404 // Offsets for start and end of k loop.
6405 // Prevents mapping of space beyond the grid.
6406 var k1start = 0;
6407 var k1end = 0;
6408 var k2start = 0;
6409 var k2end = 0;
6410 for (var d = 0; d < max_d; d++) {
6411 // Bail out if deadline is reached.
6412 if ((new Date()).getTime() > deadline) {
6413 break;
6414 }
6415
6416 // Walk the front path one step.
6417 for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
6418 var k1_offset = v_offset + k1;
6419 var x1;
6420 if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
6421 x1 = v1[k1_offset + 1];
6422 } else {
6423 x1 = v1[k1_offset - 1] + 1;
6424 }
6425 var y1 = x1 - k1;
6426 while (x1 < text1_length && y1 < text2_length &&
6427 text1.charAt(x1) == text2.charAt(y1)) {
6428 x1++;
6429 y1++;
6430 }
6431 v1[k1_offset] = x1;
6432 if (x1 > text1_length) {
6433 // Ran off the right of the graph.
6434 k1end += 2;
6435 } else if (y1 > text2_length) {
6436 // Ran off the bottom of the graph.
6437 k1start += 2;
6438 } else if (front) {
6439 var k2_offset = v_offset + delta - k1;
6440 if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
6441 // Mirror x2 onto top-left coordinate system.
6442 var x2 = text1_length - v2[k2_offset];
6443 if (x1 >= x2) {
6444 // Overlap detected.
6445 return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
6446 }
6447 }
6448 }
6449 }
6450
6451 // Walk the reverse path one step.
6452 for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
6453 var k2_offset = v_offset + k2;
6454 var x2;
6455 if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
6456 x2 = v2[k2_offset + 1];
6457 } else {
6458 x2 = v2[k2_offset - 1] + 1;
6459 }
6460 var y2 = x2 - k2;
6461 while (x2 < text1_length && y2 < text2_length &&
6462 text1.charAt(text1_length - x2 - 1) ==
6463 text2.charAt(text2_length - y2 - 1)) {
6464 x2++;
6465 y2++;
6466 }
6467 v2[k2_offset] = x2;
6468 if (x2 > text1_length) {
6469 // Ran off the left of the graph.
6470 k2end += 2;
6471 } else if (y2 > text2_length) {
6472 // Ran off the top of the graph.
6473 k2start += 2;
6474 } else if (!front) {
6475 var k1_offset = v_offset + delta - k2;
6476 if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
6477 var x1 = v1[k1_offset];
6478 var y1 = v_offset + x1 - k1_offset;
6479 // Mirror x2 onto top-left coordinate system.
6480 x2 = text1_length - x2;
6481 if (x1 >= x2) {
6482 // Overlap detected.
6483 return this.diff_bisectSplit_(text1, text2, x1, y1, deadline);
6484 }
6485 }
6486 }
6487 }
6488 }
6489 // Diff took too long and hit the deadline or
6490 // number of diffs equals number of characters, no commonality at all.
6491 return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
6492};
6493
6494
6495/**
6496 * Given the location of the 'middle snake', split the diff in two parts
6497 * and recurse.
6498 * @param {string} text1 Old string to be diffed.
6499 * @param {string} text2 New string to be diffed.
6500 * @param {number} x Index of split point in text1.
6501 * @param {number} y Index of split point in text2.
6502 * @param {number} deadline Time at which to bail if not yet complete.
6503 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
6504 * @private
6505 */
6506diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y,
6507 deadline) {
6508 var text1a = text1.substring(0, x);
6509 var text2a = text2.substring(0, y);
6510 var text1b = text1.substring(x);
6511 var text2b = text2.substring(y);
6512
6513 // Compute both diffs serially.
6514 var diffs = this.diff_main(text1a, text2a, false, deadline);
6515 var diffsb = this.diff_main(text1b, text2b, false, deadline);
6516
6517 return diffs.concat(diffsb);
6518};
6519
6520
6521/**
6522 * Split two texts into an array of strings. Reduce the texts to a string of
6523 * hashes where each Unicode character represents one line.
6524 * @param {string} text1 First string.
6525 * @param {string} text2 Second string.
6526 * @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
6527 * An object containing the encoded text1, the encoded text2 and
6528 * the array of unique strings.
6529 * The zeroth element of the array of unique strings is intentionally blank.
6530 * @private
6531 */
6532diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) {
6533 var lineArray = []; // e.g. lineArray[4] == 'Hello\n'
6534 var lineHash = {}; // e.g. lineHash['Hello\n'] == 4
6535
6536 // '\x00' is a valid character, but various debuggers don't like it.
6537 // So we'll insert a junk entry to avoid generating a null character.
6538 lineArray[0] = '';
6539
6540 /**
6541 * Split a text into an array of strings. Reduce the texts to a string of
6542 * hashes where each Unicode character represents one line.
6543 * Modifies linearray and linehash through being a closure.
6544 * @param {string} text String to encode.
6545 * @return {string} Encoded string.
6546 * @private
6547 */
6548 function diff_linesToCharsMunge_(text) {
6549 var chars = '';
6550 // Walk the text, pulling out a substring for each line.
6551 // text.split('\n') would would temporarily double our memory footprint.
6552 // Modifying text would create many large strings to garbage collect.
6553 var lineStart = 0;
6554 var lineEnd = -1;
6555 // Keeping our own length variable is faster than looking it up.
6556 var lineArrayLength = lineArray.length;
6557 while (lineEnd < text.length - 1) {
6558 lineEnd = text.indexOf('\n', lineStart);
6559 if (lineEnd == -1) {
6560 lineEnd = text.length - 1;
6561 }
6562 var line = text.substring(lineStart, lineEnd + 1);
6563 lineStart = lineEnd + 1;
6564
6565 if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
6566 (lineHash[line] !== undefined)) {
6567 chars += String.fromCharCode(lineHash[line]);
6568 } else {
6569 chars += String.fromCharCode(lineArrayLength);
6570 lineHash[line] = lineArrayLength;
6571 lineArray[lineArrayLength++] = line;
6572 }
6573 }
6574 return chars;
6575 }
6576
6577 var chars1 = diff_linesToCharsMunge_(text1);
6578 var chars2 = diff_linesToCharsMunge_(text2);
6579 return {chars1: chars1, chars2: chars2, lineArray: lineArray};
6580};
6581
6582
6583/**
6584 * Rehydrate the text in a diff from a string of line hashes to real lines of
6585 * text.
6586 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
6587 * @param {!Array.<string>} lineArray Array of unique strings.
6588 * @private
6589 */
6590diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) {
6591 for (var x = 0; x < diffs.length; x++) {
6592 var chars = diffs[x][1];
6593 var text = [];
6594 for (var y = 0; y < chars.length; y++) {
6595 text[y] = lineArray[chars.charCodeAt(y)];
6596 }
6597 diffs[x][1] = text.join('');
6598 }
6599};
6600
6601
6602/**
6603 * Determine the common prefix of two strings.
6604 * @param {string} text1 First string.
6605 * @param {string} text2 Second string.
6606 * @return {number} The number of characters common to the start of each
6607 * string.
6608 */
6609diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) {
6610 // Quick check for common null cases.
6611 if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
6612 return 0;
6613 }
6614 // Binary search.
6615 // Performance analysis: http://neil.fraser.name/news/2007/10/09/
6616 var pointermin = 0;
6617 var pointermax = Math.min(text1.length, text2.length);
6618 var pointermid = pointermax;
6619 var pointerstart = 0;
6620 while (pointermin < pointermid) {
6621 if (text1.substring(pointerstart, pointermid) ==
6622 text2.substring(pointerstart, pointermid)) {
6623 pointermin = pointermid;
6624 pointerstart = pointermin;
6625 } else {
6626 pointermax = pointermid;
6627 }
6628 pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
6629 }
6630 return pointermid;
6631};
6632
6633
6634/**
6635 * Determine the common suffix of two strings.
6636 * @param {string} text1 First string.
6637 * @param {string} text2 Second string.
6638 * @return {number} The number of characters common to the end of each string.
6639 */
6640diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) {
6641 // Quick check for common null cases.
6642 if (!text1 || !text2 ||
6643 text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
6644 return 0;
6645 }
6646 // Binary search.
6647 // Performance analysis: http://neil.fraser.name/news/2007/10/09/
6648 var pointermin = 0;
6649 var pointermax = Math.min(text1.length, text2.length);
6650 var pointermid = pointermax;
6651 var pointerend = 0;
6652 while (pointermin < pointermid) {
6653 if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
6654 text2.substring(text2.length - pointermid, text2.length - pointerend)) {
6655 pointermin = pointermid;
6656 pointerend = pointermin;
6657 } else {
6658 pointermax = pointermid;
6659 }
6660 pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
6661 }
6662 return pointermid;
6663};
6664
6665
6666/**
6667 * Determine if the suffix of one string is the prefix of another.
6668 * @param {string} text1 First string.
6669 * @param {string} text2 Second string.
6670 * @return {number} The number of characters common to the end of the first
6671 * string and the start of the second string.
6672 * @private
6673 */
6674diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) {
6675 // Cache the text lengths to prevent multiple calls.
6676 var text1_length = text1.length;
6677 var text2_length = text2.length;
6678 // Eliminate the null case.
6679 if (text1_length == 0 || text2_length == 0) {
6680 return 0;
6681 }
6682 // Truncate the longer string.
6683 if (text1_length > text2_length) {
6684 text1 = text1.substring(text1_length - text2_length);
6685 } else if (text1_length < text2_length) {
6686 text2 = text2.substring(0, text1_length);
6687 }
6688 var text_length = Math.min(text1_length, text2_length);
6689 // Quick check for the worst case.
6690 if (text1 == text2) {
6691 return text_length;
6692 }
6693
6694 // Start by looking for a single character match
6695 // and increase length until no match is found.
6696 // Performance analysis: http://neil.fraser.name/news/2010/11/04/
6697 var best = 0;
6698 var length = 1;
6699 while (true) {
6700 var pattern = text1.substring(text_length - length);
6701 var found = text2.indexOf(pattern);
6702 if (found == -1) {
6703 return best;
6704 }
6705 length += found;
6706 if (found == 0 || text1.substring(text_length - length) ==
6707 text2.substring(0, length)) {
6708 best = length;
6709 length++;
6710 }
6711 }
6712};
6713
6714
6715/**
6716 * Do the two texts share a substring which is at least half the length of the
6717 * longer text?
6718 * This speedup can produce non-minimal diffs.
6719 * @param {string} text1 First string.
6720 * @param {string} text2 Second string.
6721 * @return {Array.<string>} Five element Array, containing the prefix of
6722 * text1, the suffix of text1, the prefix of text2, the suffix of
6723 * text2 and the common middle. Or null if there was no match.
6724 * @private
6725 */
6726diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) {
6727 if (this.Diff_Timeout <= 0) {
6728 // Don't risk returning a non-optimal diff if we have unlimited time.
6729 return null;
6730 }
6731 var longtext = text1.length > text2.length ? text1 : text2;
6732 var shorttext = text1.length > text2.length ? text2 : text1;
6733 if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
6734 return null; // Pointless.
6735 }
6736 var dmp = this; // 'this' becomes 'window' in a closure.
6737
6738 /**
6739 * Does a substring of shorttext exist within longtext such that the substring
6740 * is at least half the length of longtext?
6741 * Closure, but does not reference any external variables.
6742 * @param {string} longtext Longer string.
6743 * @param {string} shorttext Shorter string.
6744 * @param {number} i Start index of quarter length substring within longtext.
6745 * @return {Array.<string>} Five element Array, containing the prefix of
6746 * longtext, the suffix of longtext, the prefix of shorttext, the suffix
6747 * of shorttext and the common middle. Or null if there was no match.
6748 * @private
6749 */
6750 function diff_halfMatchI_(longtext, shorttext, i) {
6751 // Start with a 1/4 length substring at position i as a seed.
6752 var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
6753 var j = -1;
6754 var best_common = '';
6755 var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
6756 while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
6757 var prefixLength = dmp.diff_commonPrefix(longtext.substring(i),
6758 shorttext.substring(j));
6759 var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i),
6760 shorttext.substring(0, j));
6761 if (best_common.length < suffixLength + prefixLength) {
6762 best_common = shorttext.substring(j - suffixLength, j) +
6763 shorttext.substring(j, j + prefixLength);
6764 best_longtext_a = longtext.substring(0, i - suffixLength);
6765 best_longtext_b = longtext.substring(i + prefixLength);
6766 best_shorttext_a = shorttext.substring(0, j - suffixLength);
6767 best_shorttext_b = shorttext.substring(j + prefixLength);
6768 }
6769 }
6770 if (best_common.length * 2 >= longtext.length) {
6771 return [best_longtext_a, best_longtext_b,
6772 best_shorttext_a, best_shorttext_b, best_common];
6773 } else {
6774 return null;
6775 }
6776 }
6777
6778 // First check if the second quarter is the seed for a half-match.
6779 var hm1 = diff_halfMatchI_(longtext, shorttext,
6780 Math.ceil(longtext.length / 4));
6781 // Check again based on the third quarter.
6782 var hm2 = diff_halfMatchI_(longtext, shorttext,
6783 Math.ceil(longtext.length / 2));
6784 var hm;
6785 if (!hm1 && !hm2) {
6786 return null;
6787 } else if (!hm2) {
6788 hm = hm1;
6789 } else if (!hm1) {
6790 hm = hm2;
6791 } else {
6792 // Both matched. Select the longest.
6793 hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
6794 }
6795
6796 // A half-match was found, sort out the return data.
6797 var text1_a, text1_b, text2_a, text2_b;
6798 if (text1.length > text2.length) {
6799 text1_a = hm[0];
6800 text1_b = hm[1];
6801 text2_a = hm[2];
6802 text2_b = hm[3];
6803 } else {
6804 text2_a = hm[0];
6805 text2_b = hm[1];
6806 text1_a = hm[2];
6807 text1_b = hm[3];
6808 }
6809 var mid_common = hm[4];
6810 return [text1_a, text1_b, text2_a, text2_b, mid_common];
6811};
6812
6813
6814/**
6815 * Reduce the number of edits by eliminating semantically trivial equalities.
6816 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
6817 */
6818diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) {
6819 var changes = false;
6820 var equalities = []; // Stack of indices where equalities are found.
6821 var equalitiesLength = 0; // Keeping our own length var is faster in JS.
6822 /** @type {?string} */
6823 var lastequality = null;
6824 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
6825 var pointer = 0; // Index of current position.
6826 // Number of characters that changed prior to the equality.
6827 var length_insertions1 = 0;
6828 var length_deletions1 = 0;
6829 // Number of characters that changed after the equality.
6830 var length_insertions2 = 0;
6831 var length_deletions2 = 0;
6832 while (pointer < diffs.length) {
6833 if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
6834 equalities[equalitiesLength++] = pointer;
6835 length_insertions1 = length_insertions2;
6836 length_deletions1 = length_deletions2;
6837 length_insertions2 = 0;
6838 length_deletions2 = 0;
6839 lastequality = diffs[pointer][1];
6840 } else { // An insertion or deletion.
6841 if (diffs[pointer][0] == DIFF_INSERT) {
6842 length_insertions2 += diffs[pointer][1].length;
6843 } else {
6844 length_deletions2 += diffs[pointer][1].length;
6845 }
6846 // Eliminate an equality that is smaller or equal to the edits on both
6847 // sides of it.
6848 if (lastequality && (lastequality.length <=
6849 Math.max(length_insertions1, length_deletions1)) &&
6850 (lastequality.length <= Math.max(length_insertions2,
6851 length_deletions2))) {
6852 // Duplicate record.
6853 diffs.splice(equalities[equalitiesLength - 1], 0,
6854 [DIFF_DELETE, lastequality]);
6855 // Change second copy to insert.
6856 diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
6857 // Throw away the equality we just deleted.
6858 equalitiesLength--;
6859 // Throw away the previous equality (it needs to be reevaluated).
6860 equalitiesLength--;
6861 pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
6862 length_insertions1 = 0; // Reset the counters.
6863 length_deletions1 = 0;
6864 length_insertions2 = 0;
6865 length_deletions2 = 0;
6866 lastequality = null;
6867 changes = true;
6868 }
6869 }
6870 pointer++;
6871 }
6872
6873 // Normalize the diff.
6874 if (changes) {
6875 this.diff_cleanupMerge(diffs);
6876 }
6877 this.diff_cleanupSemanticLossless(diffs);
6878
6879 // Find any overlaps between deletions and insertions.
6880 // e.g: <del>abcxxx</del><ins>xxxdef</ins>
6881 // -> <del>abc</del>xxx<ins>def</ins>
6882 // e.g: <del>xxxabc</del><ins>defxxx</ins>
6883 // -> <ins>def</ins>xxx<del>abc</del>
6884 // Only extract an overlap if it is as big as the edit ahead or behind it.
6885 pointer = 1;
6886 while (pointer < diffs.length) {
6887 if (diffs[pointer - 1][0] == DIFF_DELETE &&
6888 diffs[pointer][0] == DIFF_INSERT) {
6889 var deletion = diffs[pointer - 1][1];
6890 var insertion = diffs[pointer][1];
6891 var overlap_length1 = this.diff_commonOverlap_(deletion, insertion);
6892 var overlap_length2 = this.diff_commonOverlap_(insertion, deletion);
6893 if (overlap_length1 >= overlap_length2) {
6894 if (overlap_length1 >= deletion.length / 2 ||
6895 overlap_length1 >= insertion.length / 2) {
6896 // Overlap found. Insert an equality and trim the surrounding edits.
6897 diffs.splice(pointer, 0,
6898 [DIFF_EQUAL, insertion.substring(0, overlap_length1)]);
6899 diffs[pointer - 1][1] =
6900 deletion.substring(0, deletion.length - overlap_length1);
6901 diffs[pointer + 1][1] = insertion.substring(overlap_length1);
6902 pointer++;
6903 }
6904 } else {
6905 if (overlap_length2 >= deletion.length / 2 ||
6906 overlap_length2 >= insertion.length / 2) {
6907 // Reverse overlap found.
6908 // Insert an equality and swap and trim the surrounding edits.
6909 diffs.splice(pointer, 0,
6910 [DIFF_EQUAL, deletion.substring(0, overlap_length2)]);
6911 diffs[pointer - 1][0] = DIFF_INSERT;
6912 diffs[pointer - 1][1] =
6913 insertion.substring(0, insertion.length - overlap_length2);
6914 diffs[pointer + 1][0] = DIFF_DELETE;
6915 diffs[pointer + 1][1] =
6916 deletion.substring(overlap_length2);
6917 pointer++;
6918 }
6919 }
6920 pointer++;
6921 }
6922 pointer++;
6923 }
6924};
6925
6926
6927/**
6928 * Look for single edits surrounded on both sides by equalities
6929 * which can be shifted sideways to align the edit to a word boundary.
6930 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
6931 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
6932 */
6933diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) {
6934 /**
6935 * Given two strings, compute a score representing whether the internal
6936 * boundary falls on logical boundaries.
6937 * Scores range from 6 (best) to 0 (worst).
6938 * Closure, but does not reference any external variables.
6939 * @param {string} one First string.
6940 * @param {string} two Second string.
6941 * @return {number} The score.
6942 * @private
6943 */
6944 function diff_cleanupSemanticScore_(one, two) {
6945 if (!one || !two) {
6946 // Edges are the best.
6947 return 6;
6948 }
6949
6950 // Each port of this function behaves slightly differently due to
6951 // subtle differences in each language's definition of things like
6952 // 'whitespace'. Since this function's purpose is largely cosmetic,
6953 // the choice has been made to use each language's native features
6954 // rather than force total conformity.
6955 var char1 = one.charAt(one.length - 1);
6956 var char2 = two.charAt(0);
6957 var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_);
6958 var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_);
6959 var whitespace1 = nonAlphaNumeric1 &&
6960 char1.match(diff_match_patch.whitespaceRegex_);
6961 var whitespace2 = nonAlphaNumeric2 &&
6962 char2.match(diff_match_patch.whitespaceRegex_);
6963 var lineBreak1 = whitespace1 &&
6964 char1.match(diff_match_patch.linebreakRegex_);
6965 var lineBreak2 = whitespace2 &&
6966 char2.match(diff_match_patch.linebreakRegex_);
6967 var blankLine1 = lineBreak1 &&
6968 one.match(diff_match_patch.blanklineEndRegex_);
6969 var blankLine2 = lineBreak2 &&
6970 two.match(diff_match_patch.blanklineStartRegex_);
6971
6972 if (blankLine1 || blankLine2) {
6973 // Five points for blank lines.
6974 return 5;
6975 } else if (lineBreak1 || lineBreak2) {
6976 // Four points for line breaks.
6977 return 4;
6978 } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) {
6979 // Three points for end of sentences.
6980 return 3;
6981 } else if (whitespace1 || whitespace2) {
6982 // Two points for whitespace.
6983 return 2;
6984 } else if (nonAlphaNumeric1 || nonAlphaNumeric2) {
6985 // One point for non-alphanumeric.
6986 return 1;
6987 }
6988 return 0;
6989 }
6990
6991 var pointer = 1;
6992 // Intentionally ignore the first and last element (don't need checking).
6993 while (pointer < diffs.length - 1) {
6994 if (diffs[pointer - 1][0] == DIFF_EQUAL &&
6995 diffs[pointer + 1][0] == DIFF_EQUAL) {
6996 // This is a single edit surrounded by equalities.
6997 var equality1 = diffs[pointer - 1][1];
6998 var edit = diffs[pointer][1];
6999 var equality2 = diffs[pointer + 1][1];
7000
7001 // First, shift the edit as far left as possible.
7002 var commonOffset = this.diff_commonSuffix(equality1, edit);
7003 if (commonOffset) {
7004 var commonString = edit.substring(edit.length - commonOffset);
7005 equality1 = equality1.substring(0, equality1.length - commonOffset);
7006 edit = commonString + edit.substring(0, edit.length - commonOffset);
7007 equality2 = commonString + equality2;
7008 }
7009
7010 // Second, step character by character right, looking for the best fit.
7011 var bestEquality1 = equality1;
7012 var bestEdit = edit;
7013 var bestEquality2 = equality2;
7014 var bestScore = diff_cleanupSemanticScore_(equality1, edit) +
7015 diff_cleanupSemanticScore_(edit, equality2);
7016 while (edit.charAt(0) === equality2.charAt(0)) {
7017 equality1 += edit.charAt(0);
7018 edit = edit.substring(1) + equality2.charAt(0);
7019 equality2 = equality2.substring(1);
7020 var score = diff_cleanupSemanticScore_(equality1, edit) +
7021 diff_cleanupSemanticScore_(edit, equality2);
7022 // The >= encourages trailing rather than leading whitespace on edits.
7023 if (score >= bestScore) {
7024 bestScore = score;
7025 bestEquality1 = equality1;
7026 bestEdit = edit;
7027 bestEquality2 = equality2;
7028 }
7029 }
7030
7031 if (diffs[pointer - 1][1] != bestEquality1) {
7032 // We have an improvement, save it back to the diff.
7033 if (bestEquality1) {
7034 diffs[pointer - 1][1] = bestEquality1;
7035 } else {
7036 diffs.splice(pointer - 1, 1);
7037 pointer--;
7038 }
7039 diffs[pointer][1] = bestEdit;
7040 if (bestEquality2) {
7041 diffs[pointer + 1][1] = bestEquality2;
7042 } else {
7043 diffs.splice(pointer + 1, 1);
7044 pointer--;
7045 }
7046 }
7047 }
7048 pointer++;
7049 }
7050};
7051
7052// Define some regex patterns for matching boundaries.
7053diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
7054diff_match_patch.whitespaceRegex_ = /\s/;
7055diff_match_patch.linebreakRegex_ = /[\r\n]/;
7056diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/;
7057diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/;
7058
7059/**
7060 * Reduce the number of edits by eliminating operationally trivial equalities.
7061 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7062 */
7063diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) {
7064 var changes = false;
7065 var equalities = []; // Stack of indices where equalities are found.
7066 var equalitiesLength = 0; // Keeping our own length var is faster in JS.
7067 /** @type {?string} */
7068 var lastequality = null;
7069 // Always equal to diffs[equalities[equalitiesLength - 1]][1]
7070 var pointer = 0; // Index of current position.
7071 // Is there an insertion operation before the last equality.
7072 var pre_ins = false;
7073 // Is there a deletion operation before the last equality.
7074 var pre_del = false;
7075 // Is there an insertion operation after the last equality.
7076 var post_ins = false;
7077 // Is there a deletion operation after the last equality.
7078 var post_del = false;
7079 while (pointer < diffs.length) {
7080 if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found.
7081 if (diffs[pointer][1].length < this.Diff_EditCost &&
7082 (post_ins || post_del)) {
7083 // Candidate found.
7084 equalities[equalitiesLength++] = pointer;
7085 pre_ins = post_ins;
7086 pre_del = post_del;
7087 lastequality = diffs[pointer][1];
7088 } else {
7089 // Not a candidate, and can never become one.
7090 equalitiesLength = 0;
7091 lastequality = null;
7092 }
7093 post_ins = post_del = false;
7094 } else { // An insertion or deletion.
7095 if (diffs[pointer][0] == DIFF_DELETE) {
7096 post_del = true;
7097 } else {
7098 post_ins = true;
7099 }
7100 /*
7101 * Five types to be split:
7102 * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
7103 * <ins>A</ins>X<ins>C</ins><del>D</del>
7104 * <ins>A</ins><del>B</del>X<ins>C</ins>
7105 * <ins>A</del>X<ins>C</ins><del>D</del>
7106 * <ins>A</ins><del>B</del>X<del>C</del>
7107 */
7108 if (lastequality && ((pre_ins && pre_del && post_ins && post_del) ||
7109 ((lastequality.length < this.Diff_EditCost / 2) &&
7110 (pre_ins + pre_del + post_ins + post_del) == 3))) {
7111 // Duplicate record.
7112 diffs.splice(equalities[equalitiesLength - 1], 0,
7113 [DIFF_DELETE, lastequality]);
7114 // Change second copy to insert.
7115 diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
7116 equalitiesLength--; // Throw away the equality we just deleted;
7117 lastequality = null;
7118 if (pre_ins && pre_del) {
7119 // No changes made which could affect previous entry, keep going.
7120 post_ins = post_del = true;
7121 equalitiesLength = 0;
7122 } else {
7123 equalitiesLength--; // Throw away the previous equality.
7124 pointer = equalitiesLength > 0 ?
7125 equalities[equalitiesLength - 1] : -1;
7126 post_ins = post_del = false;
7127 }
7128 changes = true;
7129 }
7130 }
7131 pointer++;
7132 }
7133
7134 if (changes) {
7135 this.diff_cleanupMerge(diffs);
7136 }
7137};
7138
7139
7140/**
7141 * Reorder and merge like edit sections. Merge equalities.
7142 * Any edit section can move as long as it doesn't cross an equality.
7143 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7144 */
7145diff_match_patch.prototype.diff_cleanupMerge = function(diffs) {
7146 diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
7147 var pointer = 0;
7148 var count_delete = 0;
7149 var count_insert = 0;
7150 var text_delete = '';
7151 var text_insert = '';
7152 var commonlength;
7153 while (pointer < diffs.length) {
7154 switch (diffs[pointer][0]) {
7155 case DIFF_INSERT:
7156 count_insert++;
7157 text_insert += diffs[pointer][1];
7158 pointer++;
7159 break;
7160 case DIFF_DELETE:
7161 count_delete++;
7162 text_delete += diffs[pointer][1];
7163 pointer++;
7164 break;
7165 case DIFF_EQUAL:
7166 // Upon reaching an equality, check for prior redundancies.
7167 if (count_delete + count_insert > 1) {
7168 if (count_delete !== 0 && count_insert !== 0) {
7169 // Factor out any common prefixies.
7170 commonlength = this.diff_commonPrefix(text_insert, text_delete);
7171 if (commonlength !== 0) {
7172 if ((pointer - count_delete - count_insert) > 0 &&
7173 diffs[pointer - count_delete - count_insert - 1][0] ==
7174 DIFF_EQUAL) {
7175 diffs[pointer - count_delete - count_insert - 1][1] +=
7176 text_insert.substring(0, commonlength);
7177 } else {
7178 diffs.splice(0, 0, [DIFF_EQUAL,
7179 text_insert.substring(0, commonlength)]);
7180 pointer++;
7181 }
7182 text_insert = text_insert.substring(commonlength);
7183 text_delete = text_delete.substring(commonlength);
7184 }
7185 // Factor out any common suffixies.
7186 commonlength = this.diff_commonSuffix(text_insert, text_delete);
7187 if (commonlength !== 0) {
7188 diffs[pointer][1] = text_insert.substring(text_insert.length -
7189 commonlength) + diffs[pointer][1];
7190 text_insert = text_insert.substring(0, text_insert.length -
7191 commonlength);
7192 text_delete = text_delete.substring(0, text_delete.length -
7193 commonlength);
7194 }
7195 }
7196 // Delete the offending records and add the merged ones.
7197 if (count_delete === 0) {
7198 diffs.splice(pointer - count_insert,
7199 count_delete + count_insert, [DIFF_INSERT, text_insert]);
7200 } else if (count_insert === 0) {
7201 diffs.splice(pointer - count_delete,
7202 count_delete + count_insert, [DIFF_DELETE, text_delete]);
7203 } else {
7204 diffs.splice(pointer - count_delete - count_insert,
7205 count_delete + count_insert, [DIFF_DELETE, text_delete],
7206 [DIFF_INSERT, text_insert]);
7207 }
7208 pointer = pointer - count_delete - count_insert +
7209 (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1;
7210 } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
7211 // Merge this equality with the previous one.
7212 diffs[pointer - 1][1] += diffs[pointer][1];
7213 diffs.splice(pointer, 1);
7214 } else {
7215 pointer++;
7216 }
7217 count_insert = 0;
7218 count_delete = 0;
7219 text_delete = '';
7220 text_insert = '';
7221 break;
7222 }
7223 }
7224 if (diffs[diffs.length - 1][1] === '') {
7225 diffs.pop(); // Remove the dummy entry at the end.
7226 }
7227
7228 // Second pass: look for single edits surrounded on both sides by equalities
7229 // which can be shifted sideways to eliminate an equality.
7230 // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
7231 var changes = false;
7232 pointer = 1;
7233 // Intentionally ignore the first and last element (don't need checking).
7234 while (pointer < diffs.length - 1) {
7235 if (diffs[pointer - 1][0] == DIFF_EQUAL &&
7236 diffs[pointer + 1][0] == DIFF_EQUAL) {
7237 // This is a single edit surrounded by equalities.
7238 if (diffs[pointer][1].substring(diffs[pointer][1].length -
7239 diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
7240 // Shift the edit over the previous equality.
7241 diffs[pointer][1] = diffs[pointer - 1][1] +
7242 diffs[pointer][1].substring(0, diffs[pointer][1].length -
7243 diffs[pointer - 1][1].length);
7244 diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
7245 diffs.splice(pointer - 1, 1);
7246 changes = true;
7247 } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
7248 diffs[pointer + 1][1]) {
7249 // Shift the edit over the next equality.
7250 diffs[pointer - 1][1] += diffs[pointer + 1][1];
7251 diffs[pointer][1] =
7252 diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
7253 diffs[pointer + 1][1];
7254 diffs.splice(pointer + 1, 1);
7255 changes = true;
7256 }
7257 }
7258 pointer++;
7259 }
7260 // If shifts were made, the diff needs reordering and another shift sweep.
7261 if (changes) {
7262 this.diff_cleanupMerge(diffs);
7263 }
7264};
7265
7266
7267/**
7268 * loc is a location in text1, compute and return the equivalent location in
7269 * text2.
7270 * e.g. 'The cat' vs 'The big cat', 1->1, 5->8
7271 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7272 * @param {number} loc Location within text1.
7273 * @return {number} Location within text2.
7274 */
7275diff_match_patch.prototype.diff_xIndex = function(diffs, loc) {
7276 var chars1 = 0;
7277 var chars2 = 0;
7278 var last_chars1 = 0;
7279 var last_chars2 = 0;
7280 var x;
7281 for (x = 0; x < diffs.length; x++) {
7282 if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion.
7283 chars1 += diffs[x][1].length;
7284 }
7285 if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion.
7286 chars2 += diffs[x][1].length;
7287 }
7288 if (chars1 > loc) { // Overshot the location.
7289 break;
7290 }
7291 last_chars1 = chars1;
7292 last_chars2 = chars2;
7293 }
7294 // Was the location was deleted?
7295 if (diffs.length != x && diffs[x][0] === DIFF_DELETE) {
7296 return last_chars2;
7297 }
7298 // Add the remaining character length.
7299 return last_chars2 + (loc - last_chars1);
7300};
7301
7302
7303/**
7304 * Convert a diff array into a pretty HTML report.
7305 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7306 * @return {string} HTML representation.
7307 */
7308diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
7309 var html = [];
7310 var pattern_amp = /&/g;
7311 var pattern_lt = /</g;
7312 var pattern_gt = />/g;
7313 var pattern_para = /\n/g;
7314 for (var x = 0; x < diffs.length; x++) {
7315 var op = diffs[x][0]; // Operation (insert, delete, equal)
7316 var data = diffs[x][1]; // Text of change.
7317 var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
7318 .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
7319 switch (op) {
7320 case DIFF_INSERT:
7321 html[x] = '<ins style="background:#e6ffe6;">' + text + '</ins>';
7322 break;
7323 case DIFF_DELETE:
7324 html[x] = '<del style="background:#ffe6e6;">' + text + '</del>';
7325 break;
7326 case DIFF_EQUAL:
7327 html[x] = '<span>' + text + '</span>';
7328 break;
7329 }
7330 }
7331 return html.join('');
7332};
7333
7334
7335/**
7336 * Compute and return the source text (all equalities and deletions).
7337 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7338 * @return {string} Source text.
7339 */
7340diff_match_patch.prototype.diff_text1 = function(diffs) {
7341 var text = [];
7342 for (var x = 0; x < diffs.length; x++) {
7343 if (diffs[x][0] !== DIFF_INSERT) {
7344 text[x] = diffs[x][1];
7345 }
7346 }
7347 return text.join('');
7348};
7349
7350
7351/**
7352 * Compute and return the destination text (all equalities and insertions).
7353 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7354 * @return {string} Destination text.
7355 */
7356diff_match_patch.prototype.diff_text2 = function(diffs) {
7357 var text = [];
7358 for (var x = 0; x < diffs.length; x++) {
7359 if (diffs[x][0] !== DIFF_DELETE) {
7360 text[x] = diffs[x][1];
7361 }
7362 }
7363 return text.join('');
7364};
7365
7366
7367/**
7368 * Compute the Levenshtein distance; the number of inserted, deleted or
7369 * substituted characters.
7370 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7371 * @return {number} Number of changes.
7372 */
7373diff_match_patch.prototype.diff_levenshtein = function(diffs) {
7374 var levenshtein = 0;
7375 var insertions = 0;
7376 var deletions = 0;
7377 for (var x = 0; x < diffs.length; x++) {
7378 var op = diffs[x][0];
7379 var data = diffs[x][1];
7380 switch (op) {
7381 case DIFF_INSERT:
7382 insertions += data.length;
7383 break;
7384 case DIFF_DELETE:
7385 deletions += data.length;
7386 break;
7387 case DIFF_EQUAL:
7388 // A deletion and an insertion is one substitution.
7389 levenshtein += Math.max(insertions, deletions);
7390 insertions = 0;
7391 deletions = 0;
7392 break;
7393 }
7394 }
7395 levenshtein += Math.max(insertions, deletions);
7396 return levenshtein;
7397};
7398
7399
7400/**
7401 * Crush the diff into an encoded string which describes the operations
7402 * required to transform text1 into text2.
7403 * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
7404 * Operations are tab-separated. Inserted text is escaped using %xx notation.
7405 * @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples.
7406 * @return {string} Delta text.
7407 */
7408diff_match_patch.prototype.diff_toDelta = function(diffs) {
7409 var text = [];
7410 for (var x = 0; x < diffs.length; x++) {
7411 switch (diffs[x][0]) {
7412 case DIFF_INSERT:
7413 text[x] = '+' + encodeURI(diffs[x][1]);
7414 break;
7415 case DIFF_DELETE:
7416 text[x] = '-' + diffs[x][1].length;
7417 break;
7418 case DIFF_EQUAL:
7419 text[x] = '=' + diffs[x][1].length;
7420 break;
7421 }
7422 }
7423 return text.join('\t').replace(/%20/g, ' ');
7424};
7425
7426
7427/**
7428 * Given the original text1, and an encoded string which describes the
7429 * operations required to transform text1 into text2, compute the full diff.
7430 * @param {string} text1 Source string for the diff.
7431 * @param {string} delta Delta text.
7432 * @return {!Array.<!diff_match_patch.Diff>} Array of diff tuples.
7433 * @throws {!Error} If invalid input.
7434 */
7435diff_match_patch.prototype.diff_fromDelta = function(text1, delta) {
7436 var diffs = [];
7437 var diffsLength = 0; // Keeping our own length var is faster in JS.
7438 var pointer = 0; // Cursor in text1
7439 var tokens = delta.split(/\t/g);
7440 for (var x = 0; x < tokens.length; x++) {
7441 // Each token begins with a one character parameter which specifies the
7442 // operation of this token (delete, insert, equality).
7443 var param = tokens[x].substring(1);
7444 switch (tokens[x].charAt(0)) {
7445 case '+':
7446 try {
7447 diffs[diffsLength++] = [DIFF_INSERT, decodeURI(param)];
7448 } catch (ex) {
7449 // Malformed URI sequence.
7450 throw new Error('Illegal escape in diff_fromDelta: ' + param);
7451 }
7452 break;
7453 case '-':
7454 // Fall through.
7455 case '=':
7456 var n = parseInt(param, 10);
7457 if (isNaN(n) || n < 0) {
7458 throw new Error('Invalid number in diff_fromDelta: ' + param);
7459 }
7460 var text = text1.substring(pointer, pointer += n);
7461 if (tokens[x].charAt(0) == '=') {
7462 diffs[diffsLength++] = [DIFF_EQUAL, text];
7463 } else {
7464 diffs[diffsLength++] = [DIFF_DELETE, text];
7465 }
7466 break;
7467 default:
7468 // Blank tokens are ok (from a trailing \t).
7469 // Anything else is an error.
7470 if (tokens[x]) {
7471 throw new Error('Invalid diff operation in diff_fromDelta: ' +
7472 tokens[x]);
7473 }
7474 }
7475 }
7476 if (pointer != text1.length) {
7477 throw new Error('Delta length (' + pointer +
7478 ') does not equal source text length (' + text1.length + ').');
7479 }
7480 return diffs;
7481};
7482
7483
7484// MATCH FUNCTIONS
7485
7486
7487/**
7488 * Locate the best instance of 'pattern' in 'text' near 'loc'.
7489 * @param {string} text The text to search.
7490 * @param {string} pattern The pattern to search for.
7491 * @param {number} loc The location to search around.
7492 * @return {number} Best match index or -1.
7493 */
7494diff_match_patch.prototype.match_main = function(text, pattern, loc) {
7495 // Check for null inputs.
7496 if (text == null || pattern == null || loc == null) {
7497 throw new Error('Null input. (match_main)');
7498 }
7499
7500 loc = Math.max(0, Math.min(loc, text.length));
7501 if (text == pattern) {
7502 // Shortcut (potentially not guaranteed by the algorithm)
7503 return 0;
7504 } else if (!text.length) {
7505 // Nothing to match.
7506 return -1;
7507 } else if (text.substring(loc, loc + pattern.length) == pattern) {
7508 // Perfect match at the perfect spot! (Includes case of null pattern)
7509 return loc;
7510 } else {
7511 // Do a fuzzy compare.
7512 return this.match_bitap_(text, pattern, loc);
7513 }
7514};
7515
7516
7517/**
7518 * Locate the best instance of 'pattern' in 'text' near 'loc' using the
7519 * Bitap algorithm.
7520 * @param {string} text The text to search.
7521 * @param {string} pattern The pattern to search for.
7522 * @param {number} loc The location to search around.
7523 * @return {number} Best match index or -1.
7524 * @private
7525 */
7526diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) {
7527 if (pattern.length > this.Match_MaxBits) {
7528 throw new Error('Pattern too long for this browser.');
7529 }
7530
7531 // Initialise the alphabet.
7532 var s = this.match_alphabet_(pattern);
7533
7534 var dmp = this; // 'this' becomes 'window' in a closure.
7535
7536 /**
7537 * Compute and return the score for a match with e errors and x location.
7538 * Accesses loc and pattern through being a closure.
7539 * @param {number} e Number of errors in match.
7540 * @param {number} x Location of match.
7541 * @return {number} Overall score for match (0.0 = good, 1.0 = bad).
7542 * @private
7543 */
7544 function match_bitapScore_(e, x) {
7545 var accuracy = e / pattern.length;
7546 var proximity = Math.abs(loc - x);
7547 if (!dmp.Match_Distance) {
7548 // Dodge divide by zero error.
7549 return proximity ? 1.0 : accuracy;
7550 }
7551 return accuracy + (proximity / dmp.Match_Distance);
7552 }
7553
7554 // Highest score beyond which we give up.
7555 var score_threshold = this.Match_Threshold;
7556 // Is there a nearby exact match? (speedup)
7557 var best_loc = text.indexOf(pattern, loc);
7558 if (best_loc != -1) {
7559 score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold);
7560 // What about in the other direction? (speedup)
7561 best_loc = text.lastIndexOf(pattern, loc + pattern.length);
7562 if (best_loc != -1) {
7563 score_threshold =
7564 Math.min(match_bitapScore_(0, best_loc), score_threshold);
7565 }
7566 }
7567
7568 // Initialise the bit arrays.
7569 var matchmask = 1 << (pattern.length - 1);
7570 best_loc = -1;
7571
7572 var bin_min, bin_mid;
7573 var bin_max = pattern.length + text.length;
7574 var last_rd;
7575 for (var d = 0; d < pattern.length; d++) {
7576 // Scan for the best match; each iteration allows for one more error.
7577 // Run a binary search to determine how far from 'loc' we can stray at this
7578 // error level.
7579 bin_min = 0;
7580 bin_mid = bin_max;
7581 while (bin_min < bin_mid) {
7582 if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) {
7583 bin_min = bin_mid;
7584 } else {
7585 bin_max = bin_mid;
7586 }
7587 bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min);
7588 }
7589 // Use the result from this iteration as the maximum for the next.
7590 bin_max = bin_mid;
7591 var start = Math.max(1, loc - bin_mid + 1);
7592 var finish = Math.min(loc + bin_mid, text.length) + pattern.length;
7593
7594 var rd = Array(finish + 2);
7595 rd[finish + 1] = (1 << d) - 1;
7596 for (var j = finish; j >= start; j--) {
7597 // The alphabet (s) is a sparse hash, so the following line generates
7598 // warnings.
7599 var charMatch = s[text.charAt(j - 1)];
7600 if (d === 0) { // First pass: exact match.
7601 rd[j] = ((rd[j + 1] << 1) | 1) & charMatch;
7602 } else { // Subsequent passes: fuzzy match.
7603 rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) |
7604 (((last_rd[j + 1] | last_rd[j]) << 1) | 1) |
7605 last_rd[j + 1];
7606 }
7607 if (rd[j] & matchmask) {
7608 var score = match_bitapScore_(d, j - 1);
7609 // This match will almost certainly be better than any existing match.
7610 // But check anyway.
7611 if (score <= score_threshold) {
7612 // Told you so.
7613 score_threshold = score;
7614 best_loc = j - 1;
7615 if (best_loc > loc) {
7616 // When passing loc, don't exceed our current distance from loc.
7617 start = Math.max(1, 2 * loc - best_loc);
7618 } else {
7619 // Already passed loc, downhill from here on in.
7620 break;
7621 }
7622 }
7623 }
7624 }
7625 // No hope for a (better) match at greater error levels.
7626 if (match_bitapScore_(d + 1, loc) > score_threshold) {
7627 break;
7628 }
7629 last_rd = rd;
7630 }
7631 return best_loc;
7632};
7633
7634
7635/**
7636 * Initialise the alphabet for the Bitap algorithm.
7637 * @param {string} pattern The text to encode.
7638 * @return {!Object} Hash of character locations.
7639 * @private
7640 */
7641diff_match_patch.prototype.match_alphabet_ = function(pattern) {
7642 var s = {};
7643 for (var i = 0; i < pattern.length; i++) {
7644 s[pattern.charAt(i)] = 0;
7645 }
7646 for (var i = 0; i < pattern.length; i++) {
7647 s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1);
7648 }
7649 return s;
7650};
7651
7652
7653// PATCH FUNCTIONS
7654
7655
7656/**
7657 * Increase the context until it is unique,
7658 * but don't let the pattern expand beyond Match_MaxBits.
7659 * @param {!diff_match_patch.patch_obj} patch The patch to grow.
7660 * @param {string} text Source text.
7661 * @private
7662 */
7663diff_match_patch.prototype.patch_addContext_ = function(patch, text) {
7664 if (text.length == 0) {
7665 return;
7666 }
7667 var pattern = text.substring(patch.start2, patch.start2 + patch.length1);
7668 var padding = 0;
7669
7670 // Look for the first and last matches of pattern in text. If two different
7671 // matches are found, increase the pattern length.
7672 while (text.indexOf(pattern) != text.lastIndexOf(pattern) &&
7673 pattern.length < this.Match_MaxBits - this.Patch_Margin -
7674 this.Patch_Margin) {
7675 padding += this.Patch_Margin;
7676 pattern = text.substring(patch.start2 - padding,
7677 patch.start2 + patch.length1 + padding);
7678 }
7679 // Add one chunk for good luck.
7680 padding += this.Patch_Margin;
7681
7682 // Add the prefix.
7683 var prefix = text.substring(patch.start2 - padding, patch.start2);
7684 if (prefix) {
7685 patch.diffs.unshift([DIFF_EQUAL, prefix]);
7686 }
7687 // Add the suffix.
7688 var suffix = text.substring(patch.start2 + patch.length1,
7689 patch.start2 + patch.length1 + padding);
7690 if (suffix) {
7691 patch.diffs.push([DIFF_EQUAL, suffix]);
7692 }
7693
7694 // Roll back the start points.
7695 patch.start1 -= prefix.length;
7696 patch.start2 -= prefix.length;
7697 // Extend the lengths.
7698 patch.length1 += prefix.length + suffix.length;
7699 patch.length2 += prefix.length + suffix.length;
7700};
7701
7702
7703/**
7704 * Compute a list of patches to turn text1 into text2.
7705 * Use diffs if provided, otherwise compute it ourselves.
7706 * There are four ways to call this function, depending on what data is
7707 * available to the caller:
7708 * Method 1:
7709 * a = text1, b = text2
7710 * Method 2:
7711 * a = diffs
7712 * Method 3 (optimal):
7713 * a = text1, b = diffs
7714 * Method 4 (deprecated, use method 3):
7715 * a = text1, b = text2, c = diffs
7716 *
7717 * @param {string|!Array.<!diff_match_patch.Diff>} a text1 (methods 1,3,4) or
7718 * Array of diff tuples for text1 to text2 (method 2).
7719 * @param {string|!Array.<!diff_match_patch.Diff>} opt_b text2 (methods 1,4) or
7720 * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
7721 * @param {string|!Array.<!diff_match_patch.Diff>} opt_c Array of diff tuples
7722 * for text1 to text2 (method 4) or undefined (methods 1,2,3).
7723 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
7724 */
7725diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) {
7726 var text1, diffs;
7727 if (typeof a == 'string' && typeof opt_b == 'string' &&
7728 typeof opt_c == 'undefined') {
7729 // Method 1: text1, text2
7730 // Compute diffs from text1 and text2.
7731 text1 = /** @type {string} */(a);
7732 diffs = this.diff_main(text1, /** @type {string} */(opt_b), true);
7733 if (diffs.length > 2) {
7734 this.diff_cleanupSemantic(diffs);
7735 this.diff_cleanupEfficiency(diffs);
7736 }
7737 } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' &&
7738 typeof opt_c == 'undefined') {
7739 // Method 2: diffs
7740 // Compute text1 from diffs.
7741 diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(a);
7742 text1 = this.diff_text1(diffs);
7743 } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' &&
7744 typeof opt_c == 'undefined') {
7745 // Method 3: text1, diffs
7746 text1 = /** @type {string} */(a);
7747 diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_b);
7748 } else if (typeof a == 'string' && typeof opt_b == 'string' &&
7749 opt_c && typeof opt_c == 'object') {
7750 // Method 4: text1, text2, diffs
7751 // text2 is not used.
7752 text1 = /** @type {string} */(a);
7753 diffs = /** @type {!Array.<!diff_match_patch.Diff>} */(opt_c);
7754 } else {
7755 throw new Error('Unknown call format to patch_make.');
7756 }
7757
7758 if (diffs.length === 0) {
7759 return []; // Get rid of the null case.
7760 }
7761 var patches = [];
7762 var patch = new diff_match_patch.patch_obj();
7763 var patchDiffLength = 0; // Keeping our own length var is faster in JS.
7764 var char_count1 = 0; // Number of characters into the text1 string.
7765 var char_count2 = 0; // Number of characters into the text2 string.
7766 // Start with text1 (prepatch_text) and apply the diffs until we arrive at
7767 // text2 (postpatch_text). We recreate the patches one by one to determine
7768 // context info.
7769 var prepatch_text = text1;
7770 var postpatch_text = text1;
7771 for (var x = 0; x < diffs.length; x++) {
7772 var diff_type = diffs[x][0];
7773 var diff_text = diffs[x][1];
7774
7775 if (!patchDiffLength && diff_type !== DIFF_EQUAL) {
7776 // A new patch starts here.
7777 patch.start1 = char_count1;
7778 patch.start2 = char_count2;
7779 }
7780
7781 switch (diff_type) {
7782 case DIFF_INSERT:
7783 patch.diffs[patchDiffLength++] = diffs[x];
7784 patch.length2 += diff_text.length;
7785 postpatch_text = postpatch_text.substring(0, char_count2) + diff_text +
7786 postpatch_text.substring(char_count2);
7787 break;
7788 case DIFF_DELETE:
7789 patch.length1 += diff_text.length;
7790 patch.diffs[patchDiffLength++] = diffs[x];
7791 postpatch_text = postpatch_text.substring(0, char_count2) +
7792 postpatch_text.substring(char_count2 +
7793 diff_text.length);
7794 break;
7795 case DIFF_EQUAL:
7796 if (diff_text.length <= 2 * this.Patch_Margin &&
7797 patchDiffLength && diffs.length != x + 1) {
7798 // Small equality inside a patch.
7799 patch.diffs[patchDiffLength++] = diffs[x];
7800 patch.length1 += diff_text.length;
7801 patch.length2 += diff_text.length;
7802 } else if (diff_text.length >= 2 * this.Patch_Margin) {
7803 // Time for a new patch.
7804 if (patchDiffLength) {
7805 this.patch_addContext_(patch, prepatch_text);
7806 patches.push(patch);
7807 patch = new diff_match_patch.patch_obj();
7808 patchDiffLength = 0;
7809 // Unlike Unidiff, our patch lists have a rolling context.
7810 // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
7811 // Update prepatch text & pos to reflect the application of the
7812 // just completed patch.
7813 prepatch_text = postpatch_text;
7814 char_count1 = char_count2;
7815 }
7816 }
7817 break;
7818 }
7819
7820 // Update the current character count.
7821 if (diff_type !== DIFF_INSERT) {
7822 char_count1 += diff_text.length;
7823 }
7824 if (diff_type !== DIFF_DELETE) {
7825 char_count2 += diff_text.length;
7826 }
7827 }
7828 // Pick up the leftover patch if not empty.
7829 if (patchDiffLength) {
7830 this.patch_addContext_(patch, prepatch_text);
7831 patches.push(patch);
7832 }
7833
7834 return patches;
7835};
7836
7837
7838/**
7839 * Given an array of patches, return another array that is identical.
7840 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
7841 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
7842 */
7843diff_match_patch.prototype.patch_deepCopy = function(patches) {
7844 // Making deep copies is hard in JavaScript.
7845 var patchesCopy = [];
7846 for (var x = 0; x < patches.length; x++) {
7847 var patch = patches[x];
7848 var patchCopy = new diff_match_patch.patch_obj();
7849 patchCopy.diffs = [];
7850 for (var y = 0; y < patch.diffs.length; y++) {
7851 patchCopy.diffs[y] = patch.diffs[y].slice();
7852 }
7853 patchCopy.start1 = patch.start1;
7854 patchCopy.start2 = patch.start2;
7855 patchCopy.length1 = patch.length1;
7856 patchCopy.length2 = patch.length2;
7857 patchesCopy[x] = patchCopy;
7858 }
7859 return patchesCopy;
7860};
7861
7862
7863/**
7864 * Merge a set of patches onto the text. Return a patched text, as well
7865 * as a list of true/false values indicating which patches were applied.
7866 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
7867 * @param {string} text Old text.
7868 * @return {!Array.<string|!Array.<boolean>>} Two element Array, containing the
7869 * new text and an array of boolean values.
7870 */
7871diff_match_patch.prototype.patch_apply = function(patches, text) {
7872 if (patches.length == 0) {
7873 return [text, []];
7874 }
7875
7876 // Deep copy the patches so that no changes are made to originals.
7877 patches = this.patch_deepCopy(patches);
7878
7879 var nullPadding = this.patch_addPadding(patches);
7880 text = nullPadding + text + nullPadding;
7881
7882 this.patch_splitMax(patches);
7883 // delta keeps track of the offset between the expected and actual location
7884 // of the previous patch. If there are patches expected at positions 10 and
7885 // 20, but the first patch was found at 12, delta is 2 and the second patch
7886 // has an effective expected position of 22.
7887 var delta = 0;
7888 var results = [];
7889 for (var x = 0; x < patches.length; x++) {
7890 var expected_loc = patches[x].start2 + delta;
7891 var text1 = this.diff_text1(patches[x].diffs);
7892 var start_loc;
7893 var end_loc = -1;
7894 if (text1.length > this.Match_MaxBits) {
7895 // patch_splitMax will only provide an oversized pattern in the case of
7896 // a monster delete.
7897 start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits),
7898 expected_loc);
7899 if (start_loc != -1) {
7900 end_loc = this.match_main(text,
7901 text1.substring(text1.length - this.Match_MaxBits),
7902 expected_loc + text1.length - this.Match_MaxBits);
7903 if (end_loc == -1 || start_loc >= end_loc) {
7904 // Can't find valid trailing context. Drop this patch.
7905 start_loc = -1;
7906 }
7907 }
7908 } else {
7909 start_loc = this.match_main(text, text1, expected_loc);
7910 }
7911 if (start_loc == -1) {
7912 // No match found. :(
7913 results[x] = false;
7914 // Subtract the delta for this failed patch from subsequent patches.
7915 delta -= patches[x].length2 - patches[x].length1;
7916 } else {
7917 // Found a match. :)
7918 results[x] = true;
7919 delta = start_loc - expected_loc;
7920 var text2;
7921 if (end_loc == -1) {
7922 text2 = text.substring(start_loc, start_loc + text1.length);
7923 } else {
7924 text2 = text.substring(start_loc, end_loc + this.Match_MaxBits);
7925 }
7926 if (text1 == text2) {
7927 // Perfect match, just shove the replacement text in.
7928 text = text.substring(0, start_loc) +
7929 this.diff_text2(patches[x].diffs) +
7930 text.substring(start_loc + text1.length);
7931 } else {
7932 // Imperfect match. Run a diff to get a framework of equivalent
7933 // indices.
7934 var diffs = this.diff_main(text1, text2, false);
7935 if (text1.length > this.Match_MaxBits &&
7936 this.diff_levenshtein(diffs) / text1.length >
7937 this.Patch_DeleteThreshold) {
7938 // The end points match, but the content is unacceptably bad.
7939 results[x] = false;
7940 } else {
7941 this.diff_cleanupSemanticLossless(diffs);
7942 var index1 = 0;
7943 var index2;
7944 for (var y = 0; y < patches[x].diffs.length; y++) {
7945 var mod = patches[x].diffs[y];
7946 if (mod[0] !== DIFF_EQUAL) {
7947 index2 = this.diff_xIndex(diffs, index1);
7948 }
7949 if (mod[0] === DIFF_INSERT) { // Insertion
7950 text = text.substring(0, start_loc + index2) + mod[1] +
7951 text.substring(start_loc + index2);
7952 } else if (mod[0] === DIFF_DELETE) { // Deletion
7953 text = text.substring(0, start_loc + index2) +
7954 text.substring(start_loc + this.diff_xIndex(diffs,
7955 index1 + mod[1].length));
7956 }
7957 if (mod[0] !== DIFF_DELETE) {
7958 index1 += mod[1].length;
7959 }
7960 }
7961 }
7962 }
7963 }
7964 }
7965 // Strip the padding off.
7966 text = text.substring(nullPadding.length, text.length - nullPadding.length);
7967 return [text, results];
7968};
7969
7970
7971/**
7972 * Add some padding on text start and end so that edges can match something.
7973 * Intended to be called only from within patch_apply.
7974 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
7975 * @return {string} The padding string added to each side.
7976 */
7977diff_match_patch.prototype.patch_addPadding = function(patches) {
7978 var paddingLength = this.Patch_Margin;
7979 var nullPadding = '';
7980 for (var x = 1; x <= paddingLength; x++) {
7981 nullPadding += String.fromCharCode(x);
7982 }
7983
7984 // Bump all the patches forward.
7985 for (var x = 0; x < patches.length; x++) {
7986 patches[x].start1 += paddingLength;
7987 patches[x].start2 += paddingLength;
7988 }
7989
7990 // Add some padding on start of first diff.
7991 var patch = patches[0];
7992 var diffs = patch.diffs;
7993 if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) {
7994 // Add nullPadding equality.
7995 diffs.unshift([DIFF_EQUAL, nullPadding]);
7996 patch.start1 -= paddingLength; // Should be 0.
7997 patch.start2 -= paddingLength; // Should be 0.
7998 patch.length1 += paddingLength;
7999 patch.length2 += paddingLength;
8000 } else if (paddingLength > diffs[0][1].length) {
8001 // Grow first equality.
8002 var extraLength = paddingLength - diffs[0][1].length;
8003 diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1];
8004 patch.start1 -= extraLength;
8005 patch.start2 -= extraLength;
8006 patch.length1 += extraLength;
8007 patch.length2 += extraLength;
8008 }
8009
8010 // Add some padding on end of last diff.
8011 patch = patches[patches.length - 1];
8012 diffs = patch.diffs;
8013 if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) {
8014 // Add nullPadding equality.
8015 diffs.push([DIFF_EQUAL, nullPadding]);
8016 patch.length1 += paddingLength;
8017 patch.length2 += paddingLength;
8018 } else if (paddingLength > diffs[diffs.length - 1][1].length) {
8019 // Grow last equality.
8020 var extraLength = paddingLength - diffs[diffs.length - 1][1].length;
8021 diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength);
8022 patch.length1 += extraLength;
8023 patch.length2 += extraLength;
8024 }
8025
8026 return nullPadding;
8027};
8028
8029
8030/**
8031 * Look through the patches and break up any which are longer than the maximum
8032 * limit of the match algorithm.
8033 * Intended to be called only from within patch_apply.
8034 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
8035 */
8036diff_match_patch.prototype.patch_splitMax = function(patches) {
8037 var patch_size = this.Match_MaxBits;
8038 for (var x = 0; x < patches.length; x++) {
8039 if (patches[x].length1 <= patch_size) {
8040 continue;
8041 }
8042 var bigpatch = patches[x];
8043 // Remove the big old patch.
8044 patches.splice(x--, 1);
8045 var start1 = bigpatch.start1;
8046 var start2 = bigpatch.start2;
8047 var precontext = '';
8048 while (bigpatch.diffs.length !== 0) {
8049 // Create one of several smaller patches.
8050 var patch = new diff_match_patch.patch_obj();
8051 var empty = true;
8052 patch.start1 = start1 - precontext.length;
8053 patch.start2 = start2 - precontext.length;
8054 if (precontext !== '') {
8055 patch.length1 = patch.length2 = precontext.length;
8056 patch.diffs.push([DIFF_EQUAL, precontext]);
8057 }
8058 while (bigpatch.diffs.length !== 0 &&
8059 patch.length1 < patch_size - this.Patch_Margin) {
8060 var diff_type = bigpatch.diffs[0][0];
8061 var diff_text = bigpatch.diffs[0][1];
8062 if (diff_type === DIFF_INSERT) {
8063 // Insertions are harmless.
8064 patch.length2 += diff_text.length;
8065 start2 += diff_text.length;
8066 patch.diffs.push(bigpatch.diffs.shift());
8067 empty = false;
8068 } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 &&
8069 patch.diffs[0][0] == DIFF_EQUAL &&
8070 diff_text.length > 2 * patch_size) {
8071 // This is a large deletion. Let it pass in one chunk.
8072 patch.length1 += diff_text.length;
8073 start1 += diff_text.length;
8074 empty = false;
8075 patch.diffs.push([diff_type, diff_text]);
8076 bigpatch.diffs.shift();
8077 } else {
8078 // Deletion or equality. Only take as much as we can stomach.
8079 diff_text = diff_text.substring(0,
8080 patch_size - patch.length1 - this.Patch_Margin);
8081 patch.length1 += diff_text.length;
8082 start1 += diff_text.length;
8083 if (diff_type === DIFF_EQUAL) {
8084 patch.length2 += diff_text.length;
8085 start2 += diff_text.length;
8086 } else {
8087 empty = false;
8088 }
8089 patch.diffs.push([diff_type, diff_text]);
8090 if (diff_text == bigpatch.diffs[0][1]) {
8091 bigpatch.diffs.shift();
8092 } else {
8093 bigpatch.diffs[0][1] =
8094 bigpatch.diffs[0][1].substring(diff_text.length);
8095 }
8096 }
8097 }
8098 // Compute the head context for the next patch.
8099 precontext = this.diff_text2(patch.diffs);
8100 precontext =
8101 precontext.substring(precontext.length - this.Patch_Margin);
8102 // Append the end context for this patch.
8103 var postcontext = this.diff_text1(bigpatch.diffs)
8104 .substring(0, this.Patch_Margin);
8105 if (postcontext !== '') {
8106 patch.length1 += postcontext.length;
8107 patch.length2 += postcontext.length;
8108 if (patch.diffs.length !== 0 &&
8109 patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) {
8110 patch.diffs[patch.diffs.length - 1][1] += postcontext;
8111 } else {
8112 patch.diffs.push([DIFF_EQUAL, postcontext]);
8113 }
8114 }
8115 if (!empty) {
8116 patches.splice(++x, 0, patch);
8117 }
8118 }
8119 }
8120};
8121
8122
8123/**
8124 * Take a list of patches and return a textual representation.
8125 * @param {!Array.<!diff_match_patch.patch_obj>} patches Array of Patch objects.
8126 * @return {string} Text representation of patches.
8127 */
8128diff_match_patch.prototype.patch_toText = function(patches) {
8129 var text = [];
8130 for (var x = 0; x < patches.length; x++) {
8131 text[x] = patches[x];
8132 }
8133 return text.join('');
8134};
8135
8136
8137/**
8138 * Parse a textual representation of patches and return a list of Patch objects.
8139 * @param {string} textline Text representation of patches.
8140 * @return {!Array.<!diff_match_patch.patch_obj>} Array of Patch objects.
8141 * @throws {!Error} If invalid input.
8142 */
8143diff_match_patch.prototype.patch_fromText = function(textline) {
8144 var patches = [];
8145 if (!textline) {
8146 return patches;
8147 }
8148 var text = textline.split('\n');
8149 var textPointer = 0;
8150 var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;
8151 while (textPointer < text.length) {
8152 var m = text[textPointer].match(patchHeader);
8153 if (!m) {
8154 throw new Error('Invalid patch string: ' + text[textPointer]);
8155 }
8156 var patch = new diff_match_patch.patch_obj();
8157 patches.push(patch);
8158 patch.start1 = parseInt(m[1], 10);
8159 if (m[2] === '') {
8160 patch.start1--;
8161 patch.length1 = 1;
8162 } else if (m[2] == '0') {
8163 patch.length1 = 0;
8164 } else {
8165 patch.start1--;
8166 patch.length1 = parseInt(m[2], 10);
8167 }
8168
8169 patch.start2 = parseInt(m[3], 10);
8170 if (m[4] === '') {
8171 patch.start2--;
8172 patch.length2 = 1;
8173 } else if (m[4] == '0') {
8174 patch.length2 = 0;
8175 } else {
8176 patch.start2--;
8177 patch.length2 = parseInt(m[4], 10);
8178 }
8179 textPointer++;
8180
8181 while (textPointer < text.length) {
8182 var sign = text[textPointer].charAt(0);
8183 try {
8184 var line = decodeURI(text[textPointer].substring(1));
8185 } catch (ex) {
8186 // Malformed URI sequence.
8187 throw new Error('Illegal escape in patch_fromText: ' + line);
8188 }
8189 if (sign == '-') {
8190 // Deletion.
8191 patch.diffs.push([DIFF_DELETE, line]);
8192 } else if (sign == '+') {
8193 // Insertion.
8194 patch.diffs.push([DIFF_INSERT, line]);
8195 } else if (sign == ' ') {
8196 // Minor equality.
8197 patch.diffs.push([DIFF_EQUAL, line]);
8198 } else if (sign == '@') {
8199 // Start of next patch.
8200 break;
8201 } else if (sign === '') {
8202 // Blank line? Whatever.
8203 } else {
8204 // WTF?
8205 throw new Error('Invalid patch mode "' + sign + '" in: ' + line);
8206 }
8207 textPointer++;
8208 }
8209 }
8210 return patches;
8211};
8212
8213
8214/**
8215 * Class representing one patch operation.
8216 * @constructor
8217 */
8218diff_match_patch.patch_obj = function() {
8219 /** @type {!Array.<!diff_match_patch.Diff>} */
8220 this.diffs = [];
8221 /** @type {?number} */
8222 this.start1 = null;
8223 /** @type {?number} */
8224 this.start2 = null;
8225 /** @type {number} */
8226 this.length1 = 0;
8227 /** @type {number} */
8228 this.length2 = 0;
8229};
8230
8231
8232/**
8233 * Emmulate GNU diff's format.
8234 * Header: @@ -382,8 +481,9 @@
8235 * Indicies are printed as 1-based, not 0-based.
8236 * @return {string} The GNU diff string.
8237 */
8238diff_match_patch.patch_obj.prototype.toString = function() {
8239 var coords1, coords2;
8240 if (this.length1 === 0) {
8241 coords1 = this.start1 + ',0';
8242 } else if (this.length1 == 1) {
8243 coords1 = this.start1 + 1;
8244 } else {
8245 coords1 = (this.start1 + 1) + ',' + this.length1;
8246 }
8247 if (this.length2 === 0) {
8248 coords2 = this.start2 + ',0';
8249 } else if (this.length2 == 1) {
8250 coords2 = this.start2 + 1;
8251 } else {
8252 coords2 = (this.start2 + 1) + ',' + this.length2;
8253 }
8254 var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n'];
8255 var op;
8256 // Escape the body of the patch with %xx notation.
8257 for (var x = 0; x < this.diffs.length; x++) {
8258 switch (this.diffs[x][0]) {
8259 case DIFF_INSERT:
8260 op = '+';
8261 break;
8262 case DIFF_DELETE:
8263 op = '-';
8264 break;
8265 case DIFF_EQUAL:
8266 op = ' ';
8267 break;
8268 }
8269 text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n';
8270 }
8271 return text.join('').replace(/%20/g, ' ');
8272};
8273
8274
8275// Export these global variables so that they survive Google's JS compiler.
8276// In a browser, 'this' will be 'window'.
8277// Users of node.js should 'require' the uncompressed version since Google's
8278// JS compiler may break the following exports for non-browser environments.
8279this['diff_match_patch'] = diff_match_patch;
8280this['DIFF_DELETE'] = DIFF_DELETE;
8281this['DIFF_INSERT'] = DIFF_INSERT;
8282this['DIFF_EQUAL'] = DIFF_EQUAL;
8283
8284},{}],27:[function(_dereq_,module,exports){
8285
8286var indexOf = [].indexOf;
8287
8288module.exports = function(arr, obj){
8289 if (indexOf) return arr.indexOf(obj);
8290 for (var i = 0; i < arr.length; ++i) {
8291 if (arr[i] === obj) return i;
8292 }
8293 return -1;
8294};
8295},{}],28:[function(_dereq_,module,exports){
8296if (typeof Object.create === 'function') {
8297 // implementation from standard node.js 'util' module
8298 module.exports = function inherits(ctor, superCtor) {
8299 ctor.super_ = superCtor
8300 ctor.prototype = Object.create(superCtor.prototype, {
8301 constructor: {
8302 value: ctor,
8303 enumerable: false,
8304 writable: true,
8305 configurable: true
8306 }
8307 });
8308 };
8309} else {
8310 // old school shim for old browsers
8311 module.exports = function inherits(ctor, superCtor) {
8312 ctor.super_ = superCtor
8313 var TempCtor = function () {}
8314 TempCtor.prototype = superCtor.prototype
8315 ctor.prototype = new TempCtor()
8316 ctor.prototype.constructor = ctor
8317 }
8318}
8319
8320},{}],29:[function(_dereq_,module,exports){
8321'use strict';
8322
8323// modified from https://github.com/es-shims/es5-shim
8324var has = Object.prototype.hasOwnProperty;
8325var toStr = Object.prototype.toString;
8326var slice = Array.prototype.slice;
8327var isArgs = _dereq_('./isArguments');
8328var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
8329var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
8330var dontEnums = [
8331 'toString',
8332 'toLocaleString',
8333 'valueOf',
8334 'hasOwnProperty',
8335 'isPrototypeOf',
8336 'propertyIsEnumerable',
8337 'constructor'
8338];
8339var equalsConstructorPrototype = function (o) {
8340 var ctor = o.constructor;
8341 return ctor && ctor.prototype === o;
8342};
8343var blacklistedKeys = {
8344 $console: true,
8345 $frame: true,
8346 $frameElement: true,
8347 $frames: true,
8348 $parent: true,
8349 $self: true,
8350 $webkitIndexedDB: true,
8351 $webkitStorageInfo: true,
8352 $window: true
8353};
8354var hasAutomationEqualityBug = (function () {
8355 /* global window */
8356 if (typeof window === 'undefined') { return false; }
8357 for (var k in window) {
8358 try {
8359 if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
8360 try {
8361 equalsConstructorPrototype(window[k]);
8362 } catch (e) {
8363 return true;
8364 }
8365 }
8366 } catch (e) {
8367 return true;
8368 }
8369 }
8370 return false;
8371}());
8372var equalsConstructorPrototypeIfNotBuggy = function (o) {
8373 /* global window */
8374 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
8375 return equalsConstructorPrototype(o);
8376 }
8377 try {
8378 return equalsConstructorPrototype(o);
8379 } catch (e) {
8380 return false;
8381 }
8382};
8383
8384var keysShim = function keys(object) {
8385 var isObject = object !== null && typeof object === 'object';
8386 var isFunction = toStr.call(object) === '[object Function]';
8387 var isArguments = isArgs(object);
8388 var isString = isObject && toStr.call(object) === '[object String]';
8389 var theKeys = [];
8390
8391 if (!isObject && !isFunction && !isArguments) {
8392 throw new TypeError('Object.keys called on a non-object');
8393 }
8394
8395 var skipProto = hasProtoEnumBug && isFunction;
8396 if (isString && object.length > 0 && !has.call(object, 0)) {
8397 for (var i = 0; i < object.length; ++i) {
8398 theKeys.push(String(i));
8399 }
8400 }
8401
8402 if (isArguments && object.length > 0) {
8403 for (var j = 0; j < object.length; ++j) {
8404 theKeys.push(String(j));
8405 }
8406 } else {
8407 for (var name in object) {
8408 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
8409 theKeys.push(String(name));
8410 }
8411 }
8412 }
8413
8414 if (hasDontEnumBug) {
8415 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
8416
8417 for (var k = 0; k < dontEnums.length; ++k) {
8418 if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
8419 theKeys.push(dontEnums[k]);
8420 }
8421 }
8422 }
8423 return theKeys;
8424};
8425
8426keysShim.shim = function shimObjectKeys() {
8427 if (Object.keys) {
8428 var keysWorksWithArguments = (function () {
8429 // Safari 5.0 bug
8430 return (Object.keys(arguments) || '').length === 2;
8431 }(1, 2));
8432 if (!keysWorksWithArguments) {
8433 var originalKeys = Object.keys;
8434 Object.keys = function keys(object) {
8435 if (isArgs(object)) {
8436 return originalKeys(slice.call(object));
8437 } else {
8438 return originalKeys(object);
8439 }
8440 };
8441 }
8442 } else {
8443 Object.keys = keysShim;
8444 }
8445 return Object.keys || keysShim;
8446};
8447
8448module.exports = keysShim;
8449
8450},{"./isArguments":30}],30:[function(_dereq_,module,exports){
8451'use strict';
8452
8453var toStr = Object.prototype.toString;
8454
8455module.exports = function isArguments(value) {
8456 var str = toStr.call(value);
8457 var isArgs = str === '[object Arguments]';
8458 if (!isArgs) {
8459 isArgs = str !== '[object Array]' &&
8460 value !== null &&
8461 typeof value === 'object' &&
8462 typeof value.length === 'number' &&
8463 value.length >= 0 &&
8464 toStr.call(value.callee) === '[object Function]';
8465 }
8466 return isArgs;
8467};
8468
8469},{}],31:[function(_dereq_,module,exports){
8470// shim for using process in browser
8471
8472var process = module.exports = {};
8473var queue = [];
8474var draining = false;
8475var currentQueue;
8476var queueIndex = -1;
8477
8478function cleanUpNextTick() {
8479 draining = false;
8480 if (currentQueue.length) {
8481 queue = currentQueue.concat(queue);
8482 } else {
8483 queueIndex = -1;
8484 }
8485 if (queue.length) {
8486 drainQueue();
8487 }
8488}
8489
8490function drainQueue() {
8491 if (draining) {
8492 return;
8493 }
8494 var timeout = setTimeout(cleanUpNextTick);
8495 draining = true;
8496
8497 var len = queue.length;
8498 while(len) {
8499 currentQueue = queue;
8500 queue = [];
8501 while (++queueIndex < len) {
8502 if (currentQueue) {
8503 currentQueue[queueIndex].run();
8504 }
8505 }
8506 queueIndex = -1;
8507 len = queue.length;
8508 }
8509 currentQueue = null;
8510 draining = false;
8511 clearTimeout(timeout);
8512}
8513
8514process.nextTick = function (fun) {
8515 var args = new Array(arguments.length - 1);
8516 if (arguments.length > 1) {
8517 for (var i = 1; i < arguments.length; i++) {
8518 args[i - 1] = arguments[i];
8519 }
8520 }
8521 queue.push(new Item(fun, args));
8522 if (queue.length === 1 && !draining) {
8523 setTimeout(drainQueue, 0);
8524 }
8525};
8526
8527// v8 likes predictible objects
8528function Item(fun, array) {
8529 this.fun = fun;
8530 this.array = array;
8531}
8532Item.prototype.run = function () {
8533 this.fun.apply(null, this.array);
8534};
8535process.title = 'browser';
8536process.browser = true;
8537process.env = {};
8538process.argv = [];
8539process.version = ''; // empty string to avoid regexp issues
8540process.versions = {};
8541
8542function noop() {}
8543
8544process.on = noop;
8545process.addListener = noop;
8546process.once = noop;
8547process.off = noop;
8548process.removeListener = noop;
8549process.removeAllListeners = noop;
8550process.emit = noop;
8551
8552process.binding = function (name) {
8553 throw new Error('process.binding is not supported');
8554};
8555
8556process.cwd = function () { return '/' };
8557process.chdir = function (dir) {
8558 throw new Error('process.chdir is not supported');
8559};
8560process.umask = function() { return 0; };
8561
8562},{}],32:[function(_dereq_,module,exports){
8563/**
8564 * stringifier
8565 *
8566 * https://github.com/twada/stringifier
8567 *
8568 * Copyright (c) 2014-2015 Takuto Wada
8569 * Licensed under the MIT license.
8570 * http://twada.mit-license.org/2014-2015
8571 */
8572'use strict';
8573
8574var traverse = _dereq_('traverse');
8575var typeName = _dereq_('type-name');
8576var extend = _dereq_('xtend');
8577var s = _dereq_('./strategies');
8578
8579function defaultHandlers () {
8580 return {
8581 'null': s.always('null'),
8582 'undefined': s.always('undefined'),
8583 'function': s.prune(),
8584 'string': s.json(),
8585 'boolean': s.json(),
8586 'number': s.number(),
8587 'symbol': s.toStr(),
8588 'RegExp': s.toStr(),
8589 'String': s.newLike(),
8590 'Boolean': s.newLike(),
8591 'Number': s.newLike(),
8592 'Date': s.newLike(),
8593 'Array': s.array(),
8594 'Object': s.object(),
8595 '@default': s.object()
8596 };
8597}
8598
8599function defaultOptions () {
8600 return {
8601 maxDepth: null,
8602 indent: null,
8603 anonymous: '@Anonymous',
8604 circular: '#@Circular#',
8605 snip: '..(snip)',
8606 lineSeparator: '\n',
8607 typeFun: typeName
8608 };
8609}
8610
8611function createStringifier (customOptions) {
8612 var options = extend(defaultOptions(), customOptions);
8613 var handlers = extend(defaultHandlers(), options.handlers);
8614 return function stringifyAny (push, x) {
8615 var context = this;
8616 var handler = handlerFor(context.node, options, handlers);
8617 var currentPath = '/' + context.path.join('/');
8618 var customization = handlers[currentPath];
8619 var acc = {
8620 context: context,
8621 options: options,
8622 handlers: handlers,
8623 push: push
8624 };
8625 if (typeName(customization) === 'function') {
8626 handler = customization;
8627 } else if (typeName(customization) === 'number') {
8628 handler = s.flow.compose(s.filters.truncate(customization),handler);
8629 } else if (context.parent && typeName(context.parent.node) === 'Array' && !(context.key in context.parent.node)) {
8630 // sparse arrays
8631 handler = s.always('');
8632 }
8633 handler(acc, x);
8634 return push;
8635 };
8636}
8637
8638function handlerFor (val, options, handlers) {
8639 var tname = options.typeFun(val);
8640 if (typeName(handlers[tname]) === 'function') {
8641 return handlers[tname];
8642 }
8643 return handlers['@default'];
8644}
8645
8646function walk (val, reducer) {
8647 var buffer = [];
8648 var push = function (str) {
8649 buffer.push(str);
8650 };
8651 traverse(val).reduce(reducer, push);
8652 return buffer.join('');
8653}
8654
8655function stringify (val, options) {
8656 return walk(val, createStringifier(options));
8657}
8658
8659function stringifier (options) {
8660 return function (val) {
8661 return walk(val, createStringifier(options));
8662 };
8663}
8664
8665stringifier.stringify = stringify;
8666stringifier.strategies = s;
8667stringifier.defaultOptions = defaultOptions;
8668stringifier.defaultHandlers = defaultHandlers;
8669module.exports = stringifier;
8670
8671},{"./strategies":33,"traverse":34,"type-name":35,"xtend":38}],33:[function(_dereq_,module,exports){
8672'use strict';
8673
8674var typeName = _dereq_('type-name');
8675var forEach = _dereq_('array-foreach');
8676var arrayFilter = _dereq_('array-filter');
8677var reduceRight = _dereq_('array-reduce-right');
8678var indexOf = _dereq_('indexof');
8679var slice = Array.prototype.slice;
8680var END = {};
8681var ITERATE = {};
8682
8683// arguments should end with end or iterate
8684function compose () {
8685 var filters = slice.apply(arguments);
8686 return reduceRight(filters, function(right, left) {
8687 return left(right);
8688 });
8689}
8690
8691// skip children
8692function end () {
8693 return function (acc, x) {
8694 acc.context.keys = [];
8695 return END;
8696 };
8697}
8698
8699// iterate children
8700function iterate () {
8701 return function (acc, x) {
8702 return ITERATE;
8703 };
8704}
8705
8706function filter (predicate) {
8707 return function (next) {
8708 return function (acc, x) {
8709 var toBeIterated;
8710 var isIteratingArray = (typeName(x) === 'Array');
8711 if (typeName(predicate) === 'function') {
8712 toBeIterated = [];
8713 forEach(acc.context.keys, function (key) {
8714 var indexOrKey = isIteratingArray ? parseInt(key, 10) : key;
8715 var kvp = {
8716 key: indexOrKey,
8717 value: x[key]
8718 };
8719 var decision = predicate(kvp);
8720 if (decision) {
8721 toBeIterated.push(key);
8722 }
8723 if (typeName(decision) === 'number') {
8724 truncateByKey(decision, key, acc);
8725 }
8726 if (typeName(decision) === 'function') {
8727 customizeStrategyForKey(decision, key, acc);
8728 }
8729 });
8730 acc.context.keys = toBeIterated;
8731 }
8732 return next(acc, x);
8733 };
8734 };
8735}
8736
8737function customizeStrategyForKey (strategy, key, acc) {
8738 acc.handlers[currentPath(key, acc)] = strategy;
8739}
8740
8741function truncateByKey (size, key, acc) {
8742 acc.handlers[currentPath(key, acc)] = size;
8743}
8744
8745function currentPath (key, acc) {
8746 var pathToCurrentNode = [''].concat(acc.context.path);
8747 if (typeName(key) !== 'undefined') {
8748 pathToCurrentNode.push(key);
8749 }
8750 return pathToCurrentNode.join('/');
8751}
8752
8753function allowedKeys (orderedWhiteList) {
8754 return function (next) {
8755 return function (acc, x) {
8756 var isIteratingArray = (typeName(x) === 'Array');
8757 if (!isIteratingArray && typeName(orderedWhiteList) === 'Array') {
8758 acc.context.keys = arrayFilter(orderedWhiteList, function (propKey) {
8759 return indexOf(acc.context.keys, propKey) !== -1;
8760 });
8761 }
8762 return next(acc, x);
8763 };
8764 };
8765}
8766
8767function safeKeys () {
8768 return function (next) {
8769 return function (acc, x) {
8770 if (typeName(x) !== 'Array') {
8771 acc.context.keys = arrayFilter(acc.context.keys, function (propKey) {
8772 // Error handling for unsafe property access.
8773 // For example, on PhantomJS,
8774 // accessing HTMLInputElement.selectionEnd causes TypeError
8775 try {
8776 var val = x[propKey];
8777 return true;
8778 } catch (e) {
8779 // skip unsafe key
8780 return false;
8781 }
8782 });
8783 }
8784 return next(acc, x);
8785 };
8786 };
8787}
8788
8789function arrayIndicesToKeys () {
8790 return function (next) {
8791 return function (acc, x) {
8792 if (typeName(x) === 'Array' && 0 < x.length) {
8793 var indices = Array(x.length);
8794 for(var i = 0; i < x.length; i += 1) {
8795 indices[i] = String(i); // traverse uses strings as keys
8796 }
8797 acc.context.keys = indices;
8798 }
8799 return next(acc, x);
8800 };
8801 };
8802}
8803
8804function when (guard, then) {
8805 return function (next) {
8806 return function (acc, x) {
8807 var kvp = {
8808 key: acc.context.key,
8809 value: x
8810 };
8811 if (guard(kvp, acc)) {
8812 return then(acc, x);
8813 }
8814 return next(acc, x);
8815 };
8816 };
8817}
8818
8819function truncate (size) {
8820 return function (next) {
8821 return function (acc, x) {
8822 var orig = acc.push;
8823 var ret;
8824 acc.push = function (str) {
8825 var savings = str.length - size;
8826 var truncated;
8827 if (savings <= size) {
8828 orig.call(acc, str);
8829 } else {
8830 truncated = str.substring(0, size);
8831 orig.call(acc, truncated + acc.options.snip);
8832 }
8833 };
8834 ret = next(acc, x);
8835 acc.push = orig;
8836 return ret;
8837 };
8838 };
8839}
8840
8841function constructorName () {
8842 return function (next) {
8843 return function (acc, x) {
8844 var name = acc.options.typeFun(x);
8845 if (name === '') {
8846 name = acc.options.anonymous;
8847 }
8848 acc.push(name);
8849 return next(acc, x);
8850 };
8851 };
8852}
8853
8854function always (str) {
8855 return function (next) {
8856 return function (acc, x) {
8857 acc.push(str);
8858 return next(acc, x);
8859 };
8860 };
8861}
8862
8863function optionValue (key) {
8864 return function (next) {
8865 return function (acc, x) {
8866 acc.push(acc.options[key]);
8867 return next(acc, x);
8868 };
8869 };
8870}
8871
8872function json (replacer) {
8873 return function (next) {
8874 return function (acc, x) {
8875 acc.push(JSON.stringify(x, replacer));
8876 return next(acc, x);
8877 };
8878 };
8879}
8880
8881function toStr () {
8882 return function (next) {
8883 return function (acc, x) {
8884 acc.push(x.toString());
8885 return next(acc, x);
8886 };
8887 };
8888}
8889
8890function decorateArray () {
8891 return function (next) {
8892 return function (acc, x) {
8893 acc.context.before(function (node) {
8894 acc.push('[');
8895 });
8896 acc.context.after(function (node) {
8897 afterAllChildren(this, acc.push, acc.options);
8898 acc.push(']');
8899 });
8900 acc.context.pre(function (val, key) {
8901 beforeEachChild(this, acc.push, acc.options);
8902 });
8903 acc.context.post(function (childContext) {
8904 afterEachChild(childContext, acc.push);
8905 });
8906 return next(acc, x);
8907 };
8908 };
8909}
8910
8911function decorateObject () {
8912 return function (next) {
8913 return function (acc, x) {
8914 acc.context.before(function (node) {
8915 acc.push('{');
8916 });
8917 acc.context.after(function (node) {
8918 afterAllChildren(this, acc.push, acc.options);
8919 acc.push('}');
8920 });
8921 acc.context.pre(function (val, key) {
8922 beforeEachChild(this, acc.push, acc.options);
8923 acc.push(sanitizeKey(key) + (acc.options.indent ? ': ' : ':'));
8924 });
8925 acc.context.post(function (childContext) {
8926 afterEachChild(childContext, acc.push);
8927 });
8928 return next(acc, x);
8929 };
8930 };
8931}
8932
8933function sanitizeKey (key) {
8934 return /^[A-Za-z_]+$/.test(key) ? key : JSON.stringify(key);
8935}
8936
8937function afterAllChildren (context, push, options) {
8938 if (options.indent && 0 < context.keys.length) {
8939 push(options.lineSeparator);
8940 for(var i = 0; i < context.level; i += 1) { // indent level - 1
8941 push(options.indent);
8942 }
8943 }
8944}
8945
8946function beforeEachChild (context, push, options) {
8947 if (options.indent) {
8948 push(options.lineSeparator);
8949 for(var i = 0; i <= context.level; i += 1) {
8950 push(options.indent);
8951 }
8952 }
8953}
8954
8955function afterEachChild (childContext, push) {
8956 if (!childContext.isLast) {
8957 push(',');
8958 }
8959}
8960
8961function nan (kvp, acc) {
8962 return kvp.value !== kvp.value;
8963}
8964
8965function positiveInfinity (kvp, acc) {
8966 return !isFinite(kvp.value) && kvp.value === Infinity;
8967}
8968
8969function negativeInfinity (kvp, acc) {
8970 return !isFinite(kvp.value) && kvp.value !== Infinity;
8971}
8972
8973function circular (kvp, acc) {
8974 return acc.context.circular;
8975}
8976
8977function maxDepth (kvp, acc) {
8978 return (acc.options.maxDepth && acc.options.maxDepth <= acc.context.level);
8979}
8980
8981var prune = compose(
8982 always('#'),
8983 constructorName(),
8984 always('#'),
8985 end()
8986);
8987var omitNaN = when(nan, compose(
8988 always('NaN'),
8989 end()
8990));
8991var omitPositiveInfinity = when(positiveInfinity, compose(
8992 always('Infinity'),
8993 end()
8994));
8995var omitNegativeInfinity = when(negativeInfinity, compose(
8996 always('-Infinity'),
8997 end()
8998));
8999var omitCircular = when(circular, compose(
9000 optionValue('circular'),
9001 end()
9002));
9003var omitMaxDepth = when(maxDepth, prune);
9004
9005module.exports = {
9006 filters: {
9007 always: always,
9008 constructorName: constructorName,
9009 json: json,
9010 toStr: toStr,
9011 prune: prune,
9012 truncate: truncate,
9013 decorateArray: decorateArray,
9014 decorateObject: decorateObject
9015 },
9016 flow: {
9017 compose: compose,
9018 when: when,
9019 allowedKeys: allowedKeys,
9020 safeKeys: safeKeys,
9021 filter: filter,
9022 iterate: iterate,
9023 end: end
9024 },
9025 symbols: {
9026 END: END,
9027 ITERATE: ITERATE
9028 },
9029 always: function (str) {
9030 return compose(always(str), end());
9031 },
9032 json: function () {
9033 return compose(json(), end());
9034 },
9035 toStr: function () {
9036 return compose(toStr(), end());
9037 },
9038 prune: function () {
9039 return prune;
9040 },
9041 number: function () {
9042 return compose(
9043 omitNaN,
9044 omitPositiveInfinity,
9045 omitNegativeInfinity,
9046 json(),
9047 end()
9048 );
9049 },
9050 newLike: function () {
9051 return compose(
9052 always('new '),
9053 constructorName(),
9054 always('('),
9055 json(),
9056 always(')'),
9057 end()
9058 );
9059 },
9060 array: function (predicate) {
9061 return compose(
9062 omitCircular,
9063 omitMaxDepth,
9064 decorateArray(),
9065 arrayIndicesToKeys(),
9066 filter(predicate),
9067 iterate()
9068 );
9069 },
9070 object: function (predicate, orderedWhiteList) {
9071 return compose(
9072 omitCircular,
9073 omitMaxDepth,
9074 constructorName(),
9075 decorateObject(),
9076 allowedKeys(orderedWhiteList),
9077 safeKeys(),
9078 filter(predicate),
9079 iterate()
9080 );
9081 }
9082};
9083
9084},{"array-filter":16,"array-foreach":17,"array-reduce-right":19,"indexof":27,"type-name":35}],34:[function(_dereq_,module,exports){
9085var traverse = module.exports = function (obj) {
9086 return new Traverse(obj);
9087};
9088
9089function Traverse (obj) {
9090 this.value = obj;
9091}
9092
9093Traverse.prototype.get = function (ps) {
9094 var node = this.value;
9095 for (var i = 0; i < ps.length; i ++) {
9096 var key = ps[i];
9097 if (!node || !hasOwnProperty.call(node, key)) {
9098 node = undefined;
9099 break;
9100 }
9101 node = node[key];
9102 }
9103 return node;
9104};
9105
9106Traverse.prototype.has = function (ps) {
9107 var node = this.value;
9108 for (var i = 0; i < ps.length; i ++) {
9109 var key = ps[i];
9110 if (!node || !hasOwnProperty.call(node, key)) {
9111 return false;
9112 }
9113 node = node[key];
9114 }
9115 return true;
9116};
9117
9118Traverse.prototype.set = function (ps, value) {
9119 var node = this.value;
9120 for (var i = 0; i < ps.length - 1; i ++) {
9121 var key = ps[i];
9122 if (!hasOwnProperty.call(node, key)) node[key] = {};
9123 node = node[key];
9124 }
9125 node[ps[i]] = value;
9126 return value;
9127};
9128
9129Traverse.prototype.map = function (cb) {
9130 return walk(this.value, cb, true);
9131};
9132
9133Traverse.prototype.forEach = function (cb) {
9134 this.value = walk(this.value, cb, false);
9135 return this.value;
9136};
9137
9138Traverse.prototype.reduce = function (cb, init) {
9139 var skip = arguments.length === 1;
9140 var acc = skip ? this.value : init;
9141 this.forEach(function (x) {
9142 if (!this.isRoot || !skip) {
9143 acc = cb.call(this, acc, x);
9144 }
9145 });
9146 return acc;
9147};
9148
9149Traverse.prototype.paths = function () {
9150 var acc = [];
9151 this.forEach(function (x) {
9152 acc.push(this.path);
9153 });
9154 return acc;
9155};
9156
9157Traverse.prototype.nodes = function () {
9158 var acc = [];
9159 this.forEach(function (x) {
9160 acc.push(this.node);
9161 });
9162 return acc;
9163};
9164
9165Traverse.prototype.clone = function () {
9166 var parents = [], nodes = [];
9167
9168 return (function clone (src) {
9169 for (var i = 0; i < parents.length; i++) {
9170 if (parents[i] === src) {
9171 return nodes[i];
9172 }
9173 }
9174
9175 if (typeof src === 'object' && src !== null) {
9176 var dst = copy(src);
9177
9178 parents.push(src);
9179 nodes.push(dst);
9180
9181 forEach(objectKeys(src), function (key) {
9182 dst[key] = clone(src[key]);
9183 });
9184
9185 parents.pop();
9186 nodes.pop();
9187 return dst;
9188 }
9189 else {
9190 return src;
9191 }
9192 })(this.value);
9193};
9194
9195function walk (root, cb, immutable) {
9196 var path = [];
9197 var parents = [];
9198 var alive = true;
9199
9200 return (function walker (node_) {
9201 var node = immutable ? copy(node_) : node_;
9202 var modifiers = {};
9203
9204 var keepGoing = true;
9205
9206 var state = {
9207 node : node,
9208 node_ : node_,
9209 path : [].concat(path),
9210 parent : parents[parents.length - 1],
9211 parents : parents,
9212 key : path.slice(-1)[0],
9213 isRoot : path.length === 0,
9214 level : path.length,
9215 circular : null,
9216 update : function (x, stopHere) {
9217 if (!state.isRoot) {
9218 state.parent.node[state.key] = x;
9219 }
9220 state.node = x;
9221 if (stopHere) keepGoing = false;
9222 },
9223 'delete' : function (stopHere) {
9224 delete state.parent.node[state.key];
9225 if (stopHere) keepGoing = false;
9226 },
9227 remove : function (stopHere) {
9228 if (isArray(state.parent.node)) {
9229 state.parent.node.splice(state.key, 1);
9230 }
9231 else {
9232 delete state.parent.node[state.key];
9233 }
9234 if (stopHere) keepGoing = false;
9235 },
9236 keys : null,
9237 before : function (f) { modifiers.before = f },
9238 after : function (f) { modifiers.after = f },
9239 pre : function (f) { modifiers.pre = f },
9240 post : function (f) { modifiers.post = f },
9241 stop : function () { alive = false },
9242 block : function () { keepGoing = false }
9243 };
9244
9245 if (!alive) return state;
9246
9247 function updateState() {
9248 if (typeof state.node === 'object' && state.node !== null) {
9249 if (!state.keys || state.node_ !== state.node) {
9250 state.keys = objectKeys(state.node)
9251 }
9252
9253 state.isLeaf = state.keys.length == 0;
9254
9255 for (var i = 0; i < parents.length; i++) {
9256 if (parents[i].node_ === node_) {
9257 state.circular = parents[i];
9258 break;
9259 }
9260 }
9261 }
9262 else {
9263 state.isLeaf = true;
9264 state.keys = null;
9265 }
9266
9267 state.notLeaf = !state.isLeaf;
9268 state.notRoot = !state.isRoot;
9269 }
9270
9271 updateState();
9272
9273 // use return values to update if defined
9274 var ret = cb.call(state, state.node);
9275 if (ret !== undefined && state.update) state.update(ret);
9276
9277 if (modifiers.before) modifiers.before.call(state, state.node);
9278
9279 if (!keepGoing) return state;
9280
9281 if (typeof state.node == 'object'
9282 && state.node !== null && !state.circular) {
9283 parents.push(state);
9284
9285 updateState();
9286
9287 forEach(state.keys, function (key, i) {
9288 path.push(key);
9289
9290 if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
9291
9292 var child = walker(state.node[key]);
9293 if (immutable && hasOwnProperty.call(state.node, key)) {
9294 state.node[key] = child.node;
9295 }
9296
9297 child.isLast = i == state.keys.length - 1;
9298 child.isFirst = i == 0;
9299
9300 if (modifiers.post) modifiers.post.call(state, child);
9301
9302 path.pop();
9303 });
9304 parents.pop();
9305 }
9306
9307 if (modifiers.after) modifiers.after.call(state, state.node);
9308
9309 return state;
9310 })(root).node;
9311}
9312
9313function copy (src) {
9314 if (typeof src === 'object' && src !== null) {
9315 var dst;
9316
9317 if (isArray(src)) {
9318 dst = [];
9319 }
9320 else if (isDate(src)) {
9321 dst = new Date(src.getTime ? src.getTime() : src);
9322 }
9323 else if (isRegExp(src)) {
9324 dst = new RegExp(src);
9325 }
9326 else if (isError(src)) {
9327 dst = { message: src.message };
9328 }
9329 else if (isBoolean(src)) {
9330 dst = new Boolean(src);
9331 }
9332 else if (isNumber(src)) {
9333 dst = new Number(src);
9334 }
9335 else if (isString(src)) {
9336 dst = new String(src);
9337 }
9338 else if (Object.create && Object.getPrototypeOf) {
9339 dst = Object.create(Object.getPrototypeOf(src));
9340 }
9341 else if (src.constructor === Object) {
9342 dst = {};
9343 }
9344 else {
9345 var proto =
9346 (src.constructor && src.constructor.prototype)
9347 || src.__proto__
9348 || {}
9349 ;
9350 var T = function () {};
9351 T.prototype = proto;
9352 dst = new T;
9353 }
9354
9355 forEach(objectKeys(src), function (key) {
9356 dst[key] = src[key];
9357 });
9358 return dst;
9359 }
9360 else return src;
9361}
9362
9363var objectKeys = Object.keys || function keys (obj) {
9364 var res = [];
9365 for (var key in obj) res.push(key)
9366 return res;
9367};
9368
9369function toS (obj) { return Object.prototype.toString.call(obj) }
9370function isDate (obj) { return toS(obj) === '[object Date]' }
9371function isRegExp (obj) { return toS(obj) === '[object RegExp]' }
9372function isError (obj) { return toS(obj) === '[object Error]' }
9373function isBoolean (obj) { return toS(obj) === '[object Boolean]' }
9374function isNumber (obj) { return toS(obj) === '[object Number]' }
9375function isString (obj) { return toS(obj) === '[object String]' }
9376
9377var isArray = Array.isArray || function isArray (xs) {
9378 return Object.prototype.toString.call(xs) === '[object Array]';
9379};
9380
9381var forEach = function (xs, fn) {
9382 if (xs.forEach) return xs.forEach(fn)
9383 else for (var i = 0; i < xs.length; i++) {
9384 fn(xs[i], i, xs);
9385 }
9386};
9387
9388forEach(objectKeys(Traverse.prototype), function (key) {
9389 traverse[key] = function (obj) {
9390 var args = [].slice.call(arguments, 1);
9391 var t = new Traverse(obj);
9392 return t[key].apply(t, args);
9393 };
9394});
9395
9396var hasOwnProperty = Object.hasOwnProperty || function (obj, key) {
9397 return key in obj;
9398};
9399
9400},{}],35:[function(_dereq_,module,exports){
9401/**
9402 * type-name - Just a reasonable typeof
9403 *
9404 * https://github.com/twada/type-name
9405 *
9406 * Copyright (c) 2014-2015 Takuto Wada
9407 * Licensed under the MIT license.
9408 * http://twada.mit-license.org/2014-2015
9409 */
9410'use strict';
9411
9412var toStr = Object.prototype.toString;
9413
9414function funcName (f) {
9415 return f.name ? f.name : /^\s*function\s*([^\(]*)/im.exec(f.toString())[1];
9416}
9417
9418function ctorName (obj) {
9419 var strName = toStr.call(obj).slice(8, -1);
9420 if (strName === 'Object' && obj.constructor) {
9421 return funcName(obj.constructor);
9422 }
9423 return strName;
9424}
9425
9426function typeName (val) {
9427 var type;
9428 if (val === null) {
9429 return 'null';
9430 }
9431 type = typeof(val);
9432 if (type === 'object') {
9433 return ctorName(val);
9434 }
9435 return type;
9436}
9437
9438module.exports = typeName;
9439
9440},{}],36:[function(_dereq_,module,exports){
9441module.exports = function isBuffer(arg) {
9442 return arg && typeof arg === 'object'
9443 && typeof arg.copy === 'function'
9444 && typeof arg.fill === 'function'
9445 && typeof arg.readUInt8 === 'function';
9446}
9447},{}],37:[function(_dereq_,module,exports){
9448(function (process,global){
9449// Copyright Joyent, Inc. and other Node contributors.
9450//
9451// Permission is hereby granted, free of charge, to any person obtaining a
9452// copy of this software and associated documentation files (the
9453// "Software"), to deal in the Software without restriction, including
9454// without limitation the rights to use, copy, modify, merge, publish,
9455// distribute, sublicense, and/or sell copies of the Software, and to permit
9456// persons to whom the Software is furnished to do so, subject to the
9457// following conditions:
9458//
9459// The above copyright notice and this permission notice shall be included
9460// in all copies or substantial portions of the Software.
9461//
9462// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9463// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9464// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9465// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9466// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9467// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9468// USE OR OTHER DEALINGS IN THE SOFTWARE.
9469
9470var formatRegExp = /%[sdj%]/g;
9471exports.format = function(f) {
9472 if (!isString(f)) {
9473 var objects = [];
9474 for (var i = 0; i < arguments.length; i++) {
9475 objects.push(inspect(arguments[i]));
9476 }
9477 return objects.join(' ');
9478 }
9479
9480 var i = 1;
9481 var args = arguments;
9482 var len = args.length;
9483 var str = String(f).replace(formatRegExp, function(x) {
9484 if (x === '%%') return '%';
9485 if (i >= len) return x;
9486 switch (x) {
9487 case '%s': return String(args[i++]);
9488 case '%d': return Number(args[i++]);
9489 case '%j':
9490 try {
9491 return JSON.stringify(args[i++]);
9492 } catch (_) {
9493 return '[Circular]';
9494 }
9495 default:
9496 return x;
9497 }
9498 });
9499 for (var x = args[i]; i < len; x = args[++i]) {
9500 if (isNull(x) || !isObject(x)) {
9501 str += ' ' + x;
9502 } else {
9503 str += ' ' + inspect(x);
9504 }
9505 }
9506 return str;
9507};
9508
9509
9510// Mark that a method should not be used.
9511// Returns a modified function which warns once by default.
9512// If --no-deprecation is set, then it is a no-op.
9513exports.deprecate = function(fn, msg) {
9514 // Allow for deprecating things in the process of starting up.
9515 if (isUndefined(global.process)) {
9516 return function() {
9517 return exports.deprecate(fn, msg).apply(this, arguments);
9518 };
9519 }
9520
9521 if (process.noDeprecation === true) {
9522 return fn;
9523 }
9524
9525 var warned = false;
9526 function deprecated() {
9527 if (!warned) {
9528 if (process.throwDeprecation) {
9529 throw new Error(msg);
9530 } else if (process.traceDeprecation) {
9531 console.trace(msg);
9532 } else {
9533 console.error(msg);
9534 }
9535 warned = true;
9536 }
9537 return fn.apply(this, arguments);
9538 }
9539
9540 return deprecated;
9541};
9542
9543
9544var debugs = {};
9545var debugEnviron;
9546exports.debuglog = function(set) {
9547 if (isUndefined(debugEnviron))
9548 debugEnviron = process.env.NODE_DEBUG || '';
9549 set = set.toUpperCase();
9550 if (!debugs[set]) {
9551 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
9552 var pid = process.pid;
9553 debugs[set] = function() {
9554 var msg = exports.format.apply(exports, arguments);
9555 console.error('%s %d: %s', set, pid, msg);
9556 };
9557 } else {
9558 debugs[set] = function() {};
9559 }
9560 }
9561 return debugs[set];
9562};
9563
9564
9565/**
9566 * Echos the value of a value. Trys to print the value out
9567 * in the best way possible given the different types.
9568 *
9569 * @param {Object} obj The object to print out.
9570 * @param {Object} opts Optional options object that alters the output.
9571 */
9572/* legacy: obj, showHidden, depth, colors*/
9573function inspect(obj, opts) {
9574 // default options
9575 var ctx = {
9576 seen: [],
9577 stylize: stylizeNoColor
9578 };
9579 // legacy...
9580 if (arguments.length >= 3) ctx.depth = arguments[2];
9581 if (arguments.length >= 4) ctx.colors = arguments[3];
9582 if (isBoolean(opts)) {
9583 // legacy...
9584 ctx.showHidden = opts;
9585 } else if (opts) {
9586 // got an "options" object
9587 exports._extend(ctx, opts);
9588 }
9589 // set default options
9590 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
9591 if (isUndefined(ctx.depth)) ctx.depth = 2;
9592 if (isUndefined(ctx.colors)) ctx.colors = false;
9593 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
9594 if (ctx.colors) ctx.stylize = stylizeWithColor;
9595 return formatValue(ctx, obj, ctx.depth);
9596}
9597exports.inspect = inspect;
9598
9599
9600// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
9601inspect.colors = {
9602 'bold' : [1, 22],
9603 'italic' : [3, 23],
9604 'underline' : [4, 24],
9605 'inverse' : [7, 27],
9606 'white' : [37, 39],
9607 'grey' : [90, 39],
9608 'black' : [30, 39],
9609 'blue' : [34, 39],
9610 'cyan' : [36, 39],
9611 'green' : [32, 39],
9612 'magenta' : [35, 39],
9613 'red' : [31, 39],
9614 'yellow' : [33, 39]
9615};
9616
9617// Don't use 'blue' not visible on cmd.exe
9618inspect.styles = {
9619 'special': 'cyan',
9620 'number': 'yellow',
9621 'boolean': 'yellow',
9622 'undefined': 'grey',
9623 'null': 'bold',
9624 'string': 'green',
9625 'date': 'magenta',
9626 // "name": intentionally not styling
9627 'regexp': 'red'
9628};
9629
9630
9631function stylizeWithColor(str, styleType) {
9632 var style = inspect.styles[styleType];
9633
9634 if (style) {
9635 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
9636 '\u001b[' + inspect.colors[style][1] + 'm';
9637 } else {
9638 return str;
9639 }
9640}
9641
9642
9643function stylizeNoColor(str, styleType) {
9644 return str;
9645}
9646
9647
9648function arrayToHash(array) {
9649 var hash = {};
9650
9651 array.forEach(function(val, idx) {
9652 hash[val] = true;
9653 });
9654
9655 return hash;
9656}
9657
9658
9659function formatValue(ctx, value, recurseTimes) {
9660 // Provide a hook for user-specified inspect functions.
9661 // Check that value is an object with an inspect function on it
9662 if (ctx.customInspect &&
9663 value &&
9664 isFunction(value.inspect) &&
9665 // Filter out the util module, it's inspect function is special
9666 value.inspect !== exports.inspect &&
9667 // Also filter out any prototype objects using the circular check.
9668 !(value.constructor && value.constructor.prototype === value)) {
9669 var ret = value.inspect(recurseTimes, ctx);
9670 if (!isString(ret)) {
9671 ret = formatValue(ctx, ret, recurseTimes);
9672 }
9673 return ret;
9674 }
9675
9676 // Primitive types cannot have properties
9677 var primitive = formatPrimitive(ctx, value);
9678 if (primitive) {
9679 return primitive;
9680 }
9681
9682 // Look up the keys of the object.
9683 var keys = Object.keys(value);
9684 var visibleKeys = arrayToHash(keys);
9685
9686 if (ctx.showHidden) {
9687 keys = Object.getOwnPropertyNames(value);
9688 }
9689
9690 // IE doesn't make error fields non-enumerable
9691 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
9692 if (isError(value)
9693 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
9694 return formatError(value);
9695 }
9696
9697 // Some type of object without properties can be shortcutted.
9698 if (keys.length === 0) {
9699 if (isFunction(value)) {
9700 var name = value.name ? ': ' + value.name : '';
9701 return ctx.stylize('[Function' + name + ']', 'special');
9702 }
9703 if (isRegExp(value)) {
9704 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
9705 }
9706 if (isDate(value)) {
9707 return ctx.stylize(Date.prototype.toString.call(value), 'date');
9708 }
9709 if (isError(value)) {
9710 return formatError(value);
9711 }
9712 }
9713
9714 var base = '', array = false, braces = ['{', '}'];
9715
9716 // Make Array say that they are Array
9717 if (isArray(value)) {
9718 array = true;
9719 braces = ['[', ']'];
9720 }
9721
9722 // Make functions say that they are functions
9723 if (isFunction(value)) {
9724 var n = value.name ? ': ' + value.name : '';
9725 base = ' [Function' + n + ']';
9726 }
9727
9728 // Make RegExps say that they are RegExps
9729 if (isRegExp(value)) {
9730 base = ' ' + RegExp.prototype.toString.call(value);
9731 }
9732
9733 // Make dates with properties first say the date
9734 if (isDate(value)) {
9735 base = ' ' + Date.prototype.toUTCString.call(value);
9736 }
9737
9738 // Make error with message first say the error
9739 if (isError(value)) {
9740 base = ' ' + formatError(value);
9741 }
9742
9743 if (keys.length === 0 && (!array || value.length == 0)) {
9744 return braces[0] + base + braces[1];
9745 }
9746
9747 if (recurseTimes < 0) {
9748 if (isRegExp(value)) {
9749 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
9750 } else {
9751 return ctx.stylize('[Object]', 'special');
9752 }
9753 }
9754
9755 ctx.seen.push(value);
9756
9757 var output;
9758 if (array) {
9759 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
9760 } else {
9761 output = keys.map(function(key) {
9762 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
9763 });
9764 }
9765
9766 ctx.seen.pop();
9767
9768 return reduceToSingleString(output, base, braces);
9769}
9770
9771
9772function formatPrimitive(ctx, value) {
9773 if (isUndefined(value))
9774 return ctx.stylize('undefined', 'undefined');
9775 if (isString(value)) {
9776 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
9777 .replace(/'/g, "\\'")
9778 .replace(/\\"/g, '"') + '\'';
9779 return ctx.stylize(simple, 'string');
9780 }
9781 if (isNumber(value))
9782 return ctx.stylize('' + value, 'number');
9783 if (isBoolean(value))
9784 return ctx.stylize('' + value, 'boolean');
9785 // For some reason typeof null is "object", so special case here.
9786 if (isNull(value))
9787 return ctx.stylize('null', 'null');
9788}
9789
9790
9791function formatError(value) {
9792 return '[' + Error.prototype.toString.call(value) + ']';
9793}
9794
9795
9796function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
9797 var output = [];
9798 for (var i = 0, l = value.length; i < l; ++i) {
9799 if (hasOwnProperty(value, String(i))) {
9800 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
9801 String(i), true));
9802 } else {
9803 output.push('');
9804 }
9805 }
9806 keys.forEach(function(key) {
9807 if (!key.match(/^\d+$/)) {
9808 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
9809 key, true));
9810 }
9811 });
9812 return output;
9813}
9814
9815
9816function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
9817 var name, str, desc;
9818 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
9819 if (desc.get) {
9820 if (desc.set) {
9821 str = ctx.stylize('[Getter/Setter]', 'special');
9822 } else {
9823 str = ctx.stylize('[Getter]', 'special');
9824 }
9825 } else {
9826 if (desc.set) {
9827 str = ctx.stylize('[Setter]', 'special');
9828 }
9829 }
9830 if (!hasOwnProperty(visibleKeys, key)) {
9831 name = '[' + key + ']';
9832 }
9833 if (!str) {
9834 if (ctx.seen.indexOf(desc.value) < 0) {
9835 if (isNull(recurseTimes)) {
9836 str = formatValue(ctx, desc.value, null);
9837 } else {
9838 str = formatValue(ctx, desc.value, recurseTimes - 1);
9839 }
9840 if (str.indexOf('\n') > -1) {
9841 if (array) {
9842 str = str.split('\n').map(function(line) {
9843 return ' ' + line;
9844 }).join('\n').substr(2);
9845 } else {
9846 str = '\n' + str.split('\n').map(function(line) {
9847 return ' ' + line;
9848 }).join('\n');
9849 }
9850 }
9851 } else {
9852 str = ctx.stylize('[Circular]', 'special');
9853 }
9854 }
9855 if (isUndefined(name)) {
9856 if (array && key.match(/^\d+$/)) {
9857 return str;
9858 }
9859 name = JSON.stringify('' + key);
9860 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
9861 name = name.substr(1, name.length - 2);
9862 name = ctx.stylize(name, 'name');
9863 } else {
9864 name = name.replace(/'/g, "\\'")
9865 .replace(/\\"/g, '"')
9866 .replace(/(^"|"$)/g, "'");
9867 name = ctx.stylize(name, 'string');
9868 }
9869 }
9870
9871 return name + ': ' + str;
9872}
9873
9874
9875function reduceToSingleString(output, base, braces) {
9876 var numLinesEst = 0;
9877 var length = output.reduce(function(prev, cur) {
9878 numLinesEst++;
9879 if (cur.indexOf('\n') >= 0) numLinesEst++;
9880 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
9881 }, 0);
9882
9883 if (length > 60) {
9884 return braces[0] +
9885 (base === '' ? '' : base + '\n ') +
9886 ' ' +
9887 output.join(',\n ') +
9888 ' ' +
9889 braces[1];
9890 }
9891
9892 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
9893}
9894
9895
9896// NOTE: These type checking functions intentionally don't use `instanceof`
9897// because it is fragile and can be easily faked with `Object.create()`.
9898function isArray(ar) {
9899 return Array.isArray(ar);
9900}
9901exports.isArray = isArray;
9902
9903function isBoolean(arg) {
9904 return typeof arg === 'boolean';
9905}
9906exports.isBoolean = isBoolean;
9907
9908function isNull(arg) {
9909 return arg === null;
9910}
9911exports.isNull = isNull;
9912
9913function isNullOrUndefined(arg) {
9914 return arg == null;
9915}
9916exports.isNullOrUndefined = isNullOrUndefined;
9917
9918function isNumber(arg) {
9919 return typeof arg === 'number';
9920}
9921exports.isNumber = isNumber;
9922
9923function isString(arg) {
9924 return typeof arg === 'string';
9925}
9926exports.isString = isString;
9927
9928function isSymbol(arg) {
9929 return typeof arg === 'symbol';
9930}
9931exports.isSymbol = isSymbol;
9932
9933function isUndefined(arg) {
9934 return arg === void 0;
9935}
9936exports.isUndefined = isUndefined;
9937
9938function isRegExp(re) {
9939 return isObject(re) && objectToString(re) === '[object RegExp]';
9940}
9941exports.isRegExp = isRegExp;
9942
9943function isObject(arg) {
9944 return typeof arg === 'object' && arg !== null;
9945}
9946exports.isObject = isObject;
9947
9948function isDate(d) {
9949 return isObject(d) && objectToString(d) === '[object Date]';
9950}
9951exports.isDate = isDate;
9952
9953function isError(e) {
9954 return isObject(e) &&
9955 (objectToString(e) === '[object Error]' || e instanceof Error);
9956}
9957exports.isError = isError;
9958
9959function isFunction(arg) {
9960 return typeof arg === 'function';
9961}
9962exports.isFunction = isFunction;
9963
9964function isPrimitive(arg) {
9965 return arg === null ||
9966 typeof arg === 'boolean' ||
9967 typeof arg === 'number' ||
9968 typeof arg === 'string' ||
9969 typeof arg === 'symbol' || // ES6 symbol
9970 typeof arg === 'undefined';
9971}
9972exports.isPrimitive = isPrimitive;
9973
9974exports.isBuffer = _dereq_('./support/isBuffer');
9975
9976function objectToString(o) {
9977 return Object.prototype.toString.call(o);
9978}
9979
9980
9981function pad(n) {
9982 return n < 10 ? '0' + n.toString(10) : n.toString(10);
9983}
9984
9985
9986var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
9987 'Oct', 'Nov', 'Dec'];
9988
9989// 26 Feb 16:19:34
9990function timestamp() {
9991 var d = new Date();
9992 var time = [pad(d.getHours()),
9993 pad(d.getMinutes()),
9994 pad(d.getSeconds())].join(':');
9995 return [d.getDate(), months[d.getMonth()], time].join(' ');
9996}
9997
9998
9999// log is just a thin wrapper to console.log that prepends a timestamp
10000exports.log = function() {
10001 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
10002};
10003
10004
10005/**
10006 * Inherit the prototype methods from one constructor into another.
10007 *
10008 * The Function.prototype.inherits from lang.js rewritten as a standalone
10009 * function (not on Function.prototype). NOTE: If this file is to be loaded
10010 * during bootstrapping this function needs to be rewritten using some native
10011 * functions as prototype setup using normal JavaScript does not work as
10012 * expected during bootstrapping (see mirror.js in r114903).
10013 *
10014 * @param {function} ctor Constructor function which needs to inherit the
10015 * prototype.
10016 * @param {function} superCtor Constructor function to inherit prototype from.
10017 */
10018exports.inherits = _dereq_('inherits');
10019
10020exports._extend = function(origin, add) {
10021 // Don't do anything if add isn't an object
10022 if (!add || !isObject(add)) return origin;
10023
10024 var keys = Object.keys(add);
10025 var i = keys.length;
10026 while (i--) {
10027 origin[keys[i]] = add[keys[i]];
10028 }
10029 return origin;
10030};
10031
10032function hasOwnProperty(obj, prop) {
10033 return Object.prototype.hasOwnProperty.call(obj, prop);
10034}
10035
10036}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10037},{"./support/isBuffer":36,"_process":31,"inherits":28}],38:[function(_dereq_,module,exports){
10038module.exports = extend
10039
10040var hasOwnProperty = Object.prototype.hasOwnProperty;
10041
10042function extend() {
10043 var target = {}
10044
10045 for (var i = 0; i < arguments.length; i++) {
10046 var source = arguments[i]
10047
10048 for (var key in source) {
10049 if (hasOwnProperty.call(source, key)) {
10050 target[key] = source[key]
10051 }
10052 }
10053 }
10054
10055 return target
10056}
10057
10058},{}]},{},[1])(1)
10059});
\No newline at end of file