From 37df68d6dbb137aa6ae9ace5faa4ea299cc4fa8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Sat, 12 Aug 2017 01:32:57 +0200 Subject: [PATCH] Rebuilt docs bundle.js, made some minor tweaks in the code to make it happen --- docs/bundle.js | 116739 +++++++++---------- main.js | 4 +- package.json | 3 +- packages/regenerator-preset/index.js | 4 +- packages/regenerator-runtime/package.json | 2 +- 5 files changed, 58120 insertions(+), 58632 deletions(-) diff --git a/docs/bundle.js b/docs/bundle.js index 01cb2e893..41a8b92c8 100644 --- a/docs/bundle.js +++ b/docs/bundle.js @@ -1,10008 +1,12000 @@ (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.regenerator = 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 + * @license MIT */ +function compare(a, b) { + if (a === b) { + return 0; + } -var assert = require("assert"); -var types = require("recast").types; -var n = types.namedTypes; -var b = types.builders; -var hasOwn = Object.prototype.hasOwnProperty; - -exports.defaults = function(obj) { - var len = arguments.length; - var extension; + var x = a.length; + var y = b.length; - for (var i = 1; i < len; ++i) { - if ((extension = arguments[i])) { - for (var key in extension) { - if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) { - obj[key] = extension[key]; - } - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; } } - return obj; -}; + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} -exports.runtimeProperty = function(name) { - return b.memberExpression( - b.identifier("regeneratorRuntime"), - b.identifier(name), - false - ); -}; +// based on node assert, original notice: -// Inspired by the isReference function from ast-util: -// https://github.com/eventualbuddha/ast-util/blob/9bf91c5ce8/lib/index.js#L466-L506 -exports.isReference = function(path, name) { - var node = path.value; +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - if (!n.Identifier.check(node)) { +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { return false; } - - if (name && node.name !== name) { + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { return false; } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. - var parent = path.parent.value; +var assert = module.exports = ok; - switch (parent.type) { - case "VariableDeclarator": - return path.name === "init"; +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) - case "MemberExpression": - return path.name === "object" || ( - parent.computed && path.name === "property" - ); +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; - case "FunctionExpression": - case "FunctionDeclaration": - case "ArrowFunctionExpression": - if (path.name === "id") { - return false; - } + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } - if (path.parentPath.name === "params" && - parent.params === path.parentPath.value && - parent.params[path.name] === node) { - return false; + this.stack = out; } + } +}; - return true; +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); - case "ClassDeclaration": - case "ClassExpression": - return path.name !== "id"; +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} - case "CatchClause": - return path.name !== "param"; +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. - case "Property": - case "MethodDefinition": - return path.name !== "key"; +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. - case "ImportSpecifier": - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "LabeledStatement": - return false; +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} - default: - return true; - } -}; +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; -},{"assert":791,"recast":521}],2:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. -var recast = require("recast"); -var types = recast.types; -var n = types.namedTypes; -var util = require("./util.js"); +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; -exports.transform = function transform(node, options) { - options = util.defaults(options || {}, { - includeRuntime: false - }); +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); - var result = require("babel-core").transformFromAst(node, null, { - presets: [require("regenerator-preset")], - code: false, - ast: true - }); +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; - node = result.ast; +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); - if (options.includeRuntime === true) { - injectRuntime(n.File.check(node) ? node.program : node); +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); } +}; - return node; +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } }; -function injectRuntime(program) { - n.Program.assert(program); +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; - // Include the runtime by modifying the AST rather than by concatenating - // strings. This technique will allow for more accurate source mapping. - var runtimePath = require("..").runtime.path; - var runtime = fs.readFileSync(runtimePath, "utf8"); - var runtimeBody = recast.parse(runtime, { - sourceFileName: runtimePath - }).program.body; +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; - var body = program.body; - body.unshift.apply(body, runtimeBody); -} + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); -},{"..":3,"./util.js":1,"babel-core":26,"recast":521,"regenerator-preset":540}],3:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; -var fs = require("fs"); -var through = require("through"); -var transform = require("./lib/visit").transform; -var utils = require("./lib/util"); -var genOrAsyncFunExp = /\bfunction\s*\*|\basync\b/; + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; -function exports(file, options) { - var data = []; - return through(write, end); + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; - function write(buf) { - data.push(buf); - } + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; - function end() { - try { - this.queue(compile(data.join(""), options).code); - this.queue(null); - } catch (e) { this.emit('error', e); } - } -} + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } -// To get a writable stream for use as a browserify transform, call -// require("regenerator")(). -module.exports = exports; + memos.actual.push(actual); + memos.expected.push(expected); -// To include the runtime globally in the current node process, call -// require("regenerator").runtime(). -function runtime() { - regeneratorRuntime = require("regenerator-runtime"); + return objEquiv(actual, expected, strict, memos); + } } -exports.runtime = runtime; -runtime.path = require("regenerator-runtime/path.js").path; -var cachedRuntimeCode; -function getRuntimeCode() { - return cachedRuntimeCode || - (cachedRuntimeCode = fs.readFileSync(runtime.path, "utf8")); +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; } -var transformOptions = { - presets: [require("regenerator-preset")], - parserOpts: { - sourceType: "module", - allowImportExportEverywhere: true, - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - strictMode: false, - plugins: ["*", "jsx", "flow"] +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); } -}; - -function compile(source, options) { - var result; + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} - options = utils.defaults(options || {}, { - includeRuntime: false - }); +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); - // Shortcut: Transform only if generators or async functions present. - if (genOrAsyncFunExp.test(source)) { - result = require("babel-core").transform(source, transformOptions); - } else { - result = { code: source }; +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } +}; - if (options.includeRuntime === true) { - result.code = getRuntimeCode() + "\n" + result.code; +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } - - return result; } -// Allow packages that depend on Regenerator to use the same copy of -// ast-types, in case multiple versions are installed by NPM. -exports.types = require("recast").types; - -// Transforms a string of source code, returning a { code, map? } result. -exports.compile = compile; -// To modify an AST directly, call require("regenerator").transform(ast). -exports.transform = transform; +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); -},{"./lib/util":1,"./lib/visit":2,"babel-core":26,"fs":790,"recast":521,"regenerator-preset":540,"regenerator-runtime":542,"regenerator-runtime/path.js":541,"through":537}],4:[function(require,module,exports){ -'use strict'; -module.exports = function () { - return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } }; -},{}],5:[function(require,module,exports){ -'use strict'; +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); + if (Error.isPrototypeOf(expected)) { + return false; + } - return styles; + return expected.call({}, actual) === true; } -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} -},{}],6:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./es7")); +function _throws(shouldThrow, block, expected, message) { + var actual; - var types = fork.use(require("../lib/types")); - var defaults = fork.use(require("../lib/shared")).defaults; - var def = types.Type.def; - var or = types.Type.or; + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } - def("Noop") - .bases("Node") - .build(); + if (typeof expected === 'string') { + message = expected; + expected = null; + } - def("DoExpression") - .bases("Expression") - .build("body") - .field("body", [def("Statement")]); + actual = _tryBlock(block); - def("Super") - .bases("Expression") - .build(); + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); - def("BindExpression") - .bases("Expression") - .build("object", "callee") - .field("object", or(def("Expression"), null)) - .field("callee", def("Expression")); + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } - def("Decorator") - .bases("Node") - .build("expression") - .field("expression", def("Expression")); + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; - def("Property") - .field("decorators", - or([def("Decorator")], null), - defaults["null"]); + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } - def("MethodDefinition") - .field("decorators", - or([def("Decorator")], null), - defaults["null"]); + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} - def("MetaProperty") - .bases("Expression") - .build("meta", "property") - .field("meta", def("Identifier")) - .field("property", def("Identifier")); +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); - def("ParenthesizedExpression") - .bases("Expression") - .build("expression") - .field("expression", def("Expression")); +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; - def("ImportSpecifier") - .bases("ModuleSpecifier") - .build("imported", "local") - .field("imported", def("Identifier")); +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; - def("ImportDefaultSpecifier") - .bases("ModuleSpecifier") - .build("local"); +assert.ifError = function(err) { if (err) throw err; }; - def("ImportNamespaceSpecifier") - .bases("ModuleSpecifier") - .build("local"); +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; - def("ExportDefaultDeclaration") - .bases("Declaration") - .build("declaration") - .field("declaration", or(def("Declaration"), def("Expression"))); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"util/":36}],3:[function(require,module,exports){ +'use strict' - def("ExportNamedDeclaration") - .bases("Declaration") - .build("declaration", "specifiers", "source") - .field("declaration", or(def("Declaration"), null)) - .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray) - .field("source", or(def("Literal"), null), defaults["null"]); +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray - def("ExportSpecifier") - .bases("ModuleSpecifier") - .build("local", "exported") - .field("exported", def("Identifier")); +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - def("ExportNamespaceSpecifier") - .bases("Specifier") - .build("exported") - .field("exported", def("Identifier")); +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} - def("ExportDefaultSpecifier") - .bases("Specifier") - .build("exported") - .field("exported", def("Identifier")); +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 - def("ExportAllDeclaration") - .bases("Declaration") - .build("exported", "source") - .field("exported", or(def("Identifier"), null)) - .field("source", def("Literal")); +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - def("CommentBlock") - .bases("Comment") - .build("value", /*optional:*/ "leading", "trailing"); + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} - def("CommentLine") - .bases("Comment") - .build("value", /*optional:*/ "leading", "trailing"); -}; -},{"../lib/shared":22,"../lib/types":23,"./es7":11}],7:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./babel")); - fork.use(require("./flow")); +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) +} - // var types = fork.types; - var types = fork.use(require("../lib/types")); - // var defaults = fork.shared.defaults; - var defaults = fork.use(require("../lib/shared")).defaults; - var def = types.Type.def; - var or = types.Type.or; +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) - def("Directive") - .bases("Node") - .build("value") - .field("value", def("DirectiveLiteral")); + arr = new Arr((len * 3 / 4) - placeHolders) - def("DirectiveLiteral") - .bases("Node", "Expression") - .build("value") - .field("value", String, defaults["use strict"]); + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len - def("BlockStatement") - .bases("Statement") - .build("body") - .field("body", [def("Statement")]) - .field("directives", [def("Directive")], defaults.emptyArray); + var L = 0 - def("Program") - .bases("Node") - .build("body") - .field("body", [def("Statement")]) - .field("directives", [def("Directive")], defaults.emptyArray); + for (i = 0; i < l; i += 4) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - // Split Literal - def("StringLiteral") - .bases("Literal") - .build("value") - .field("value", String); + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - def("NumericLiteral") - .bases("Literal") - .build("value") - .field("value", Number); + return arr +} - def("NullLiteral") - .bases("Literal") - .build(); +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} - def("BooleanLiteral") - .bases("Literal") - .build("value") - .field("value", Boolean); +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} - def("RegExpLiteral") - .bases("Literal") - .build("pattern", "flags") - .field("pattern", String) - .field("flags", String); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - var ObjectExpressionProperty = or( - def("Property"), - def("ObjectMethod"), - def("ObjectProperty"), - def("SpreadProperty") - ); + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } - // Split Property -> ObjectProperty and ObjectMethod - def("ObjectExpression") - .bases("Expression") - .build("properties") - .field("properties", [ObjectExpressionProperty]); + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } - // ObjectMethod hoist .value properties to own properties - def("ObjectMethod") - .bases("Node", "Function") - .build("kind", "key", "params", "body", "computed") - .field("kind", or("method", "get", "set")) - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("params", [def("Pattern")]) - .field("body", def("BlockStatement")) - .field("computed", Boolean, defaults["false"]) - .field("generator", Boolean, defaults["false"]) - .field("async", Boolean, defaults["false"]) - .field("decorators", - or([def("Decorator")], null), - defaults["null"]); + parts.push(output) - def("ObjectProperty") - .bases("Node") - .build("key", "value") - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("value", or(def("Expression"), def("Pattern"))) - .field("computed", Boolean, defaults["false"]); + return parts.join('') +} - var ClassBodyElement = or( - def("MethodDefinition"), - def("VariableDeclarator"), - def("ClassPropertyDefinition"), - def("ClassProperty"), - def("ClassMethod") - ); +},{}],4:[function(require,module,exports){ +arguments[4][1][0].apply(exports,arguments) +},{"dup":1}],5:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ - // MethodDefinition -> ClassMethod - def("ClassBody") - .bases("Declaration") - .build("body") - .field("body", [ClassBodyElement]); +'use strict' - def("ClassMethod") - .bases("Declaration", "Function") - .build("kind", "key", "params", "body", "computed", "static") - .field("kind", or("get", "set", "method", "constructor")) - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("params", [def("Pattern")]) - .field("body", def("BlockStatement")) - .field("computed", Boolean, defaults["false"]) - .field("static", Boolean, defaults["false"]) - .field("generator", Boolean, defaults["false"]) - .field("async", Boolean, defaults["false"]) - .field("decorators", - or([def("Decorator")], null), - defaults["null"]); +var base64 = require('base64-js') +var ieee754 = require('ieee754') - var ObjectPatternProperty = or( - def("Property"), - def("PropertyPattern"), - def("SpreadPropertyPattern"), - def("SpreadProperty"), // Used by Esprima - def("ObjectProperty"), // Babel 6 - def("RestProperty") // Babel 6 - ); +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 - // Split into RestProperty and SpreadProperty - def("ObjectPattern") - .bases("Pattern") - .build("properties") - .field("properties", [ObjectPatternProperty]) - .field("decorators", - or([def("Decorator")], null), - defaults["null"]); +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH - def("SpreadProperty") - .bases("Node") - .build("argument") - .field("argument", def("Expression")); +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - def("RestProperty") - .bases("Node") - .build("argument") - .field("argument", def("Expression")); +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} - def("ForAwaitStatement") - .bases("Statement") - .build("left", "right", "body") - .field("left", or( - def("VariableDeclaration"), - def("Expression"))) - .field("right", def("Expression")) - .field("body", def("Statement")); +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } +} - // The callee node of a dynamic import(...) expression. - def("Import") - .bases("Expression") - .build(); -}; +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} -},{"../lib/shared":22,"../lib/types":23,"./babel":6,"./flow":13}],8:[function(require,module,exports){ -module.exports = function (fork) { - var types = fork.use(require("../lib/types")); - var Type = types.Type; - var def = Type.def; - var or = Type.or; - var shared = fork.use(require("../lib/shared")); - var defaults = shared.defaults; - var geq = shared.geq; - - // Abstract supertype of all syntactic entities that are allowed to have a - // .loc field. - def("Printable") - .field("loc", or( - def("SourceLocation"), - null - ), defaults["null"], true); - - def("Node") - .bases("Printable") - .field("type", String) - .field("comments", or( - [def("Comment")], - null - ), defaults["null"], true); - - def("SourceLocation") - .build("start", "end", "source") - .field("start", def("Position")) - .field("end", def("Position")) - .field("source", or(String, null), defaults["null"]); +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ - def("Position") - .build("line", "column") - .field("line", geq(1)) - .field("column", geq(0)); +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} - def("File") - .bases("Node") - .build("program", "name") - .field("program", def("Program")) - .field("name", or(String, null), defaults["null"]); +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} - def("Program") - .bases("Node") - .build("body") - .field("body", [def("Statement")]); +Buffer.poolSize = 8192 // not used by this implementation - def("Function") - .bases("Node") - .field("id", or(def("Identifier"), null), defaults["null"]) - .field("params", [def("Pattern")]) - .field("body", def("BlockStatement")); +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - def("Statement").bases("Node"); + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length) + } -// The empty .build() here means that an EmptyStatement can be constructed -// (i.e. it's not abstract) but that it needs no arguments. - def("EmptyStatement").bases("Statement").build(); + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - def("BlockStatement") - .bases("Statement") - .build("body") - .field("body", [def("Statement")]); + return fromObject(value) +} - // TODO Figure out how to silently coerce Expressions to - // ExpressionStatements where a Statement was expected. - def("ExpressionStatement") - .bases("Statement") - .build("expression") - .field("expression", def("Expression")); +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} - def("IfStatement") - .bases("Statement") - .build("test", "consequent", "alternate") - .field("test", def("Expression")) - .field("consequent", def("Statement")) - .field("alternate", or(def("Statement"), null), defaults["null"]); +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array - def("LabeledStatement") - .bases("Statement") - .build("label", "body") - .field("label", def("Identifier")) - .field("body", def("Statement")); +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} - def("BreakStatement") - .bases("Statement") - .build("label") - .field("label", or(def("Identifier"), null), defaults["null"]); +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} - def("ContinueStatement") - .bases("Statement") - .build("label") - .field("label", or(def("Identifier"), null), defaults["null"]); +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - def("WithStatement") - .bases("Statement") - .build("object", "body") - .field("object", def("Expression")) - .field("body", def("Statement")); +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} - def("SwitchStatement") - .bases("Statement") - .build("discriminant", "cases", "lexical") - .field("discriminant", def("Expression")) - .field("cases", [def("SwitchCase")]) - .field("lexical", Boolean, defaults["false"]); +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} - def("ReturnStatement") - .bases("Statement") - .build("argument") - .field("argument", or(def("Expression"), null)); +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - def("ThrowStatement") - .bases("Statement") - .build("argument") - .field("argument", def("Expression")); + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } - def("TryStatement") - .bases("Statement") - .build("block", "handler", "finalizer") - .field("block", def("BlockStatement")) - .field("handler", or(def("CatchClause"), null), function () { - return this.handlers && this.handlers[0] || null; - }) - .field("handlers", [def("CatchClause")], function () { - return this.handler ? [this.handler] : []; - }, true) // Indicates this field is hidden from eachField iteration. - .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) - .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) - def("CatchClause") - .bases("Node") - .build("param", "guard", "body") - .field("param", def("Pattern")) - .field("guard", or(def("Expression"), null), defaults["null"]) - .field("body", def("BlockStatement")); + var actual = buf.write(string, encoding) - def("WhileStatement") - .bases("Statement") - .build("test", "body") - .field("test", def("Expression")) - .field("body", def("Statement")); + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } - def("DoWhileStatement") - .bases("Statement") - .build("body", "test") - .field("body", def("Statement")) - .field("test", def("Expression")); + return buf +} - def("ForStatement") - .bases("Statement") - .build("init", "test", "update", "body") - .field("init", or( - def("VariableDeclaration"), - def("Expression"), - null)) - .field("test", or(def("Expression"), null)) - .field("update", or(def("Expression"), null)) - .field("body", def("Statement")); +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} - def("ForInStatement") - .bases("Statement") - .build("left", "right", "body") - .field("left", or( - def("VariableDeclaration"), - def("Expression"))) - .field("right", def("Expression")) - .field("body", def("Statement")); +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } - def("DebuggerStatement").bases("Statement").build(); + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } - def("Declaration").bases("Statement"); + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } - def("FunctionDeclaration") - .bases("Function", "Declaration") - .build("id", "params", "body") - .field("id", def("Identifier")); + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} - def("FunctionExpression") - .bases("Function", "Expression") - .build("id", "params", "body"); +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) - def("VariableDeclaration") - .bases("Declaration") - .build("kind", "declarations") - .field("kind", or("var", "let", "const")) - .field("declarations", [def("VariableDeclarator")]); + if (buf.length === 0) { + return buf + } - def("VariableDeclarator") - .bases("Node") - .build("id", "init") - .field("id", def("Pattern")) - .field("init", or(def("Expression"), null)); + obj.copy(buf, 0, 0, len) + return buf + } - // TODO Are all Expressions really Patterns? - def("Expression").bases("Node", "Pattern"); + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - def("ThisExpression").bases("Expression").build(); + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } - def("ArrayExpression") - .bases("Expression") - .build("elements") - .field("elements", [or(def("Expression"), null)]); + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} - def("ObjectExpression") - .bases("Expression") - .build("properties") - .field("properties", [def("Property")]); +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} - // TODO Not in the Mozilla Parser API, but used by Esprima. - def("Property") - .bases("Node") // Want to be able to visit Property Nodes. - .build("kind", "key", "value") - .field("kind", or("init", "get", "set")) - .field("key", or(def("Literal"), def("Identifier"))) - .field("value", def("Expression")); +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} - def("SequenceExpression") - .bases("Expression") - .build("expressions") - .field("expressions", [def("Expression")]); +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} - var UnaryOperator = or( - "-", "+", "!", "~", - "typeof", "void", "delete"); +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - def("UnaryExpression") - .bases("Expression") - .build("operator", "argument", "prefix") - .field("operator", UnaryOperator) - .field("argument", def("Expression")) - // Esprima doesn't bother with this field, presumably because it's - // always true for unary operators. - .field("prefix", Boolean, defaults["true"]); + if (a === b) return 0 - var BinaryOperator = or( - "==", "!=", "===", "!==", - "<", "<=", ">", ">=", - "<<", ">>", ">>>", - "+", "-", "*", "/", "%", - "&", // TODO Missing from the Parser API. - "|", "^", "in", - "instanceof", ".."); + var x = a.length + var y = b.length - def("BinaryExpression") - .bases("Expression") - .build("operator", "left", "right") - .field("operator", BinaryOperator) - .field("left", def("Expression")) - .field("right", def("Expression")); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } - var AssignmentOperator = or( - "=", "+=", "-=", "*=", "/=", "%=", - "<<=", ">>=", ">>>=", - "|=", "^=", "&="); + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - def("AssignmentExpression") - .bases("Expression") - .build("operator", "left", "right") - .field("operator", AssignmentOperator) - .field("left", def("Pattern")) - .field("right", def("Expression")); +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} - var UpdateOperator = or("++", "--"); +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - def("UpdateExpression") - .bases("Expression") - .build("operator", "argument", "prefix") - .field("operator", UpdateOperator) - .field("argument", def("Expression")) - .field("prefix", Boolean); + if (list.length === 0) { + return Buffer.alloc(0) + } - var LogicalOperator = or("||", "&&"); + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } - def("LogicalExpression") - .bases("Expression") - .build("operator", "left", "right") - .field("operator", LogicalOperator) - .field("left", def("Expression")) - .field("right", def("Expression")); + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} - def("ConditionalExpression") - .bases("Expression") - .build("test", "consequent", "alternate") - .field("test", def("Expression")) - .field("consequent", def("Expression")) - .field("alternate", def("Expression")); +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || isArrayBuffer(string)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } - def("NewExpression") - .bases("Expression") - .build("callee", "arguments") - .field("callee", def("Expression")) - // The Mozilla Parser API gives this type as [or(def("Expression"), - // null)], but null values don't really make sense at the call site. - // TODO Report this nonsense. - .field("arguments", [def("Expression")]); + var len = string.length + if (len === 0) return 0 - def("CallExpression") - .bases("Expression") - .build("callee", "arguments") - .field("callee", def("Expression")) - // See comment for NewExpression above. - .field("arguments", [def("Expression")]); - - def("MemberExpression") - .bases("Expression") - .build("object", "property", "computed") - .field("object", def("Expression")) - .field("property", or(def("Identifier"), def("Expression"))) - .field("computed", Boolean, function () { - var type = this.property.type; - if (type === 'Literal' || - type === 'MemberExpression' || - type === 'BinaryExpression') { - return true; - } - return false; - }); - - def("Pattern").bases("Node"); - - def("SwitchCase") - .bases("Node") - .build("test", "consequent") - .field("test", or(def("Expression"), null)) - .field("consequent", [def("Statement")]); - - def("Identifier") - // But aren't Expressions and Patterns already Nodes? TODO Report this. - .bases("Node", "Expression", "Pattern") - .build("name") - .field("name", String); + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength - def("Literal") - // But aren't Expressions already Nodes? TODO Report this. - .bases("Node", "Expression") - .build("value") - .field("value", or(String, Boolean, null, Number, RegExp)) - .field("regex", or({ - pattern: String, - flags: String - }, null), function () { - if (this.value instanceof RegExp) { - var flags = ""; +function slowToString (encoding, start, end) { + var loweredCase = false - if (this.value.ignoreCase) flags += "i"; - if (this.value.multiline) flags += "m"; - if (this.value.global) flags += "g"; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - return { - pattern: this.value.source, - flags: flags - }; - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - return null; - }); + if (end === undefined || end > this.length) { + end = this.length + } - // Abstract (non-buildable) comment supertype. Not a Node. - def("Comment") - .bases("Printable") - .field("value", String) - // A .leading comment comes before the node, whereas a .trailing - // comment comes after it. These two fields should not both be true, - // but they might both be false when the comment falls inside a node - // and the node has no children for the comment to lead or trail, - // e.g. { /*dangling*/ }. - .field("leading", Boolean, defaults["true"]) - .field("trailing", Boolean, defaults["false"]); -}; -},{"../lib/shared":22,"../lib/types":23}],9:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./core")); - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; + if (end <= 0) { + return '' + } - // Note that none of these types are buildable because the Mozilla Parser - // API doesn't specify any builder functions, and nobody uses E4X anymore. + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 - def("XMLDefaultDeclaration") - .bases("Declaration") - .field("namespace", def("Expression")); + if (end <= start) { + return '' + } - def("XMLAnyName").bases("Expression"); + if (!encoding) encoding = 'utf8' - def("XMLQualifiedIdentifier") - .bases("Expression") - .field("left", or(def("Identifier"), def("XMLAnyName"))) - .field("right", or(def("Identifier"), def("Expression"))) - .field("computed", Boolean); + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - def("XMLFunctionQualifiedIdentifier") - .bases("Expression") - .field("right", or(def("Identifier"), def("Expression"))) - .field("computed", Boolean); + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - def("XMLAttributeSelector") - .bases("Expression") - .field("attribute", def("Expression")); + case 'ascii': + return asciiSlice(this, start, end) - def("XMLFilterExpression") - .bases("Expression") - .field("left", def("Expression")) - .field("right", def("Expression")); + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - def("XMLElement") - .bases("XML", "Expression") - .field("contents", [def("XML")]); + case 'base64': + return base64Slice(this, start, end) - def("XMLList") - .bases("XML", "Expression") - .field("contents", [def("XML")]); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - def("XML").bases("Node"); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} - def("XMLEscape") - .bases("XML") - .field("expression", def("Expression")); +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true - def("XMLText") - .bases("XML") - .field("text", String); +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} - def("XMLStartTag") - .bases("XML") - .field("contents", [def("XML")]); +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} - def("XMLEndTag") - .bases("XML") - .field("contents", [def("XML")]); +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} - def("XMLPointTag") - .bases("XML") - .field("contents", [def("XML")]); +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} - def("XMLName") - .bases("XML") - .field("contents", or(String, [def("XML")])); +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} - def("XMLAttribute") - .bases("XML") - .field("value", String); +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} - def("XMLCdata") - .bases("XML") - .field("contents", String); +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} - def("XMLComment") - .bases("XML") - .field("contents", String); +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } - def("XMLProcessingInstruction") - .bases("XML") - .field("target", String) - .field("contents", or(String, null)); -}; -},{"../lib/types":23,"./core":8}],10:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./core")); - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var defaults = fork.use(require("../lib/shared")).defaults; + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } - def("Function") - .field("generator", Boolean, defaults["false"]) - .field("expression", Boolean, defaults["false"]) - .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) - // TODO This could be represented as a RestElement in .params. - .field("rest", or(def("Identifier"), null), defaults["null"]); + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - // The ESTree way of representing a ...rest parameter. - def("RestElement") - .bases("Pattern") - .build("argument") - .field("argument", def("Pattern")); + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - def("SpreadElementPattern") - .bases("Pattern") - .build("argument") - .field("argument", def("Pattern")); + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 - def("FunctionDeclaration") - .build("id", "params", "body", "generator", "expression"); + if (this === target) return 0 - def("FunctionExpression") - .build("id", "params", "body", "generator", "expression"); + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) - // The Parser API calls this ArrowExpression, but Esprima and all other - // actual parsers use ArrowFunctionExpression. - def("ArrowFunctionExpression") - .bases("Function", "Expression") - .build("params", "body", "expression") - // The forced null value here is compatible with the overridden - // definition of the "id" field in the Function interface. - .field("id", null, defaults["null"]) - // Arrow function bodies are allowed to be expressions. - .field("body", or(def("BlockStatement"), def("Expression"))) - // The current spec forbids arrow generators, so I have taken the - // liberty of enforcing that. TODO Report this. - .field("generator", false, defaults["false"]); + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) - def("YieldExpression") - .bases("Expression") - .build("argument", "delegate") - .field("argument", or(def("Expression"), null)) - .field("delegate", Boolean, defaults["false"]); + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } - def("GeneratorExpression") - .bases("Expression") - .build("body", "blocks", "filter") - .field("body", def("Expression")) - .field("blocks", [def("ComprehensionBlock")]) - .field("filter", or(def("Expression"), null)); + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - def("ComprehensionExpression") - .bases("Expression") - .build("body", "blocks", "filter") - .field("body", def("Expression")) - .field("blocks", [def("ComprehensionBlock")]) - .field("filter", or(def("Expression"), null)); +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 - def("ComprehensionBlock") - .bases("Node") - .build("left", "right", "each") - .field("left", def("Pattern")) - .field("right", def("Expression")) - .field("each", Boolean); + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } - def("Property") - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("value", or(def("Expression"), def("Pattern"))) - .field("method", Boolean, defaults["false"]) - .field("shorthand", Boolean, defaults["false"]) - .field("computed", Boolean, defaults["false"]); + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } - def("PropertyPattern") - .bases("Pattern") - .build("key", "pattern") - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("pattern", def("Pattern")) - .field("computed", Boolean, defaults["false"]); + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } - def("ObjectPattern") - .bases("Pattern") - .build("properties") - .field("properties", [or(def("PropertyPattern"), def("Property"))]); + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } - def("ArrayPattern") - .bases("Pattern") - .build("elements") - .field("elements", [or(def("Pattern"), null)]); + throw new TypeError('val must be string, number or Buffer') +} - def("MethodDefinition") - .bases("Declaration") - .build("kind", "key", "value", "static") - .field("kind", or("constructor", "method", "get", "set")) - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("value", def("Function")) - .field("computed", Boolean, defaults["false"]) - .field("static", Boolean, defaults["false"]); +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - def("SpreadElement") - .bases("Node") - .build("argument") - .field("argument", def("Expression")); + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } - def("ArrayExpression") - .field("elements", [or( - def("Expression"), - def("SpreadElement"), - def("RestElement"), - null - )]); + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - def("NewExpression") - .field("arguments", [or(def("Expression"), def("SpreadElement"))]); + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } - def("CallExpression") - .field("arguments", [or(def("Expression"), def("SpreadElement"))]); + return -1 +} - // Note: this node type is *not* an AssignmentExpression with a Pattern on - // the left-hand side! The existing AssignmentExpression type already - // supports destructuring assignments. AssignmentPattern nodes may appear - // wherever a Pattern is allowed, and the right-hand side represents a - // default value to be destructured against the left-hand side, if no - // value is otherwise provided. For example: default parameter values. - def("AssignmentPattern") - .bases("Pattern") - .build("left", "right") - .field("left", def("Pattern")) - .field("right", def("Expression")); +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} - var ClassBodyElement = or( - def("MethodDefinition"), - def("VariableDeclarator"), - def("ClassPropertyDefinition"), - def("ClassProperty") - ); +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} - def("ClassProperty") - .bases("Declaration") - .build("key") - .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) - .field("computed", Boolean, defaults["false"]); +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} - def("ClassPropertyDefinition") // static property - .bases("Declaration") - .build("definition") - // Yes, Virginia, circular definitions are permitted. - .field("definition", ClassBodyElement); +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } - def("ClassBody") - .bases("Declaration") - .build("body") - .field("body", [ClassBodyElement]); + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - def("ClassDeclaration") - .bases("Declaration") - .build("id", "body", "superClass") - .field("id", or(def("Identifier"), null)) - .field("body", def("ClassBody")) - .field("superClass", or(def("Expression"), null), defaults["null"]); + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} - def("ClassExpression") - .bases("Expression") - .build("id", "body", "superClass") - .field("id", or(def("Identifier"), null), defaults["null"]) - .field("body", def("ClassBody")) - .field("superClass", or(def("Expression"), null), defaults["null"]) - .field("implements", [def("ClassImplements")], defaults.emptyArray); +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} - def("ClassImplements") - .bases("Node") - .build("id") - .field("id", def("Identifier")) - .field("superClass", or(def("Expression"), null), defaults["null"]); +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} - // Specifier and ModuleSpecifier are abstract non-standard types - // introduced for definitional convenience. - def("Specifier").bases("Node"); +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} - // This supertype is shared/abused by both def/babel.js and - // def/esprima.js. In the future, it will be possible to load only one set - // of definitions appropriate for a given parser, but until then we must - // rely on default functions to reconcile the conflicting AST formats. - def("ModuleSpecifier") - .bases("Specifier") - // This local field is used by Babel/Acorn. It should not technically - // be optional in the Babel/Acorn AST format, but it must be optional - // in the Esprima AST format. - .field("local", or(def("Identifier"), null), defaults["null"]) - // The id and name fields are used by Esprima. The id field should not - // technically be optional in the Esprima AST format, but it must be - // optional in the Babel/Acorn AST format. - .field("id", or(def("Identifier"), null), defaults["null"]) - .field("name", or(def("Identifier"), null), defaults["null"]); +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} - def("TaggedTemplateExpression") - .bases("Expression") - .build("tag", "quasi") - .field("tag", def("Expression")) - .field("quasi", def("TemplateLiteral")); +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} - def("TemplateLiteral") - .bases("Expression") - .build("quasis", "expressions") - .field("quasis", [def("TemplateElement")]) - .field("expressions", [def("Expression")]); +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } - def("TemplateElement") - .bases("Node") - .build("value", "tail") - .field("value", {"cooked": String, "raw": String}) - .field("tail", Boolean); -}; + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining -},{"../lib/shared":22,"../lib/types":23,"./core":8}],11:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require('./es6')); + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var builtin = types.builtInTypes; - var defaults = fork.use(require("../lib/shared")).defaults; + if (!encoding) encoding = 'utf8' - def("Function") - .field("async", Boolean, defaults["false"]); + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - def("SpreadProperty") - .bases("Node") - .build("argument") - .field("argument", def("Expression")); + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - def("ObjectExpression") - .field("properties", [or(def("Property"), def("SpreadProperty"))]); + case 'ascii': + return asciiWrite(this, string, offset, length) - def("SpreadPropertyPattern") - .bases("Pattern") - .build("argument") - .field("argument", def("Pattern")); + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - def("ObjectPattern") - .field("properties", [or( - def("Property"), - def("PropertyPattern"), - def("SpreadPropertyPattern") - )]); + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - def("AwaitExpression") - .bases("Expression") - .build("argument", "all") - .field("argument", or(def("Expression"), null)) - .field("all", Boolean, defaults["false"]); -}; -},{"../lib/shared":22,"../lib/types":23,"./es6":10}],12:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./es7")); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - var types = fork.use(require("../lib/types")); - var defaults = fork.use(require("../lib/shared")).defaults; - var def = types.Type.def; - var or = types.Type.or; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} - def("VariableDeclaration") - .field("declarations", [or( - def("VariableDeclarator"), - def("Identifier") // Esprima deviation. - )]); +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - def("Property") - .field("value", or( - def("Expression"), - def("Pattern") // Esprima deviation. - )); +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} - def("ArrayPattern") - .field("elements", [or( - def("Pattern"), - def("SpreadElement"), - null - )]); +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] - def("ObjectPattern") - .field("properties", [or( - def("Property"), - def("PropertyPattern"), - def("SpreadPropertyPattern"), - def("SpreadProperty") // Used by Esprima. - )]); + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 -// Like ModuleSpecifier, except type:"ExportSpecifier" and buildable. -// export {} [from ...]; - def("ExportSpecifier") - .bases("ModuleSpecifier") - .build("id", "name"); + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint -// export <*> from ...; - def("ExportBatchSpecifier") - .bases("Specifier") - .build(); + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } -// Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. -// import {} from ...; - def("ImportSpecifier") - .bases("ModuleSpecifier") - .build("id", "name"); + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } -// import <* as id> from ...; - def("ImportNamespaceSpecifier") - .bases("ModuleSpecifier") - .build("id"); + res.push(codePoint) + i += bytesPerSequence + } -// import from ...; - def("ImportDefaultSpecifier") - .bases("ModuleSpecifier") - .build("id"); + return decodeCodePointsArray(res) +} - def("ExportDeclaration") - .bases("Declaration") - .build("default", "declaration", "specifiers", "source") - .field("default", Boolean) - .field("declaration", or( - def("Declaration"), - def("Expression"), // Implies default. - null - )) - .field("specifiers", [or( - def("ExportSpecifier"), - def("ExportBatchSpecifier") - )], defaults.emptyArray) - .field("source", or( - def("Literal"), - null - ), defaults["null"]); +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 - def("ImportDeclaration") - .bases("Declaration") - .build("specifiers", "source", "importKind") - .field("specifiers", [or( - def("ImportSpecifier"), - def("ImportNamespaceSpecifier"), - def("ImportDefaultSpecifier") - )], defaults.emptyArray) - .field("source", def("Literal")) - .field("importKind", or( - "value", - "type" - ), function() { - return "value"; - }); +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - def("Block") - .bases("Comment") - .build("value", /*optional:*/ "leading", "trailing"); + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} - def("Line") - .bases("Comment") - .build("value", /*optional:*/ "leading", "trailing"); -}; -},{"../lib/shared":22,"../lib/types":23,"./es7":11}],13:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./es7")); +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var defaults = fork.use(require("../lib/shared")).defaults; + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} - // Type Annotations - def("Type").bases("Node"); +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - def("AnyTypeAnnotation") - .bases("Type") - .build(); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - def("EmptyTypeAnnotation") - .bases("Type") - .build(); +function hexSlice (buf, start, end) { + var len = buf.length - def("MixedTypeAnnotation") - .bases("Type") - .build(); + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - def("VoidTypeAnnotation") - .bases("Type") - .build(); + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} - def("NumberTypeAnnotation") - .bases("Type") - .build(); +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} - def("NumberLiteralTypeAnnotation") - .bases("Type") - .build("value", "raw") - .field("value", Number) - .field("raw", String); +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end - // Babylon 6 differs in AST from Flow - // same as NumberLiteralTypeAnnotation - def("NumericLiteralTypeAnnotation") - .bases("Type") - .build("value", "raw") - .field("value", Number) - .field("raw", String); + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - def("StringTypeAnnotation") - .bases("Type") - .build(); + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - def("StringLiteralTypeAnnotation") - .bases("Type") - .build("value", "raw") - .field("value", String) - .field("raw", String); + if (end < start) end = start - def("BooleanTypeAnnotation") - .bases("Type") - .build(); + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} - def("BooleanLiteralTypeAnnotation") - .bases("Type") - .build("value", "raw") - .field("value", Boolean) - .field("raw", String); +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} - def("TypeAnnotation") - .bases("Node") - .build("typeAnnotation") - .field("typeAnnotation", def("Type")); +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - def("NullableTypeAnnotation") - .bases("Type") - .build("typeAnnotation") - .field("typeAnnotation", def("Type")); + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - def("NullLiteralTypeAnnotation") - .bases("Type") - .build(); + return val +} - def("NullTypeAnnotation") - .bases("Type") - .build(); +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - def("ThisTypeAnnotation") - .bases("Type") - .build(); + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - def("ExistsTypeAnnotation") - .bases("Type") - .build(); + return val +} - def("ExistentialTypeParam") - .bases("Type") - .build(); +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - def("FunctionTypeAnnotation") - .bases("Type") - .build("params", "returnType", "rest", "typeParameters") - .field("params", [def("FunctionTypeParam")]) - .field("returnType", def("Type")) - .field("rest", or(def("FunctionTypeParam"), null)) - .field("typeParameters", or(def("TypeParameterDeclaration"), null)); +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} - def("FunctionTypeParam") - .bases("Node") - .build("name", "typeAnnotation", "optional") - .field("name", def("Identifier")) - .field("typeAnnotation", def("Type")) - .field("optional", Boolean); +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} - def("ArrayTypeAnnotation") - .bases("Type") - .build("elementType") - .field("elementType", def("Type")); +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - def("ObjectTypeAnnotation") - .bases("Type") - .build("properties", "indexers", "callProperties") - .field("properties", [def("ObjectTypeProperty")]) - .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray) - .field("callProperties", - [def("ObjectTypeCallProperty")], - defaults.emptyArray) - .field("exact", Boolean, defaults["false"]); + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - def("ObjectTypeProperty") - .bases("Node") - .build("key", "value", "optional") - .field("key", or(def("Literal"), def("Identifier"))) - .field("value", def("Type")) - .field("optional", Boolean) - .field("variance", - or("plus", "minus", null), - defaults["null"]); +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - def("ObjectTypeIndexer") - .bases("Node") - .build("id", "key", "value") - .field("id", def("Identifier")) - .field("key", def("Type")) - .field("value", def("Type")) - .field("variance", - or("plus", "minus", null), - defaults["null"]); + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} - def("ObjectTypeCallProperty") - .bases("Node") - .build("value") - .field("value", def("FunctionTypeAnnotation")) - .field("static", Boolean, defaults["false"]); +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - def("QualifiedTypeIdentifier") - .bases("Node") - .build("qualification", "id") - .field("qualification", - or(def("Identifier"), - def("QualifiedTypeIdentifier"))) - .field("id", def("Identifier")); + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 - def("GenericTypeAnnotation") - .bases("Type") - .build("id", "typeParameters") - .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))) - .field("typeParameters", or(def("TypeParameterInstantiation"), null)); + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - def("MemberTypeAnnotation") - .bases("Type") - .build("object", "property") - .field("object", def("Identifier")) - .field("property", - or(def("MemberTypeAnnotation"), - def("GenericTypeAnnotation"))); + return val +} - def("UnionTypeAnnotation") - .bases("Type") - .build("types") - .field("types", [def("Type")]); +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - def("IntersectionTypeAnnotation") - .bases("Type") - .build("types") - .field("types", [def("Type")]); + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - def("TypeofTypeAnnotation") - .bases("Type") - .build("argument") - .field("argument", def("Type")); + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - def("Identifier") - .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]); + return val +} - def("TypeParameterDeclaration") - .bases("Node") - .build("params") - .field("params", [def("TypeParameter")]); +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} - def("TypeParameterInstantiation") - .bases("Node") - .build("params") - .field("params", [def("Type")]); +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} - def("TypeParameter") - .bases("Type") - .build("name", "variance", "bound") - .field("name", String) - .field("variance", - or("plus", "minus", null), - defaults["null"]) - .field("bound", - or(def("TypeAnnotation"), null), - defaults["null"]); +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} - def("Function") - .field("returnType", - or(def("TypeAnnotation"), null), - defaults["null"]) - .field("typeParameters", - or(def("TypeParameterDeclaration"), null), - defaults["null"]); +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - def("ClassProperty") - .build("key", "value", "typeAnnotation", "static") - .field("value", or(def("Expression"), null)) - .field("typeAnnotation", or(def("TypeAnnotation"), null)) - .field("static", Boolean, defaults["false"]) - .field("variance", - or("plus", "minus", null), - defaults["null"]); + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} - def("ClassImplements") - .field("typeParameters", - or(def("TypeParameterInstantiation"), null), - defaults["null"]); +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - def("InterfaceDeclaration") - .bases("Declaration") - .build("id", "body", "extends") - .field("id", def("Identifier")) - .field("typeParameters", - or(def("TypeParameterDeclaration"), null), - defaults["null"]) - .field("body", def("ObjectTypeAnnotation")) - .field("extends", [def("InterfaceExtends")]); + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} - def("DeclareInterface") - .bases("InterfaceDeclaration") - .build("id", "body", "extends"); +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} - def("InterfaceExtends") - .bases("Node") - .build("id") - .field("id", def("Identifier")) - .field("typeParameters", or(def("TypeParameterInstantiation"), null)); +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} - def("TypeAlias") - .bases("Declaration") - .build("id", "typeParameters", "right") - .field("id", def("Identifier")) - .field("typeParameters", or(def("TypeParameterDeclaration"), null)) - .field("right", def("Type")); +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} - def("DeclareTypeAlias") - .bases("TypeAlias") - .build("id", "typeParameters", "right"); +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} - def("TypeCastExpression") - .bases("Expression") - .build("expression", "typeAnnotation") - .field("expression", def("Expression")) - .field("typeAnnotation", def("TypeAnnotation")); +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} - def("TupleTypeAnnotation") - .bases("Type") - .build("types") - .field("types", [def("Type")]); +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - def("DeclareVariable") - .bases("Statement") - .build("id") - .field("id", def("Identifier")); + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - def("DeclareFunction") - .bases("Statement") - .build("id") - .field("id", def("Identifier")); + return offset + byteLength +} - def("DeclareClass") - .bases("InterfaceDeclaration") - .build("id"); +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - def("DeclareModule") - .bases("Statement") - .build("id", "body") - .field("id", or(def("Identifier"), def("Literal"))) - .field("body", def("BlockStatement")); + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - def("DeclareModuleExports") - .bases("Statement") - .build("typeAnnotation") - .field("typeAnnotation", def("Type")); + return offset + byteLength +} - def("DeclareExportDeclaration") - .bases("Declaration") - .build("default", "declaration", "specifiers", "source") - .field("default", Boolean) - .field("declaration", or( - def("DeclareVariable"), - def("DeclareFunction"), - def("DeclareClass"), - def("Type"), // Implies default. - null - )) - .field("specifiers", [or( - def("ExportSpecifier"), - def("ExportBatchSpecifier") - )], defaults.emptyArray) - .field("source", or( - def("Literal"), - null - ), defaults["null"]); +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} - def("DeclareExportAllDeclaration") - .bases("Declaration") - .build("source") - .field("source", or( - def("Literal"), - null - ), defaults["null"]); -}; +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} -},{"../lib/shared":22,"../lib/types":23,"./es7":11}],14:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./es7")); +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var defaults = fork.use(require("../lib/shared")).defaults; +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} - def("JSXAttribute") - .bases("Node") - .build("name", "value") - .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))) - .field("value", or( - def("Literal"), // attr="value" - def("JSXExpressionContainer"), // attr={value} - null // attr= or just attr - ), defaults["null"]); +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} - def("JSXIdentifier") - .bases("Identifier") - .build("name") - .field("name", String); +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - def("JSXNamespacedName") - .bases("Node") - .build("namespace", "name") - .field("namespace", def("JSXIdentifier")) - .field("name", def("JSXIdentifier")); - - def("JSXMemberExpression") - .bases("MemberExpression") - .build("object", "property") - .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))) - .field("property", def("JSXIdentifier")) - .field("computed", Boolean, defaults.false); - - var JSXElementName = or( - def("JSXIdentifier"), - def("JSXNamespacedName"), - def("JSXMemberExpression") - ); - - def("JSXSpreadAttribute") - .bases("Node") - .build("argument") - .field("argument", def("Expression")); - - var JSXAttributes = [or( - def("JSXAttribute"), - def("JSXSpreadAttribute") - )]; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - def("JSXExpressionContainer") - .bases("Expression") - .build("expression") - .field("expression", def("Expression")); + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - def("JSXElement") - .bases("Expression") - .build("openingElement", "closingElement", "children") - .field("openingElement", def("JSXOpeningElement")) - .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]) - .field("children", [or( - def("JSXElement"), - def("JSXExpressionContainer"), - def("JSXText"), - def("Literal") // TODO Esprima should return JSXText instead. - )], defaults.emptyArray) - .field("name", JSXElementName, function () { - // Little-known fact: the `this` object inside a default function - // is none other than the partially-built object itself, and any - // fields initialized directly from builder function arguments - // (like openingElement, closingElement, and children) are - // guaranteed to be available. - return this.openingElement.name; - }, true) // hidden from traversal - .field("selfClosing", Boolean, function () { - return this.openingElement.selfClosing; - }, true) // hidden from traversal - .field("attributes", JSXAttributes, function () { - return this.openingElement.attributes; - }, true); // hidden from traversal + return offset + byteLength +} - def("JSXOpeningElement") - .bases("Node") // TODO Does this make sense? Can't really be an JSXElement. - .build("name", "attributes", "selfClosing") - .field("name", JSXElementName) - .field("attributes", JSXAttributes, defaults.emptyArray) - .field("selfClosing", Boolean, defaults["false"]); +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - def("JSXClosingElement") - .bases("Node") // TODO Same concern. - .build("name") - .field("name", JSXElementName); + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - def("JSXText") - .bases("Literal") - .build("value") - .field("value", String); + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - def("JSXEmptyExpression").bases("Expression").build(); + return offset + byteLength +} -}; -},{"../lib/shared":22,"../lib/types":23,"./es7":11}],15:[function(require,module,exports){ -module.exports = function (fork) { - fork.use(require("./core")); - var types = fork.use(require("../lib/types")); - var def = types.Type.def; - var or = types.Type.or; - var shared = fork.use(require("../lib/shared")); - var geq = shared.geq; - var defaults = shared.defaults; +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} - def("Function") - // SpiderMonkey allows expression closures: function(x) x+1 - .field("body", or(def("BlockStatement"), def("Expression"))); +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} - def("ForInStatement") - .build("left", "right", "body", "each") - .field("each", Boolean, defaults["false"]); +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} - def("ForOfStatement") - .bases("Statement") - .build("left", "right", "body") - .field("left", or( - def("VariableDeclaration"), - def("Expression"))) - .field("right", def("Expression")) - .field("body", def("Statement")); +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} - def("LetStatement") - .bases("Statement") - .build("head", "body") - // TODO Deviating from the spec by reusing VariableDeclarator here. - .field("head", [def("VariableDeclarator")]) - .field("body", def("Statement")); +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} - def("LetExpression") - .bases("Expression") - .build("head", "body") - // TODO Deviating from the spec by reusing VariableDeclarator here. - .field("head", [def("VariableDeclarator")]) - .field("body", def("Expression")); +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} - def("GraphExpression") - .bases("Expression") - .build("index", "expression") - .field("index", geq(0)) - .field("expression", def("Literal")); +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} - def("GraphIndexExpression") - .bases("Expression") - .build("index") - .field("index", geq(0)); -}; -},{"../lib/shared":22,"../lib/types":23,"./core":8}],16:[function(require,module,exports){ -module.exports = function (defs) { - var used = []; - var usedResult = []; - var fork = {}; +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} - function use(plugin) { - var idx = used.indexOf(plugin); - if (idx === -1) { - idx = used.length; - used.push(plugin); - usedResult[idx] = plugin(fork); - } - return usedResult[idx]; - } +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} - fork.use = use; +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} - var types = use(require('./lib/types')); +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} - defs.forEach(use); +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} - types.finalize(); +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start - var exports = { - Type: types.Type, - builtInTypes: types.builtInTypes, - namedTypes: types.namedTypes, - builders: types.builders, - defineMethod: types.defineMethod, - getFieldNames: types.getFieldNames, - getFieldValue: types.getFieldValue, - eachField: types.eachField, - someField: types.someField, - getSupertypeNames: types.getSupertypeNames, - astNodesAreEquivalent: use(require("./lib/equiv")), - finalize: types.finalize, - Path: use(require('./lib/path')), - NodePath: use(require("./lib/node-path")), - PathVisitor: use(require("./lib/path-visitor")), - use: use - }; + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - exports.visit = exports.PathVisitor.visit; + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - return exports; -}; -},{"./lib/equiv":17,"./lib/node-path":18,"./lib/path":20,"./lib/path-visitor":19,"./lib/types":23}],17:[function(require,module,exports){ -module.exports = function (fork) { - var types = fork.use(require('../lib/types')); - var getFieldNames = types.getFieldNames; - var getFieldValue = types.getFieldValue; - var isArray = types.builtInTypes.array; - var isObject = types.builtInTypes.object; - var isDate = types.builtInTypes.Date; - var isRegExp = types.builtInTypes.RegExp; - var hasOwn = Object.prototype.hasOwnProperty; + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } - function astNodesAreEquivalent(a, b, problemPath) { - if (isArray.check(problemPath)) { - problemPath.length = 0; - } else { - problemPath = null; - } + var len = end - start + var i - return areEquivalent(a, b, problemPath); + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } - astNodesAreEquivalent.assert = function (a, b) { - var problemPath = []; - if (!astNodesAreEquivalent(a, b, problemPath)) { - if (problemPath.length === 0) { - if (a !== b) { - throw new Error("Nodes must be equal"); - } - } else { - throw new Error( - "Nodes differ in the following path: " + - problemPath.map(subscriptForProperty).join("") - ); - } - } - }; + return len +} - function subscriptForProperty(property) { - if (/[_$a-z][_$a-z0-9]*/i.test(property)) { - return "." + property; - } - return "[" + JSON.stringify(property) + "]"; +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } - function areEquivalent(a, b, problemPath) { - if (a === b) { - return true; - } - - if (isArray.check(a)) { - return arraysAreEquivalent(a, b, problemPath); - } + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } - if (isObject.check(a)) { - return objectsAreEquivalent(a, b, problemPath); - } + if (end <= start) { + return this + } - if (isDate.check(a)) { - return isDate.check(b) && (+a === +b); - } + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (isRegExp.check(a)) { - return isRegExp.check(b) && ( - a.source === b.source && - a.global === b.global && - a.multiline === b.multiline && - a.ignoreCase === b.ignoreCase - ); - } + if (!val) val = 0 - return a == b; + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] } + } - function arraysAreEquivalent(a, b, problemPath) { - isArray.assert(a); - var aLength = a.length; + return this +} - if (!isArray.check(b) || b.length !== aLength) { - if (problemPath) { - problemPath.push("length"); - } - return false; - } +// HELPER FUNCTIONS +// ================ - for (var i = 0; i < aLength; ++i) { - if (problemPath) { - problemPath.push(i); - } +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - if (i in a !== i in b) { - return false; - } +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} - if (!areEquivalent(a[i], b[i], problemPath)) { - return false; - } +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} - if (problemPath) { - var problemPathTail = problemPath.pop(); - if (problemPathTail !== i) { - throw new Error("" + problemPathTail); - } - } - } +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] - return true; - } + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) - function objectsAreEquivalent(a, b, problemPath) { - isObject.assert(a); - if (!isObject.check(b)) { - return false; + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue } - // Fast path for a common property of AST nodes. - if (a.type !== b.type) { - if (problemPath) { - problemPath.push("type"); - } - return false; - } + // valid lead + leadSurrogate = codePoint - var aNames = getFieldNames(a); - var aNameCount = aNames.length; + continue + } - var bNames = getFieldNames(b); - var bNameCount = bNames.length; + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } - if (aNameCount === bNameCount) { - for (var i = 0; i < aNameCount; ++i) { - var name = aNames[i]; - var aChild = getFieldValue(a, name); - var bChild = getFieldValue(b, name); - - if (problemPath) { - problemPath.push(name); - } - - if (!areEquivalent(aChild, bChild, problemPath)) { - return false; - } + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } - if (problemPath) { - var problemPathTail = problemPath.pop(); - if (problemPathTail !== name) { - throw new Error("" + problemPathTail); - } - } - } + leadSurrogate = null - return true; - } + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } - if (!problemPath) { - return false; - } + return bytes +} - // Since aNameCount !== bNameCount, we need to find some name that's - // missing in aNames but present in bNames, or vice-versa. +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} - var seenNames = Object.create(null); +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break - for (i = 0; i < aNameCount; ++i) { - seenNames[aNames[i]] = true; - } + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } - for (i = 0; i < bNameCount; ++i) { - name = bNames[i]; + return byteArray +} - if (!hasOwn.call(seenNames, name)) { - problemPath.push(name); - return false; - } +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} - delete seenNames[name]; - } +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} - for (name in seenNames) { - problemPath.push(name); - break; - } +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') +} - return false; - } - - return astNodesAreEquivalent; -}; +// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` +function isArrayBufferView (obj) { + return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) +} -},{"../lib/types":23}],18:[function(require,module,exports){ -module.exports = function (fork) { - var types = fork.use(require("./types")); - var n = types.namedTypes; - var b = types.builders; - var isNumber = types.builtInTypes.number; - var isArray = types.builtInTypes.array; - var Path = fork.use(require("./path")); - var Scope = fork.use(require("./scope")); +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} - function NodePath(value, parentPath, name) { - if (!(this instanceof NodePath)) { - throw new Error("NodePath constructor cannot be invoked without 'new'"); - } - Path.call(this, value, parentPath, name); - } +},{"base64-js":3,"ieee754":8}],6:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - var NPp = NodePath.prototype = Object.create(Path.prototype, { - constructor: { - value: NodePath, - enumerable: false, - writable: true, - configurable: true - } - }); +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. - Object.defineProperties(NPp, { - node: { - get: function () { - Object.defineProperty(this, "node", { - configurable: true, // Enable deletion. - value: this._computeNode() - }); +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - return this.node; - } - }, +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - parent: { - get: function () { - Object.defineProperty(this, "parent", { - configurable: true, // Enable deletion. - value: this._computeParent() - }); +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - return this.parent; - } - }, +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - scope: { - get: function () { - Object.defineProperty(this, "scope", { - configurable: true, // Enable deletion. - value: this._computeScope() - }); +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - return this.scope; - } - } - }); +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - NPp.replace = function () { - delete this.node; - delete this.parent; - delete this.scope; - return Path.prototype.replace.apply(this, arguments); - }; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - NPp.prune = function () { - var remainingNodePath = this.parent; +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; - this.replace(); +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - return cleanUpNodesAfterPrune(remainingNodePath); - }; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; - // The value of the first ancestor Path whose value is a Node. - NPp._computeNode = function () { - var value = this.value; - if (n.Node.check(value)) { - return value; - } +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - var pp = this.parentPath; - return pp && pp.node || null; - }; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; - // The first ancestor Path whose value is a Node distinct from this.node. - NPp._computeParent = function () { - var value = this.value; - var pp = this.parentPath; +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; - if (!n.Node.check(value)) { - while (pp && !n.Node.check(pp.value)) { - pp = pp.parentPath; - } +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; - if (pp) { - pp = pp.parentPath; - } - } +exports.isBuffer = Buffer.isBuffer; - while (pp && !n.Node.check(pp.value)) { - pp = pp.parentPath; - } +function objectToString(o) { + return Object.prototype.toString.call(o); +} - return pp || null; - }; +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":10}],7:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - // The closest enclosing scope that governs this node. - NPp._computeScope = function () { - var value = this.value; - var pp = this.parentPath; - var scope = pp && pp.scope; +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; - if (n.Node.check(value) && - Scope.isEstablishedBy(value)) { - scope = new Scope(this, scope); - } +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - return scope || null; - }; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - NPp.getValueProperty = function (name) { - return types.getFieldValue(this.value, name); - }; +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; - /** - * Determine whether this.node needs to be wrapped in parentheses in order - * for a parser to reproduce the same local AST structure. - * - * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression - * whose operator is "+" needs parentheses, because `1 + 2 * 3` would - * parse differently. - * - * If assumeExpressionContext === true, we don't worry about edge cases - * like an anonymous FunctionExpression appearing lexically first in its - * enclosing statement and thus needing parentheses to avoid being parsed - * as a FunctionDeclaration with a missing name. - */ - NPp.needsParens = function (assumeExpressionContext) { - var pp = this.parentPath; - if (!pp) { - return false; - } +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; - var node = this.value; +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - // Only expressions need parentheses. - if (!n.Expression.check(node)) { - return false; - } + if (!this._events) + this._events = {}; - // Identifiers never need parentheses. - if (node.type === "Identifier") { - return false; - } + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - while (!n.Node.check(pp.value)) { - pp = pp.parentPath; - if (!pp) { - return false; - } - } + handler = this._events[type]; - var parent = pp.value; + if (isUndefined(handler)) + return false; - switch (node.type) { - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - return parent.type === "MemberExpression" - && this.name === "object" - && parent.object === node; + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - case "BinaryExpression": - case "LogicalExpression": - switch (parent.type) { - case "CallExpression": - return this.name === "callee" - && parent.callee === node; + return true; +}; - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - return true; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - case "MemberExpression": - return this.name === "object" - && parent.object === node; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - case "BinaryExpression": - case "LogicalExpression": - var po = parent.operator; - var pp = PRECEDENCE[po]; - var no = node.operator; - var np = PRECEDENCE[no]; + if (!this._events) + this._events = {}; - if (pp > np) { - return true; - } + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - if (pp === np && this.name === "right") { - if (parent.right !== node) { - throw new Error("Nodes must be equal"); - } - return true; - } + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - default: - return false; - } + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - case "SequenceExpression": - switch (parent.type) { - case "ForStatement": - // Although parentheses wouldn't hurt around sequence - // expressions in the head of for loops, traditional style - // dictates that e.g. i++, j++ should not be wrapped with - // parentheses. - return false; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } - case "ExpressionStatement": - return this.name !== "expression"; + return this; +}; - default: - // Otherwise err on the side of overparenthesization, adding - // explicit exceptions above if this proves overzealous. - return true; - } +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - case "YieldExpression": - switch (parent.type) { - case "BinaryExpression": - case "LogicalExpression": - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "CallExpression": - case "MemberExpression": - case "NewExpression": - case "ConditionalExpression": - case "YieldExpression": - return true; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - default: - return false; - } + var fired = false; - case "Literal": - return parent.type === "MemberExpression" - && isNumber.check(node.value) - && this.name === "object" - && parent.object === node; + function g() { + this.removeListener(type, g); - case "AssignmentExpression": - case "ConditionalExpression": - switch (parent.type) { - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "BinaryExpression": - case "LogicalExpression": - return true; + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - case "CallExpression": - return this.name === "callee" - && parent.callee === node; + g.listener = listener; + this.on(type, g); - case "ConditionalExpression": - return this.name === "test" - && parent.test === node; + return this; +}; - case "MemberExpression": - return this.name === "object" - && parent.object === node; +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - default: - return false; - } + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - default: - if (parent.type === "NewExpression" && - this.name === "callee" && - parent.callee === node) { - return containsCallExpression(node); - } - } + if (!this._events || !this._events[type]) + return this; - if (assumeExpressionContext !== true && - !this.canBeFirstInStatement() && - this.firstInStatement()) - return true; + list = this._events[type]; + length = list.length; + position = -1; - return false; - }; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - function isBinary(node) { - return n.BinaryExpression.check(node) - || n.LogicalExpression.check(node); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - function isUnaryLike(node) { - return n.UnaryExpression.check(node) - // I considered making SpreadElement and SpreadProperty subtypes - // of UnaryExpression, but they're not really Expression nodes. - || (n.SpreadElement && n.SpreadElement.check(node)) - || (n.SpreadProperty && n.SpreadProperty.check(node)); + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - var PRECEDENCE = {}; - [["||"], - ["&&"], - ["|"], - ["^"], - ["&"], - ["==", "===", "!=", "!=="], - ["<", ">", "<=", ">=", "in", "instanceof"], - [">>", "<<", ">>>"], - ["+", "-"], - ["*", "/", "%"] - ].forEach(function (tier, i) { - tier.forEach(function (op) { - PRECEDENCE[op] = i; - }); - }); + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - function containsCallExpression(node) { - if (n.CallExpression.check(node)) { - return true; - } + return this; +}; - if (isArray.check(node)) { - return node.some(containsCallExpression); - } +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - if (n.Node.check(node)) { - return types.someField(node, function (name, child) { - return containsCallExpression(child); - }); - } + if (!this._events) + return this; - return false; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - NPp.canBeFirstInStatement = function () { - var node = this.node; - return !n.FunctionExpression.check(node) - && !n.ObjectExpression.check(node); - }; + listeners = this._events[type]; - NPp.firstInStatement = function () { - return firstInStatement(this); - }; + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - function firstInStatement(path) { - for (var node, parent; path.parent; path = path.parent) { - node = path.node; - parent = path.parent.node; + return this; +}; - if (n.BlockStatement.check(parent) && - path.parent.name === "body" && - path.name === 0) { - if (parent.body[0] !== node) { - throw new Error("Nodes must be equal"); - } - return true; - } +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - if (n.ExpressionStatement.check(parent) && - path.name === "expression") { - if (parent.expression !== node) { - throw new Error("Nodes must be equal"); - } - return true; - } +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - if (n.SequenceExpression.check(parent) && - path.parent.name === "expressions" && - path.name === 0) { - if (parent.expressions[0] !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - if (n.CallExpression.check(parent) && - path.name === "callee") { - if (parent.callee !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; - if (n.MemberExpression.check(parent) && - path.name === "object") { - if (parent.object !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } +function isFunction(arg) { + return typeof arg === 'function'; +} - if (n.ConditionalExpression.check(parent) && - path.name === "test") { - if (parent.test !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } +function isNumber(arg) { + return typeof arg === 'number'; +} - if (isBinary(parent) && - path.name === "left") { - if (parent.left !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - if (n.UnaryExpression.check(parent) && - !parent.prefix && - path.name === "argument") { - if (parent.argument !== node) { - throw new Error("Nodes must be equal"); - } - continue; - } +function isUndefined(arg) { + return arg === void 0; +} - return false; - } +},{}],8:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] - return true; - } + i += d - /** - * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up. - */ - function cleanUpNodesAfterPrune(remainingNodePath) { - if (n.VariableDeclaration.check(remainingNodePath.node)) { - var declarations = remainingNodePath.get('declarations').value; - if (!declarations || declarations.length === 0) { - return remainingNodePath.prune(); - } - } else if (n.ExpressionStatement.check(remainingNodePath.node)) { - if (!remainingNodePath.get('expression').value) { - return remainingNodePath.prune(); - } - } else if (n.IfStatement.check(remainingNodePath.node)) { - cleanUpIfStatementAfterPrune(remainingNodePath); - } + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - return remainingNodePath; - } + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - function cleanUpIfStatementAfterPrune(ifStatement) { - var testExpression = ifStatement.get('test').value; - var alternate = ifStatement.get('alternate').value; - var consequent = ifStatement.get('consequent').value; + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} - if (!consequent && !alternate) { - var testExpressionStatement = b.expressionStatement(testExpression); +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - ifStatement.replace(testExpressionStatement); - } else if (!consequent && alternate) { - var negatedTestExpression = b.unaryExpression('!', testExpression, true); + value = Math.abs(value) - if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') { - negatedTestExpression = testExpression.argument; - } + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } - ifStatement.get("test").replace(negatedTestExpression); - ifStatement.get("consequent").replace(alternate); - ifStatement.get("alternate").replace(); - } + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 } + } - return NodePath; -}; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -},{"./path":20,"./scope":21,"./types":23}],19:[function(require,module,exports){ -var hasOwn = Object.prototype.hasOwnProperty; + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -module.exports = function (fork) { - var types = fork.use(require("./types")); - var NodePath = fork.use(require("./node-path")); - var Printable = types.namedTypes.Printable; - var isArray = types.builtInTypes.array; - var isObject = types.builtInTypes.object; - var isFunction = types.builtInTypes.function; - var undefined; + buffer[offset + i - d] |= s * 128 +} - function PathVisitor() { - if (!(this instanceof PathVisitor)) { - throw new Error( - "PathVisitor constructor cannot be invoked without 'new'" - ); - } +},{}],9:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} - // Permanent state. - this._reusableContextStack = []; +},{}],10:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ - this._methodNameTable = computeMethodNameTable(this); - this._shouldVisitComments = - hasOwn.call(this._methodNameTable, "Block") || - hasOwn.call(this._methodNameTable, "Line"); +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} - this.Context = makeContextConstructor(this); +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} - // State reset every time PathVisitor.prototype.visit is called. - this._visiting = false; - this._changeReported = false; - } +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} - function computeMethodNameTable(visitor) { - var typeNames = Object.create(null); +},{}],11:[function(require,module,exports){ +var toString = {}.toString; - for (var methodName in visitor) { - if (/^visit[A-Z]/.test(methodName)) { - typeNames[methodName.slice("visit".length)] = true; - } - } +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; - var supertypeTable = types.computeSupertypeLookupTable(typeNames); - var methodNameTable = Object.create(null); +},{}],12:[function(require,module,exports){ +exports.endianness = function () { return 'LE' }; - var typeNames = Object.keys(supertypeTable); - var typeNameCount = typeNames.length; - for (var i = 0; i < typeNameCount; ++i) { - var typeName = typeNames[i]; - methodName = "visit" + supertypeTable[typeName]; - if (isFunction.check(visitor[methodName])) { - methodNameTable[typeName] = methodName; - } - } - - return methodNameTable; +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname } + else return ''; +}; - PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { - if (methods instanceof PathVisitor) { - return methods; - } +exports.loadavg = function () { return [] }; - if (!isObject.check(methods)) { - // An empty visitor? - return new PathVisitor; - } +exports.uptime = function () { return 0 }; - function Visitor() { - if (!(this instanceof Visitor)) { - throw new Error( - "Visitor constructor cannot be invoked without 'new'" - ); - } - PathVisitor.call(this); - } +exports.freemem = function () { + return Number.MAX_VALUE; +}; - var Vp = Visitor.prototype = Object.create(PVp); - Vp.constructor = Visitor; +exports.totalmem = function () { + return Number.MAX_VALUE; +}; - extend(Vp, methods); - extend(Visitor, PathVisitor); +exports.cpus = function () { return [] }; - isFunction.assert(Visitor.fromMethodsObject); - isFunction.assert(Visitor.visit); +exports.type = function () { return 'Browser' }; - return new Visitor; - }; +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; - function extend(target, source) { - for (var property in source) { - if (hasOwn.call(source, property)) { - target[property] = source[property]; - } - } +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; - return target; - } +exports.arch = function () { return 'javascript' }; - PathVisitor.visit = function visit(node, methods) { - return PathVisitor.fromMethodsObject(methods).visit(node); - }; +exports.platform = function () { return 'browser' }; - var PVp = PathVisitor.prototype; +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; - PVp.visit = function () { - if (this._visiting) { - throw new Error( - "Recursively calling visitor.visit(path) resets visitor state. " + - "Try this.visit(path) or this.traverse(path) instead." - ); - } +exports.EOL = '\n'; - // Private state that needs to be reset before every traversal. - this._visiting = true; - this._changeReported = false; - this._abortRequested = false; +},{}],13:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - var argc = arguments.length; - var args = new Array(argc) - for (var i = 0; i < argc; ++i) { - args[i] = arguments[i]; - } +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } - if (!(args[0] instanceof NodePath)) { - args[0] = new NodePath({root: args[0]}).get("root"); - } + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } - // Called with the same arguments as .visit. - this.reset.apply(this, args); + return parts; +} - try { - var root = this.visitWithoutReset(args[0]); - var didNotThrow = true; - } finally { - this._visiting = false; +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; - if (!didNotThrow && this._abortRequested) { - // If this.visitWithoutReset threw an exception and - // this._abortRequested was set to true, return the root of - // the AST instead of letting the exception propagate, so that - // client code does not have to provide a try-catch block to - // intercept the AbortRequest exception. Other kinds of - // exceptions will propagate without being intercepted and - // rethrown by a catch block, so their stacks will accurately - // reflect the original throwing context. - return args[0].value; - } - } +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; - return root; - }; + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); - PVp.AbortRequest = function AbortRequest() {}; - PVp.abort = function () { - var visitor = this; - visitor._abortRequested = true; - var request = new visitor.AbortRequest(); + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } - // If you decide to catch this exception and stop it from propagating, - // make sure to call its cancel method to avoid silencing other - // exceptions that might be thrown later in the traversal. - request.cancel = function () { - visitor._abortRequested = false; - }; + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } - throw request; - }; + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) - PVp.reset = function (path/*, additional arguments */) { - // Empty stub; may be reassigned or overridden by subclasses. - }; + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); - PVp.visitWithoutReset = function (path) { - if (this instanceof this.Context) { - // Since this.Context.prototype === this, there's a chance we - // might accidentally call context.visitWithoutReset. If that - // happens, re-invoke the method against context.visitor. - return this.visitor.visitWithoutReset(path); - } + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; - if (!(path instanceof NodePath)) { - throw new Error(""); - } +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; - var value = path.value; + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); - var methodName = value && - typeof value === "object" && - typeof value.type === "string" && - this._methodNameTable[value.type]; + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } - if (methodName) { - var context = this.acquireContext(path); - try { - return context.invokeVisitorMethod(methodName); - } finally { - this.releaseContext(context); - } + return (isAbsolute ? '/' : '') + path; +}; - } else { - // If there was no visitor method to call, visit the children of - // this node generically. - return visitChildren(path, this); - } - }; +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; - function visitChildren(path, visitor) { - if (!(path instanceof NodePath)) { - throw new Error(""); - } - if (!(visitor instanceof PathVisitor)) { - throw new Error(""); - } +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; - var value = path.value; - if (isArray.check(value)) { - path.each(visitor.visitWithoutReset, visitor); - } else if (!isObject.check(value)) { - // No children to visit. - } else { - var childNames = types.getFieldNames(value); +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); - // The .comments field of the Node type is hidden, so we only - // visit it if the visitor defines visitBlock or visitLine, and - // value.comments is defined. - if (visitor._shouldVisitComments && - value.comments && - childNames.indexOf("comments") < 0) { - childNames.push("comments"); - } + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } - var childCount = childNames.length; - var childPaths = []; + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } - for (var i = 0; i < childCount; ++i) { - var childName = childNames[i]; - if (!hasOwn.call(value, childName)) { - value[childName] = types.getFieldValue(value, childName); - } - childPaths.push(path.get(childName)); - } + if (start > end) return []; + return arr.slice(start, end - start + 1); + } - for (var i = 0; i < childCount; ++i) { - visitor.visitWithoutReset(childPaths[i]); - } - } + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); - return path.value; + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; } + } - PVp.acquireContext = function (path) { - if (this._reusableContextStack.length === 0) { - return new this.Context(path); - } - return this._reusableContextStack.pop().reset(path); - }; + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } - PVp.releaseContext = function (context) { - if (!(context instanceof this.Context)) { - throw new Error(""); - } - this._reusableContextStack.push(context); - context.currentPath = null; - }; + outputParts = outputParts.concat(toParts.slice(samePartsLength)); - PVp.reportChanged = function () { - this._changeReported = true; - }; + return outputParts.join('/'); +}; - PVp.wasChangeReported = function () { - return this._changeReported; - }; +exports.sep = '/'; +exports.delimiter = ':'; - function makeContextConstructor(visitor) { - function Context(path) { - if (!(this instanceof Context)) { - throw new Error(""); - } - if (!(this instanceof PathVisitor)) { - throw new Error(""); - } - if (!(path instanceof NodePath)) { - throw new Error(""); - } +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; - Object.defineProperty(this, "visitor", { - value: visitor, - writable: false, - enumerable: true, - configurable: false - }); + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } - this.currentPath = path; - this.needToCallTraverse = true; + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } - Object.seal(this); - } + return root + dir; +}; - if (!(visitor instanceof PathVisitor)) { - throw new Error(""); - } - // Note that the visitor object is the prototype of Context.prototype, - // so all visitor methods are inherited by context objects. - var Cp = Context.prototype = Object.create(visitor); +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; - Cp.constructor = Context; - extend(Cp, sharedContextProtoMethods); - return Context; - } +exports.extname = function(path) { + return splitPath(path)[3]; +}; -// Every PathVisitor has a different this.Context constructor and -// this.Context.prototype object, but those prototypes can all use the -// same reset, invokeVisitorMethod, and traverse function objects. - var sharedContextProtoMethods = Object.create(null); +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} - sharedContextProtoMethods.reset = - function reset(path) { - if (!(this instanceof this.Context)) { - throw new Error(""); - } - if (!(path instanceof NodePath)) { - throw new Error(""); - } +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; - this.currentPath = path; - this.needToCallTraverse = true; +}).call(this,require('_process')) +},{"_process":15}],14:[function(require,module,exports){ +(function (process){ +'use strict'; - return this; - }; +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} - sharedContextProtoMethods.invokeVisitorMethod = - function invokeVisitorMethod(methodName) { - if (!(this instanceof this.Context)) { - throw new Error(""); - } - if (!(this.currentPath instanceof NodePath)) { - throw new Error(""); - } +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} - var result = this.visitor[methodName].call(this, this.currentPath); +}).call(this,require('_process')) +},{"_process":15}],15:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; - if (result === false) { - // Visitor methods return false to indicate that they have handled - // their own traversal needs, and we should not complain if - // this.needToCallTraverse is still true. - this.needToCallTraverse = false; +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - } else if (result !== undefined) { - // Any other non-undefined value returned from the visitor method - // is interpreted as a replacement value. - this.currentPath = this.currentPath.replace(result)[0]; +var cachedSetTimeout; +var cachedClearTimeout; - if (this.needToCallTraverse) { - // If this.traverse still hasn't been called, visit the - // children of the replacement node. - this.traverse(this.currentPath); - } - } - - if (this.needToCallTraverse !== false) { - throw new Error( - "Must either call this.traverse or return false in " + methodName - ); - } +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - var path = this.currentPath; - return path && path.value; - }; - sharedContextProtoMethods.traverse = - function traverse(path, newVisitor) { - if (!(this instanceof this.Context)) { - throw new Error(""); - } - if (!(path instanceof NodePath)) { - throw new Error(""); - } - if (!(this.currentPath instanceof NodePath)) { - throw new Error(""); - } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } - this.needToCallTraverse = false; - return visitChildren(path, PathVisitor.fromMethodsObject( - newVisitor || this.visitor - )); - }; - sharedContextProtoMethods.visit = - function visit(path, newVisitor) { - if (!(this instanceof this.Context)) { - throw new Error(""); - } - if (!(path instanceof NodePath)) { - throw new Error(""); - } - if (!(this.currentPath instanceof NodePath)) { - throw new Error(""); - } +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - this.needToCallTraverse = false; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} - return PathVisitor.fromMethodsObject( - newVisitor || this.visitor - ).visitWithoutReset(path); - }; +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - sharedContextProtoMethods.reportChanged = function reportChanged() { - this.visitor.reportChanged(); - }; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} - sharedContextProtoMethods.abort = function abort() { - this.needToCallTraverse = false; - this.visitor.abort(); - }; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - return PathVisitor; +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); }; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -},{"./node-path":18,"./types":23}],20:[function(require,module,exports){ -var Ap = Array.prototype; -var slice = Ap.slice; -var map = Ap.map; -var Op = Object.prototype; -var hasOwn = Op.hasOwnProperty; +function noop() {} -module.exports = function (fork) { - var types = fork.use(require("./types")); - var isArray = types.builtInTypes.array; - var isNumber = types.builtInTypes.number; +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - function Path(value, parentPath, name) { - if (!(this instanceof Path)) { - throw new Error("Path constructor cannot be invoked without 'new'"); - } +process.listeners = function (name) { return [] } - if (parentPath) { - if (!(parentPath instanceof Path)) { - throw new Error(""); - } - } else { - parentPath = null; - name = null; - } +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - // The value encapsulated by this Path, generally equal to - // parentPath.value[name] if we have a parentPath. - this.value = value; +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - // The immediate parent Path of this Path. - this.parentPath = parentPath; +},{}],16:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); - // The name of the property of parentPath.value through which this - // Path's value was reached. - this.name = name; +},{"./lib/_stream_duplex.js":17}],17:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - // Calling path.get("child") multiple times always returns the same - // child Path object, for both performance and consistency reasons. - this.__childCache = null; - } +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - var Pp = Path.prototype; +'use strict'; - function getChildCache(path) { - // Lazily create the child cache. This also cheapens cache - // invalidation, since you can just reset path.__childCache to null. - return path.__childCache || (path.__childCache = Object.create(null)); - } +/**/ - function getChildPath(path, name) { - var cache = getChildCache(path); - var actualChildValue = path.getValueProperty(name); - var childPath = cache[name]; - if (!hasOwn.call(cache, name) || - // Ensure consistency between cache and reality. - childPath.value !== actualChildValue) { - childPath = cache[name] = new path.constructor( - actualChildValue, path, name - ); - } - return childPath; - } +var processNextTick = require('process-nextick-args'); +/**/ -// This method is designed to be overridden by subclasses that need to -// handle missing properties, etc. - Pp.getValueProperty = function getValueProperty(name) { - return this.value[name]; - }; +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ - Pp.get = function get(name) { - var path = this; - var names = arguments; - var count = names.length; +module.exports = Duplex; - for (var i = 0; i < count; ++i) { - path = getChildPath(path, names[i]); - } +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - return path; - }; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); - Pp.each = function each(callback, context) { - var childPaths = []; - var len = this.value.length; - var i = 0; +util.inherits(Duplex, Readable); - // Collect all the original child paths before invoking the callback. - for (var i = 0; i < len; ++i) { - if (hasOwn.call(this.value, i)) { - childPaths[i] = this.get(i); - } - } +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} - // Invoke the callback on just the original child paths, regardless of - // any modifications made to the array by the callback. I chose these - // semantics over cleverly invoking the callback on new elements because - // this way is much easier to reason about. - context = context || this; - for (i = 0; i < len; ++i) { - if (hasOwn.call(childPaths, i)) { - callback.call(context, childPaths[i]); - } - } - }; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - Pp.map = function map(callback, context) { - var result = []; + Readable.call(this, options); + Writable.call(this, options); - this.each(function (childPath) { - result.push(callback.call(this, childPath)); - }, context); + if (options && options.readable === false) this.readable = false; - return result; - }; + if (options && options.writable === false) this.writable = false; - Pp.filter = function filter(callback, context) { - var result = []; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.each(function (childPath) { - if (callback.call(this, childPath)) { - result.push(childPath); - } - }, context); + this.once('end', onend); +} - return result; - }; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - function emptyMoves() {} - function getMoves(path, offset, start, end) { - isArray.assert(path.value); + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} - if (offset === 0) { - return emptyMoves; - } +function onEndNT(self) { + self.end(); +} - var length = path.value.length; - if (length < 1) { - return emptyMoves; - } +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } - var argc = arguments.length; - if (argc === 2) { - start = 0; - end = length; - } else if (argc === 3) { - start = Math.max(start, 0); - end = length; - } else { - start = Math.max(start, 0); - end = Math.min(end, length); - } + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); - isNumber.assert(start); - isNumber.assert(end); +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); - var moves = Object.create(null); - var cache = getChildCache(path); + processNextTick(cb, err); +}; - for (var i = start; i < end; ++i) { - if (hasOwn.call(path.value, i)) { - var childPath = path.get(i); - if (childPath.name !== i) { - throw new Error(""); - } - var newIndex = i + offset; - childPath.name = newIndex; - moves[newIndex] = childPath; - delete cache[i]; - } - } +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":19,"./_stream_writable":21,"core-util-is":6,"inherits":9,"process-nextick-args":14}],18:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - delete cache.length; +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - return function () { - for (var newIndex in moves) { - var childPath = moves[newIndex]; - if (childPath.name !== +newIndex) { - throw new Error(""); - } - cache[newIndex] = childPath; - path.value[newIndex] = childPath.value; - } - }; - } +'use strict'; - Pp.shift = function shift() { - var move = getMoves(this, -1); - var result = this.value.shift(); - move(); - return result; - }; +module.exports = PassThrough; - Pp.unshift = function unshift(node) { - var move = getMoves(this, arguments.length); - var result = this.value.unshift.apply(this.value, arguments); - move(); - return result; - }; +var Transform = require('./_stream_transform'); - Pp.push = function push(node) { - isArray.assert(this.value); - delete getChildCache(this).length - return this.value.push.apply(this.value, arguments); - }; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - Pp.pop = function pop() { - isArray.assert(this.value); - var cache = getChildCache(this); - delete cache[this.value.length - 1]; - delete cache.length; - return this.value.pop(); - }; +util.inherits(PassThrough, Transform); - Pp.insertAt = function insertAt(index, node) { - var argc = arguments.length; - var move = getMoves(this, argc - 1, index); - if (move === emptyMoves) { - return this; - } +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - index = Math.max(index, 0); + Transform.call(this, options); +} - for (var i = 1; i < argc; ++i) { - this.value[index + i - 1] = arguments[i]; - } - - move(); +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":20,"core-util-is":6,"inherits":9}],19:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - return this; - }; +'use strict'; - Pp.insertBefore = function insertBefore(node) { - var pp = this.parentPath; - var argc = arguments.length; - var insertAtArgs = [this.name]; - for (var i = 0; i < argc; ++i) { - insertAtArgs.push(arguments[i]); - } - return pp.insertAt.apply(pp, insertAtArgs); - }; +/**/ - Pp.insertAfter = function insertAfter(node) { - var pp = this.parentPath; - var argc = arguments.length; - var insertAtArgs = [this.name + 1]; - for (var i = 0; i < argc; ++i) { - insertAtArgs.push(arguments[i]); - } - return pp.insertAt.apply(pp, insertAtArgs); - }; +var processNextTick = require('process-nextick-args'); +/**/ - function repairRelationshipWithParent(path) { - if (!(path instanceof Path)) { - throw new Error(""); - } +module.exports = Readable; - var pp = path.parentPath; - if (!pp) { - // Orphan paths have no relationship to repair. - return path; - } +/**/ +var isArray = require('isarray'); +/**/ - var parentValue = pp.value; - var parentCache = getChildCache(pp); +/**/ +var Duplex; +/**/ - // Make sure parentCache[path.name] is populated. - if (parentValue[path.name] === path.value) { - parentCache[path.name] = path; - } else if (isArray.check(parentValue)) { - // Something caused path.name to become out of date, so attempt to - // recover by searching for path.value in parentValue. - var i = parentValue.indexOf(path.value); - if (i >= 0) { - parentCache[path.name = i] = path; - } - } else { - // If path.value disagrees with parentValue[path.name], and - // path.name is not an array index, let path.value become the new - // parentValue[path.name] and update parentCache accordingly. - parentValue[path.name] = path.value; - parentCache[path.name] = path; - } +Readable.ReadableState = ReadableState; - if (parentValue[path.name] !== path.value) { - throw new Error(""); - } - if (path.parentPath.get(path.name) !== path) { - throw new Error(""); - } +/**/ +var EE = require('events').EventEmitter; - return path; - } +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - Pp.replace = function replace(replacement) { - var results = []; - var parentValue = this.parentPath.value; - var parentCache = getChildCache(this.parentPath); - var count = arguments.length; +/**/ +var Stream = require('./internal/streams/stream'); +/**/ - repairRelationshipWithParent(this); +// TODO(bmeurer): Change this back to const once hole checks are +// properly optimized away early in Ignition+TurboFan. +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ - if (isArray.check(parentValue)) { - var originalLength = parentValue.length; - var move = getMoves(this.parentPath, count - 1, this.name + 1); +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - var spliceArgs = [this.name, 1]; - for (var i = 0; i < count; ++i) { - spliceArgs.push(arguments[i]); - } +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ - var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; - if (splicedOut[0] !== this.value) { - throw new Error(""); - } - if (parentValue.length !== (originalLength - 1 + count)) { - throw new Error(""); - } +util.inherits(Readable, Stream); - move(); +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - if (count === 0) { - delete this.value; - delete parentCache[this.name]; - this.__childCache = null; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} - } else { - if (parentValue[this.name] !== replacement) { - throw new Error(""); - } +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); - if (this.value !== replacement) { - this.value = replacement; - this.__childCache = null; - } + options = options || {}; - for (i = 0; i < count; ++i) { - results.push(this.parentPath.get(this.name + i)); - } + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; - if (results[0] !== this) { - throw new Error(""); - } - } + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - } else if (count === 1) { - if (this.value !== replacement) { - this.__childCache = null; - } - this.value = parentValue[this.name] = replacement; - results.push(this); + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - } else if (count === 0) { - delete parentValue[this.name]; - delete this.value; - this.__childCache = null; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - // Leave this path cached as parentCache[this.name], even though - // it no longer has a value defined. + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - } else { - throw new Error("Could not replace path"); - } + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; - return results; - }; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; - return Path; -}; + // has it been destroyed + this.destroyed = false; -},{"./types":23}],21:[function(require,module,exports){ -var hasOwn = Object.prototype.hasOwnProperty; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; -module.exports = function (fork) { - var types = fork.use(require("./types")); - var Type = types.Type; - var namedTypes = types.namedTypes; - var Node = namedTypes.Node; - var Expression = namedTypes.Expression; - var isArray = types.builtInTypes.array; - var b = types.builders; + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - function Scope(path, parentScope) { - if (!(this instanceof Scope)) { - throw new Error("Scope constructor cannot be invoked without 'new'"); - } - if (!(path instanceof fork.use(require("./node-path")))) { - throw new Error(""); - } - ScopeType.assert(path.value); + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - var depth; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} - if (parentScope) { - if (!(parentScope instanceof Scope)) { - throw new Error(""); - } - depth = parentScope.depth + 1; - } else { - parentScope = null; - depth = 0; - } +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); - Object.defineProperties(this, { - path: { value: path }, - node: { value: path.value }, - isGlobal: { value: !parentScope, enumerable: true }, - depth: { value: depth }, - parent: { value: parentScope }, - bindings: { value: {} }, - types: { value: {} }, - }); - } + if (!(this instanceof Readable)) return new Readable(options); - var scopeTypes = [ - // Program nodes introduce global scopes. - namedTypes.Program, + this._readableState = new ReadableState(options, this); - // Function is the supertype of FunctionExpression, - // FunctionDeclaration, ArrowExpression, etc. - namedTypes.Function, + // legacy + this.readable = true; - // In case you didn't know, the caught parameter shadows any variable - // of the same name in an outer scope. - namedTypes.CatchClause - ]; + if (options) { + if (typeof options.read === 'function') this._read = options.read; - var ScopeType = Type.or.apply(Type, scopeTypes); + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - Scope.isEstablishedBy = function(node) { - return ScopeType.check(node); - }; + Stream.call(this); +} - var Sp = Scope.prototype; +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -// Will be overridden after an instance lazily calls scanScope. - Sp.didScan = false; + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); - Sp.declares = function(name) { - this.scan(); - return hasOwn.call(this.bindings, name); - }; +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; - Sp.declaresType = function(name) { - this.scan(); - return hasOwn.call(this.types, name); - }; +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - Sp.declareTemporary = function(prefix) { - if (prefix) { - if (!/^[a-z$_]/i.test(prefix)) { - throw new Error(""); - } - } else { - prefix = "t$"; - } + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } - // Include this.depth in the name to make sure the name does not - // collide with any variables in nested/enclosing scopes. - prefix += this.depth.toString(36) + "$"; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; - this.scan(); +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - var index = 0; - while (this.declares(prefix + index)) { - ++index; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); } + } + } else if (!addToFront) { + state.reading = false; + } + } - var name = prefix + index; - return this.bindings[name] = types.builders.identifier(name); - }; + return needMoreData(state); +} - Sp.injectTemporary = function(identifier, init) { - identifier || (identifier = this.declareTemporary()); +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - var bodyPath = this.path.get("body"); - if (namedTypes.BlockStatement.check(bodyPath.value)) { - bodyPath = bodyPath.get("body"); - } + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} - bodyPath.unshift( - b.variableDeclaration( - "var", - [b.variableDeclarator(identifier, init || null)] - ) - ); +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} - return identifier; - }; +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} - Sp.scan = function(force) { - if (force || !this.didScan) { - for (var name in this.bindings) { - // Empty out this.bindings, just in cases. - delete this.bindings[name]; - } - scanScope(this.path, this.bindings, this.types); - this.didScan = true; - } - }; +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; - Sp.getBindings = function () { - this.scan(); - return this.bindings; - }; +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; - Sp.getTypes = function () { - this.scan(); - return this.types; - }; +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} - function scanScope(path, bindings, scopeTypes) { - var node = path.value; - ScopeType.assert(node); +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} - if (namedTypes.CatchClause.check(node)) { - // A catch clause establishes a new scope but the only variable - // bound in that scope is the catch parameter. Any other - // declarations create bindings in the outer scope. - addPattern(path.get("param"), bindings); +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - } else { - recursiveScanScope(path, bindings, scopeTypes); - } - } + if (n !== 0) state.emittedReadable = false; - function recursiveScanScope(path, bindings, scopeTypes) { - var node = path.value; + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } - if (path.parent && - namedTypes.FunctionExpression.check(path.parent.node) && - path.parent.node.id) { - addPattern(path.parent.get("id"), bindings); - } + n = howMuchToRead(n, state); - if (!node) { - // None of the remaining cases matter if node is falsy. + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } - } else if (isArray.check(node)) { - path.each(function(childPath) { - recursiveScanChild(childPath, bindings, scopeTypes); - }); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - } else if (namedTypes.Function.check(node)) { - path.get("params").each(function(paramPath) { - addPattern(paramPath, bindings); - }); + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - recursiveScanChild(path.get("body"), bindings, scopeTypes); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) { - addTypePattern(path.get("id"), scopeTypes); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - } else if (namedTypes.VariableDeclarator.check(node)) { - addPattern(path.get("id"), bindings); - recursiveScanChild(path.get("init"), bindings, scopeTypes); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - } else if (node.type === "ImportSpecifier" || - node.type === "ImportNamespaceSpecifier" || - node.type === "ImportDefaultSpecifier") { - addPattern( - // Esprima used to use the .name field to refer to the local - // binding identifier for ImportSpecifier nodes, but .id for - // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. - // ESTree/Acorn/ESpree use .local for all three node types. - path.get(node.local ? "local" : - node.name ? "name" : "id"), - bindings - ); + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } - } else if (Node.check(node) && !Expression.check(node)) { - types.eachField(node, function(name, child) { - var childPath = path.get(name); - if (!pathHasValue(childPath, child)) { - throw new Error(""); - } - recursiveScanChild(childPath, bindings, scopeTypes); - }); - } - } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - function pathHasValue(path, value) { - if (path.value === value) { - return true; - } + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } - // Empty arrays are probably produced by defaults.emptyArray, in which - // case is makes sense to regard them as equivalent, if not ===. - if (Array.isArray(path.value) && - path.value.length === 0 && - Array.isArray(value) && - value.length === 0) { - return true; - } + if (ret !== null) this.emit('data', ret); - return false; + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; } + } + state.ended = true; - function recursiveScanChild(path, bindings, scopeTypes) { - var node = path.value; + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} - if (!node || Expression.check(node)) { - // Ignore falsy values and Expressions. +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} - } else if (namedTypes.FunctionDeclaration.check(node) && - node.id !== null) { - addPattern(path.get("id"), bindings); +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} - } else if (namedTypes.ClassDeclaration && - namedTypes.ClassDeclaration.check(node)) { - addPattern(path.get("id"), bindings); +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} - } else if (ScopeType.check(node)) { - if (namedTypes.CatchClause.check(node)) { - var catchParamName = node.param.name; - var hadBinding = hasOwn.call(bindings, catchParamName); +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} - // Any declarations that occur inside the catch body that do - // not have the same name as the catch parameter should count - // as bindings in the outer scope. - recursiveScanScope(path.get("body"), bindings, scopeTypes); +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; - // If a new binding matching the catch parameter name was - // created while scanning the catch body, ignore it because it - // actually refers to the catch parameter and not the outer - // scope that we're currently scanning. - if (!hadBinding) { - delete bindings[catchParamName]; - } - } +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - } else { - recursiveScanScope(path, bindings, scopeTypes); - } + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } + } - function addPattern(patternPath, bindings) { - var pattern = patternPath.value; - namedTypes.Pattern.assert(pattern); + function onend() { + debug('onend'); + dest.end(); + } - if (namedTypes.Identifier.check(pattern)) { - if (hasOwn.call(bindings, pattern.name)) { - bindings[pattern.name].push(patternPath); - } else { - bindings[pattern.name] = [patternPath]; - } + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - } else if (namedTypes.ObjectPattern && - namedTypes.ObjectPattern.check(pattern)) { - patternPath.get('properties').each(function(propertyPath) { - var property = propertyPath.value; - if (namedTypes.Pattern.check(property)) { - addPattern(propertyPath, bindings); - } else if (namedTypes.Property.check(property)) { - addPattern(propertyPath.get('value'), bindings); - } else if (namedTypes.SpreadProperty && - namedTypes.SpreadProperty.check(property)) { - addPattern(propertyPath.get('argument'), bindings); - } - }); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); - } else if (namedTypes.ArrayPattern && - namedTypes.ArrayPattern.check(pattern)) { - patternPath.get('elements').each(function(elementPath) { - var element = elementPath.value; - if (namedTypes.Pattern.check(element)) { - addPattern(elementPath, bindings); - } else if (namedTypes.SpreadElement && - namedTypes.SpreadElement.check(element)) { - addPattern(elementPath.get("argument"), bindings); - } - }); + cleanedUp = true; - } else if (namedTypes.PropertyPattern && - namedTypes.PropertyPattern.check(pattern)) { - addPattern(patternPath.get('pattern'), bindings); + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - } else if ((namedTypes.SpreadElementPattern && - namedTypes.SpreadElementPattern.check(pattern)) || - (namedTypes.SpreadPropertyPattern && - namedTypes.SpreadPropertyPattern.check(pattern))) { - addPattern(patternPath.get('argument'), bindings); - } + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); } + } - function addTypePattern(patternPath, types) { - var pattern = patternPath.value; - namedTypes.Pattern.assert(pattern); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - if (namedTypes.Identifier.check(pattern)) { - if (hasOwn.call(types, pattern.name)) { - types[pattern.name].push(patternPath); - } else { - types[pattern.name] = [patternPath]; - } + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - } - } + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - Sp.lookup = function(name) { - for (var scope = this; scope; scope = scope.parent) - if (scope.declares(name)) - break; - return scope; - }; + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - Sp.lookupType = function(name) { - for (var scope = this; scope; scope = scope.parent) - if (scope.declaresType(name)) - break; - return scope; - }; + // tell the dest that it's being piped to + dest.emit('pipe', src); - Sp.getGlobalScope = function() { - var scope = this; - while (!scope.isGlobal) - scope = scope.parent; - return scope; - }; + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - return Scope; + return dest; }; -},{"./node-path":18,"./types":23}],22:[function(require,module,exports){ -module.exports = function (fork) { - var exports = {}; - var types = fork.use(require("../lib/types")); - var Type = types.Type; - var builtin = types.builtInTypes; - var isNumber = builtin.number; - - // An example of constructing a new type with arbitrary constraints from - // an existing type. - exports.geq = function (than) { - return new Type(function (value) { - return isNumber.check(value) && value >= than; - }, isNumber + " >= " + than); - }; +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} - // Default value-returning functions that may optionally be passed as a - // third argument to Def.prototype.field. - exports.defaults = { - // Functions were used because (among other reasons) that's the most - // elegant way to allow for the emptyArray one always to give a new - // array instance. - "null": function () { return null }, - "emptyArray": function () { return [] }, - "false": function () { return false }, - "true": function () { return true }, - "undefined": function () {} - }; +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - var naiveIsPrimitive = Type.or( - builtin.string, - builtin.number, - builtin.boolean, - builtin.null, - builtin.undefined - ); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - exports.isPrimitive = new Type(function (value) { - if (value === null) - return true; - var type = typeof value; - return !(type === "object" || - type === "function"); - }, naiveIsPrimitive.toString()); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - return exports; -}; -},{"../lib/types":23}],23:[function(require,module,exports){ -var Ap = Array.prototype; -var slice = Ap.slice; -var map = Ap.map; -var each = Ap.forEach; -var Op = Object.prototype; -var objToStr = Op.toString; -var funObjStr = objToStr.call(function(){}); -var strObjStr = objToStr.call(""); -var hasOwn = Op.hasOwnProperty; + if (!dest) dest = state.pipes; -module.exports = function () { + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } - var exports = {}; + // slow case. multiple pipe destinations. - // A type is an object with a .check method that takes a value and returns - // true or false according to whether the value matches the type. + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; - function Type(check, name) { - var self = this; - if (!(self instanceof Type)) { - throw new Error("Type constructor cannot be invoked without 'new'"); - } + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } - // Unfortunately we can't elegantly reuse isFunction and isString, - // here, because this code is executed while defining those types. - if (objToStr.call(check) !== funObjStr) { - throw new Error(check + " is not a function"); - } + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; - // The `name` parameter can be either a function or a string. - var nameObjStr = objToStr.call(name); - if (!(nameObjStr === funObjStr || - nameObjStr === strObjStr)) { - throw new Error(name + " is neither a function nor a string"); - } + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - Object.defineProperties(self, { - name: {value: name}, - check: { - value: function (value, deep) { - var result = check.call(self, value, deep); - if (!result && deep && objToStr.call(deep) === funObjStr) - deep(self, value); - return result; - } - } - }); - } + dest.emit('unpipe', this, unpipeInfo); - var Tp = Type.prototype; + return this; +}; - // Throughout this file we use Object.defineProperty to prevent - // redefinition of exported properties. - exports.Type = Type; +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); - // Like .check, except that failure triggers an AssertionError. - Tp.assert = function (value, deep) { - if (!this.check(value, deep)) { - var str = shallowStringify(value); - throw new Error(str + " does not match type " + this); - } - return true; - }; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } - function shallowStringify(value) { - if (isObject.check(value)) - return "{" + Object.keys(value).map(function (key) { - return key + ": " + value[key]; - }).join(", ") + "}"; + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; - if (isArray.check(value)) - return "[" + value.map(shallowStringify).join(", ") + "]"; +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} - return JSON.stringify(value); - } +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; - Tp.toString = function () { - var name = this.name; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} - if (isString.check(name)) - return name; +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } - if (isFunction.check(name)) - return name.call(this) + ""; + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} - return name + " type"; - }; +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; - var builtInCtorFns = []; - var builtInCtorTypes = []; - var builtInTypes = {}; - exports.builtInTypes = builtInTypes; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} - function defBuiltInType(example, name) { - var objStr = objToStr.call(example); +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - var type = new Type(function (value) { - return objToStr.call(value) === objStr; - }, name); + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - builtInTypes[name] = type; + self.push(null); + }); - if (example && typeof example.constructor === "function") { - builtInCtorFns.push(example.constructor); - builtInCtorTypes.push(type); - } + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - return type; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } + }); - // These types check the underlying [[Class]] attribute of the given - // value, rather than using the problematic typeof operator. Note however - // that no subtyping is considered; so, for instance, isObject.check - // returns false for [], /./, new Date, and null. - var isString = defBuiltInType("truthy", "string"); - var isFunction = defBuiltInType(function () {}, "function"); - var isArray = defBuiltInType([], "array"); - var isObject = defBuiltInType({}, "object"); - var isRegExp = defBuiltInType(/./, "RegExp"); - var isDate = defBuiltInType(new Date, "Date"); - var isNumber = defBuiltInType(3, "number"); - var isBoolean = defBuiltInType(true, "boolean"); - var isNull = defBuiltInType(null, "null"); - var isUndefined = defBuiltInType(void 0, "undefined"); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } - // There are a number of idiomatic ways of expressing types, so this - // function serves to coerce them all to actual Type objects. Note that - // providing the name argument is not necessary in most cases. - function toType(from, name) { - // The toType function should of course be idempotent. - if (from instanceof Type) - return from; + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } - // The Def type is used as a helper for constructing compound - // interface types for AST nodes. - if (from instanceof Def) - return from.type; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - // Support [ElemType] syntax. - if (isArray.check(from)) - return Type.fromArray(from); + return self; +}; - // Support { someField: FieldType, ... } syntax. - if (isObject.check(from)) - return Type.fromObject(from); +// exposed for testing purposes only. +Readable._fromList = fromList; - if (isFunction.check(from)) { - var bicfIndex = builtInCtorFns.indexOf(from); - if (bicfIndex >= 0) { - return builtInCtorTypes[bicfIndex]; - } +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; - // If isFunction.check(from), and from is not a built-in - // constructor, assume from is a binary predicate function we can - // use to define the type. - return new Type(from, name); - } + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } - // As a last resort, toType returns a type that matches any value that - // is === from. This is primarily useful for literal values like - // toType(null), but it has the additional advantage of allowing - // toType to be a total function. - return new Type(function (value) { - return value === from; - }, isUndefined.check(name) ? function () { - return from + ""; - } : name); - } + return ret; +} - // Returns a type that matches the given value iff any of type1, type2, - // etc. match the value. - Type.or = function (/* type1, type2, ... */) { - var types = []; - var len = arguments.length; - for (var i = 0; i < len; ++i) - types.push(toType(arguments[i])); +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} - return new Type(function (value, deep) { - for (var i = 0; i < len; ++i) - if (types[i].check(value, deep)) - return true; - return false; - }, function () { - return types.join(" | "); - }); - }; +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - Type.fromArray = function (arr) { - if (!isArray.check(arr)) { - throw new Error(""); - } - if (arr.length !== 1) { - throw new Error("only one element type is permitted for typed arrays"); - } - return toType(arr[0]).arrayOf(); - }; +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - Tp.arrayOf = function () { - var elemType = this; - return new Type(function (value, deep) { - return isArray.check(value) && value.every(function (elem) { - return elemType.check(elem, deep); - }); - }, function () { - return "[" + elemType + "]"; - }); - }; +function endReadable(stream) { + var state = stream._readableState; - Type.fromObject = function (obj) { - var fields = Object.keys(obj).map(function (name) { - return new Field(name, obj[name]); - }); + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - return new Type(function (value, deep) { - return isObject.check(value) && fields.every(function (field) { - return field.type.check(value[field.name], deep); - }); - }, function () { - return "{ " + fields.join(", ") + " }"; - }); - }; + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} - function Field(name, type, defaultFn, hidden) { - var self = this; +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - if (!(self instanceof Field)) { - throw new Error("Field constructor cannot be invoked without 'new'"); - } - isString.assert(name); +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} - type = toType(type); +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":17,"./internal/streams/BufferList":22,"./internal/streams/destroy":23,"./internal/streams/stream":24,"_process":15,"core-util-is":6,"events":7,"inherits":9,"isarray":11,"process-nextick-args":14,"safe-buffer":29,"string_decoder/":31,"util":4}],20:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - var properties = { - name: {value: name}, - type: {value: type}, - hidden: {value: !!hidden} - }; +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - if (isFunction.check(defaultFn)) { - properties.defaultFn = {value: defaultFn}; - } +'use strict'; - Object.defineProperties(self, properties); - } +module.exports = Transform; - var Fp = Field.prototype; +var Duplex = require('./_stream_duplex'); - Fp.toString = function () { - return JSON.stringify(this.name) + ": " + this.type; - }; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - Fp.getValue = function (obj) { - var value = obj[this.name]; +util.inherits(Transform, Duplex); - if (!isUndefined.check(value)) - return value; +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; - if (this.defaultFn) - value = this.defaultFn.call(obj); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} - return value; - }; +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - // Define a type whose name is registered in a namespace (the defCache) so - // that future definitions will return the same type given the same name. - // In particular, this system allows for circular and forward definitions. - // The Def object d returned from Type.def may be used to configure the - // type d.type by calling methods such as d.bases, d.build, and d.field. - Type.def = function (typeName) { - isString.assert(typeName); - return hasOwn.call(defCache, typeName) - ? defCache[typeName] - : defCache[typeName] = new Def(typeName); - }; + var cb = ts.writecb; - // In order to return the same Def instance every time Type.def is called - // with a particular name, those instances need to be stored in a cache. - var defCache = Object.create(null); + if (!cb) { + return stream.emit('error', new Error('write callback called multiple times')); + } - function Def(typeName) { - var self = this; - if (!(self instanceof Def)) { - throw new Error("Def constructor cannot be invoked without 'new'"); - } + ts.writechunk = null; + ts.writecb = null; - Object.defineProperties(self, { - typeName: {value: typeName}, - baseNames: {value: []}, - ownFields: {value: Object.create(null)}, + if (data !== null && data !== undefined) stream.push(data); - // These two are populated during finalization. - allSupertypes: {value: Object.create(null)}, // Includes own typeName. - supertypeList: {value: []}, // Linear inheritance hierarchy. - allFields: {value: Object.create(null)}, // Includes inherited fields. - fieldNames: {value: []}, // Non-hidden keys of allFields. + cb(er); - type: { - value: new Type(function (value, deep) { - return self.check(value, deep); - }, typeName) - } - }); - } + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} - Def.fromValue = function (value) { - if (value && typeof value === "object") { - var type = value.type; - if (typeof type === "string" && - hasOwn.call(defCache, type)) { - var d = defCache[type]; - if (d.finalized) { - return d; - } - } - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - return null; - }; + Duplex.call(this, options); - var Dp = Def.prototype; + this._transformState = new TransformState(this); - Dp.isSupertypeOf = function (that) { - if (that instanceof Def) { - if (this.finalized !== true || - that.finalized !== true) { - throw new Error(""); - } - return hasOwn.call(that.allSupertypes, this.typeName); - } else { - throw new Error(that + " is not a Def"); - } - }; + var stream = this; - // Note that the list returned by this function is a copy of the internal - // supertypeList, *without* the typeName itself as the first element. - exports.getSupertypeNames = function (typeName) { - if (!hasOwn.call(defCache, typeName)) { - throw new Error(""); - } - var d = defCache[typeName]; - if (d.finalized !== true) { - throw new Error(""); - } - return d.supertypeList.slice(1); - }; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - // Returns an object mapping from every known type in the defCache to the - // most specific supertype whose name is an own property of the candidates - // object. - exports.computeSupertypeLookupTable = function (candidates) { - var table = {}; - var typeNames = Object.keys(defCache); - var typeNameCount = typeNames.length; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - for (var i = 0; i < typeNameCount; ++i) { - var typeName = typeNames[i]; - var d = defCache[typeName]; - if (d.finalized !== true) { - throw new Error("" + typeName); - } - for (var j = 0; j < d.supertypeList.length; ++j) { - var superTypeName = d.supertypeList[j]; - if (hasOwn.call(candidates, superTypeName)) { - table[typeName] = superTypeName; - break; - } - } - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - return table; - }; + if (typeof options.flush === 'function') this._flush = options.flush; + } - Dp.checkAllFields = function (value, deep) { - var allFields = this.allFields; - if (this.finalized !== true) { - throw new Error("" + this.typeName); - } + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); +} - function checkFieldByName(name) { - var field = allFields[name]; - var type = field.type; - var child = field.getValue(value); - return type.check(child, deep); - } +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - return isObject.check(value) - && Object.keys(allFields).every(checkFieldByName); - }; +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; - Dp.check = function (value, deep) { - if (this.finalized !== true) { - throw new Error( - "prematurely checking unfinalized type " + this.typeName - ); - } +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - // A Def type can only match an object value. - if (!isObject.check(value)) - return false; +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - var vDef = Def.fromValue(value); - if (!vDef) { - // If we couldn't infer the Def associated with the given value, - // and we expected it to be a SourceLocation or a Position, it was - // probably just missing a "type" field (because Esprima does not - // assign a type property to such nodes). Be optimistic and let - // this.checkAllFields make the final decision. - if (this.typeName === "SourceLocation" || - this.typeName === "Position") { - return this.checkAllFields(value, deep); - } + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; - // Calling this.checkAllFields for any other type of node is both - // bad for performance and way too forgiving. - return false; - } +Transform.prototype._destroy = function (err, cb) { + var _this = this; - // If checking deeply and vDef === this, then we only need to call - // checkAllFields once. Calling checkAllFields is too strict when deep - // is false, because then we only care about this.isSupertypeOf(vDef). - if (deep && vDef === this) - return this.checkAllFields(value, deep); + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this.emit('close'); + }); +}; - // In most cases we rely exclusively on isSupertypeOf to make O(1) - // subtyping determinations. This suffices in most situations outside - // of unit tests, since interface conformance is checked whenever new - // instances are created using builder functions. - if (!this.isSupertypeOf(vDef)) - return false; +function done(stream, er, data) { + if (er) return stream.emit('error', er); - // The exception is when deep is true; then, we recursively check all - // fields. - if (!deep) - return true; + if (data !== null && data !== undefined) stream.push(data); - // Use the more specific Def (vDef) to perform the deep check, but - // shallow-check fields defined by the less specific Def (this). - return vDef.checkAllFields(value, deep) - && this.checkAllFields(value, false); - }; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - Dp.bases = function () { - var args = slice.call(arguments); - var bases = this.baseNames; + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - if (this.finalized) { - if (args.length !== bases.length) { - throw new Error(""); - } - for (var i = 0; i < args.length; i++) { - if (args[i] !== bases[i]) { - throw new Error(""); - } - } - return this; - } + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - args.forEach(function (baseName) { - isString.assert(baseName); + return stream.push(null); +} +},{"./_stream_duplex":17,"core-util-is":6,"inherits":9}],21:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - // This indexOf lookup may be O(n), but the typical number of base - // names is very small, and indexOf is a native Array method. - if (bases.indexOf(baseName) < 0) - bases.push(baseName); - }); +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - return this; // For chaining. - }; +'use strict'; - // False by default until .build(...) is called on an instance. - Object.defineProperty(Dp, "buildable", {value: false}); +/**/ - var builders = {}; - exports.builders = builders; +var processNextTick = require('process-nextick-args'); +/**/ - // This object is used as prototype for any node created by a builder. - var nodePrototype = {}; +module.exports = Writable; - // Call this function to define a new method to be shared by all AST - // nodes. The replaced method (if any) is returned for easy wrapping. - exports.defineMethod = function (name, func) { - var old = nodePrototype[name]; +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - // Pass undefined as func to delete nodePrototype[name]. - if (isUndefined.check(func)) { - delete nodePrototype[name]; +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - } else { - isFunction.assert(func); + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - Object.defineProperty(nodePrototype, name, { - enumerable: true, // For discoverability. - configurable: true, // For delete proto[name]. - value: func - }); - } +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ - return old; - }; +/**/ +var Duplex; +/**/ - var isArrayOfString = isString.arrayOf(); +Writable.WritableState = WritableState; - // Calling the .build method of a Def simultaneously marks the type as - // buildable (by defining builders[getBuilderName(typeName)]) and - // specifies the order of arguments that should be passed to the builder - // function to create an instance of the type. - Dp.build = function (/* param1, param2, ... */) { - var self = this; +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ - var newBuildParams = slice.call(arguments); - isArrayOfString.assert(newBuildParams); +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ - // Calling Def.prototype.build multiple times has the effect of merely - // redefining this property. - Object.defineProperty(self, "buildParams", { - value: newBuildParams, - writable: false, - enumerable: false, - configurable: true - }); +/**/ +var Stream = require('./internal/streams/stream'); +/**/ - if (self.buildable) { - // If this Def is already buildable, update self.buildParams and - // continue using the old builder function. - return self; - } +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ - // Every buildable type will have its "type" field filled in - // automatically. This includes types that are not subtypes of Node, - // like SourceLocation, but that seems harmless (TODO?). - self.field("type", String, function () { return self.typeName }); +var destroyImpl = require('./internal/streams/destroy'); - // Override Dp.buildable for this Def instance. - Object.defineProperty(self, "buildable", {value: true}); +util.inherits(Writable, Stream); - Object.defineProperty(builders, getBuilderName(self.typeName), { - enumerable: true, +function nop() {} - value: function () { - var args = arguments; - var argc = args.length; - var built = Object.create(nodePrototype); +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); - if (!self.finalized) { - throw new Error( - "attempting to instantiate unfinalized type " + - self.typeName - ); - } + options = options || {}; - function add(param, i) { - if (hasOwn.call(built, param)) - return; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - var all = self.allFields; - if (!hasOwn.call(all, param)) { - throw new Error("" + param); - } + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - var field = all[param]; - var type = field.type; - var value; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - if (isNumber.check(i) && i < argc) { - value = args[i]; - } else if (field.defaultFn) { - // Expose the partially-built object to the default - // function as its `this` object. - value = field.defaultFn.call(built); - } else { - var message = "no value or default function given for field " + - JSON.stringify(param) + " of " + self.typeName + "(" + - self.buildParams.map(function (name) { - return all[name]; - }).join(", ") + ")"; - throw new Error(message); - } + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - if (!type.check(value)) { - throw new Error( - shallowStringify(value) + - " does not match field " + field + - " of type " + self.typeName - ); - } + // if _final has been called + this.finalCalled = false; - // TODO Could attach getters and setters here to enforce - // dynamic type safety. - built[param] = value; - } + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - self.buildParams.forEach(function (param, i) { - add(param, i); - }); + // has it been destroyed + this.destroyed = false; - Object.keys(self.allFields).forEach(function (param) { - add(param); // Use the default value. - }); + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // Make sure that the "type" field was filled automatically. - if (built.type !== self.typeName) { - throw new Error(""); - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - return built; - } - }); + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - return self; // For chaining. - }; + // a flag to see when we're in the middle of a write. + this.writing = false; - function getBuilderName(typeName) { - return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) { - var len = upperCasePrefix.length; - switch (len) { - case 0: return ""; - // If there's only one initial capital letter, just lower-case it. - case 1: return upperCasePrefix.toLowerCase(); - default: - // If there's more than one initial capital letter, lower-case - // all but the last one, so that XMLDefaultDeclaration (for - // example) becomes xmlDefaultDeclaration. - return upperCasePrefix.slice( - 0, len - 1).toLowerCase() + - upperCasePrefix.charAt(len - 1); - } - }); - } - exports.getBuilderName = getBuilderName; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - function getStatementBuilderName(typeName) { - typeName = getBuilderName(typeName); - return typeName.replace(/(Expression)?$/, "Statement"); - } - exports.getStatementBuilderName = getStatementBuilderName; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - // The reason fields are specified using .field(...) instead of an object - // literal syntax is somewhat subtle: the object literal syntax would - // support only one key and one value, but with .field(...) we can pass - // any number of arguments to specify the field. - Dp.field = function (name, type, defaultFn, hidden) { - if (this.finalized) { - console.error("Ignoring attempt to redefine field " + - JSON.stringify(name) + " of finalized type " + - JSON.stringify(this.typeName)); - return this; - } - this.ownFields[name] = new Field(name, type, defaultFn, hidden); - return this; // For chaining. - }; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var namedTypes = {}; - exports.namedTypes = namedTypes; - - // Like Object.keys, but aware of what fields each AST type should have. - function getFieldNames(object) { - var d = Def.fromValue(object); - if (d) { - return d.fieldNames.slice(0); - } + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - if ("type" in object) { - throw new Error( - "did not recognize object of type " + - JSON.stringify(object.type) - ); - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - return Object.keys(object); - } - exports.getFieldNames = getFieldNames; + // the amount that is being written when _write is called. + this.writelen = 0; - // Get the value of an object property, taking object.type and default - // functions into account. - function getFieldValue(object, fieldName) { - var d = Def.fromValue(object); - if (d) { - var field = d.allFields[fieldName]; - if (field) { - return field.getValue(object); - } - } + this.bufferedRequest = null; + this.lastBufferedRequest = null; - return object && object[fieldName]; - } - exports.getFieldValue = getFieldValue; + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - // Iterate over all defined fields of an object, including those missing - // or undefined, passing each field name and effective value (as returned - // by getFieldValue) to the callback. If the object has no corresponding - // Def, the callback will never be called. - exports.eachField = function (object, callback, context) { - getFieldNames(object).forEach(function (name) { - callback.call(this, name, getFieldValue(object, name)); - }, context); - }; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - // Similar to eachField, except that iteration stops as soon as the - // callback returns a truthy value. Like Array.prototype.some, the final - // result is either true or false to indicates whether the callback - // returned true for any element or not. - exports.someField = function (object, callback, context) { - return getFieldNames(object).some(function (name) { - return callback.call(this, name, getFieldValue(object, name)); - }, context); - }; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - // This property will be overridden as true by individual Def instances - // when they are finalized. - Object.defineProperty(Dp, "finalized", {value: false}); + // count buffered requests + this.bufferedRequestCount = 0; - Dp.finalize = function () { - var self = this; + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} - // It's not an error to finalize a type more than once, but only the - // first call to .finalize does anything. - if (!self.finalized) { - var allFields = self.allFields; - var allSupertypes = self.allSupertypes; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; - self.baseNames.forEach(function (name) { - var def = defCache[name]; - if (def instanceof Def) { - def.finalize(); - extend(allFields, def.allFields); - extend(allSupertypes, def.allSupertypes); - } else { - var message = "unknown supertype name " + - JSON.stringify(name) + - " for subtype " + - JSON.stringify(self.typeName); - throw new Error(message); - } - }); +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - // TODO Warn if fields are overridden with incompatible types. - extend(allFields, self.ownFields); - allSupertypes[self.typeName] = self; +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; - self.fieldNames.length = 0; - for (var fieldName in allFields) { - if (hasOwn.call(allFields, fieldName) && - !allFields[fieldName].hidden) { - self.fieldNames.push(fieldName); - } - } + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} - // Types are exported only once they have been finalized. - Object.defineProperty(namedTypes, self.typeName, { - enumerable: true, - value: self.type - }); +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); - Object.defineProperty(self, "finalized", {value: true}); + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. - // A linearization of the inheritance hierarchy. - populateSupertypeList(self.typeName, self.supertypeList); + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } - if (self.buildable && self.supertypeList.lastIndexOf("Expression") >= 0) { - wrapExpressionBuilderWithStatement(self.typeName); - } - } - }; + this._writableState = new WritableState(options, this); - // Adds an additional builder for Expression subtypes - // that wraps the built Expression in an ExpressionStatements. - function wrapExpressionBuilderWithStatement(typeName) { - var wrapperName = getStatementBuilderName(typeName); + // legacy. + this.writable = true; - // skip if the builder already exists - if (builders[wrapperName]) return; + if (options) { + if (typeof options.write === 'function') this._write = options.write; - // the builder function to wrap with builders.ExpressionStatement - var wrapped = builders[getBuilderName(typeName)]; + if (typeof options.writev === 'function') this._writev = options.writev; - // skip if there is nothing to wrap - if (!wrapped) return; + if (typeof options.destroy === 'function') this._destroy = options.destroy; - builders[wrapperName] = function () { - return builders.expressionStatement(wrapped.apply(builders, arguments)); - }; - } + if (typeof options.final === 'function') this._final = options.final; + } - function populateSupertypeList(typeName, list) { - list.length = 0; - list.push(typeName); + Stream.call(this); +} - var lastSeen = Object.create(null); +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; - for (var pos = 0; pos < list.length; ++pos) { - typeName = list[pos]; - var d = defCache[typeName]; - if (d.finalized !== true) { - throw new Error(""); - } +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} - // If we saw typeName earlier in the breadth-first traversal, - // delete the last-seen occurrence. - if (hasOwn.call(lastSeen, typeName)) { - delete list[lastSeen[typeName]]; - } +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; - // Record the new index of the last-seen occurrence of typeName. - lastSeen[typeName] = pos; + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} - // Enqueue the base names of this type. - list.push.apply(list, d.baseNames); - } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = _isUint8Array(chunk) && !state.objectMode; - // Compaction loop to remove array holes. - for (var to = 0, from = to, len = list.length; from < len; ++from) { - if (hasOwn.call(list, from)) { - list[to++] = list[from]; - } - } + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } - list.length = to; - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - function extend(into, from) { - Object.keys(from).forEach(function (name) { - into[name] = from[name]; - }); + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - return into; - }; + if (typeof cb !== 'function') cb = nop; - exports.finalize = function () { - Object.keys(defCache).forEach(function (name) { - defCache[name].finalize(); - }); - }; + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } - return exports; + return ret; }; -},{}],24:[function(require,module,exports){ -module.exports = require('./fork')([ - // This core module of AST types captures ES5 as it is parsed today by - // git://github.com/ariya/esprima.git#master. - require("./def/core"), - - // Feel free to add to or remove from this list of extension modules to - // configure the precise type hierarchy that you need. - require("./def/es6"), - require("./def/es7"), - require("./def/mozilla"), - require("./def/e4x"), - require("./def/jsx"), - require("./def/flow"), - require("./def/esprima"), - require("./def/babel"), - require("./def/babel6") -]); - -},{"./def/babel":6,"./def/babel6":7,"./def/core":8,"./def/e4x":9,"./def/es6":10,"./def/es7":11,"./def/esprima":12,"./def/flow":13,"./def/jsx":14,"./def/mozilla":15,"./fork":16}],25:[function(require,module,exports){ -"use strict"; +Writable.prototype.cork = function () { + var state = this._writableState; -exports.__esModule = true; + state.corked++; +}; -exports.default = function (rawLines, lineNumber, colNumber) { - var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; +Writable.prototype.uncork = function () { + var state = this._writableState; - colNumber = Math.max(colNumber, 0); + if (state.corked) { + state.corked--; - var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor; - var chalk = _chalk2.default; - if (opts.forceColor) { - chalk = new _chalk2.default.constructor({ enabled: true }); + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } - var maybeHighlight = function maybeHighlight(chalkFn, string) { - return highlighted ? chalkFn(string) : string; - }; - var defs = getDefs(chalk); - if (highlighted) rawLines = highlight(defs, rawLines); +}; - var linesAbove = opts.linesAbove || 2; - var linesBelow = opts.linesBelow || 3; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; - var lines = rawLines.split(NEWLINE); - var start = Math.max(lineNumber - (linesAbove + 1), 0); - var end = Math.min(lines.length, lineNumber + linesBelow); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} - if (!lineNumber && !colNumber) { - start = 0; - end = lines.length; +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } } + var len = state.objectMode ? 1 : chunk.length; - var numberMaxWidth = String(end).length; + state.length += len; - var frame = lines.slice(start, end).map(function (line, index) { - var number = start + 1 + index; - var paddedNumber = (" " + number).slice(-numberMaxWidth); - var gutter = " " + paddedNumber + " | "; - if (number === lineNumber) { - var markerLine = ""; - if (colNumber) { - var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); - } - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; } else { - return " " + maybeHighlight(defs.gutter, gutter) + line; + state.bufferedRequest = state.lastBufferedRequest; } - }).join("\n"); - - if (highlighted) { - return chalk.reset(frame); + state.bufferedRequestCount += 1; } else { - return frame; + doWrite(stream, state, false, len, chunk, encoding, cb); } -}; -var _jsTokens = require("js-tokens"); + return ret; +} -var _jsTokens2 = _interopRequireDefault(_jsTokens); +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -var _esutils = require("esutils"); +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; -var _esutils2 = _interopRequireDefault(_esutils); + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + processNextTick(cb, er); + // this can emit finish, and it will always happen + // after error + processNextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} -var _chalk = require("chalk"); +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -var _chalk2 = _interopRequireDefault(_chalk); +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + onwriteStateUpdate(state); -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold, - gutter: chalk.grey, - marker: chalk.red.bold - }; -} + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } -var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} -var JSX_TAG = /^[a-z][\w-]*$/i; +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} -var BRACKET = /^[()\[\]{}]$/; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} -function getTokenType(match) { - var _match$slice = match.slice(-2), - offset = _match$slice[0], - text = _match$slice[1]; +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - var token = (0, _jsTokens.matchToToken)(match); + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - if (token.type === "name") { - if (_esutils2.default.keyword.isReservedWordES6(token.value)) { - return "keyword"; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } + buffer.allBuffers = allBuffers; - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "*/ -var _util = require("../util"); +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var util = _interopRequireWildcard(_util); +var Buffer = require('safe-buffer').Buffer; +/**/ -var _babelMessages = require("babel-messages"); +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} -var messages = _interopRequireWildcard(_babelMessages); +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); -var _babelTypes = require("babel-types"); + this.head = null; + this.tail = null; + this.length = 0; + } -var t = _interopRequireWildcard(_babelTypes); + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; -var _babelTraverse = require("babel-traverse"); + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; -var _optionManager = require("../transformation/file/options/option-manager"); + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; -var _optionManager2 = _interopRequireDefault(_optionManager); + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; -var _pipeline = require("../transformation/pipeline"); + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; -var _pipeline2 = _interopRequireDefault(_pipeline); + return BufferList; +}(); +},{"safe-buffer":29}],23:[function(require,module,exports){ +'use strict'; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +/**/ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var processNextTick = require('process-nextick-args'); +/**/ -exports.util = util; -exports.messages = messages; -exports.types = t; -exports.traverse = _babelTraverse2.default; -exports.OptionManager = _optionManager2.default; -function Plugin(alias) { - throw new Error("The (" + alias + ") Babel 5 plugin is being run with Babel 6."); -} +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; -exports.Pipeline = _pipeline2.default; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + processNextTick(emitErrorNT, this, err); + } + return; + } -var pipeline = new _pipeline2.default(); -var analyse = exports.analyse = pipeline.analyse.bind(pipeline); -var transform = exports.transform = pipeline.transform.bind(pipeline); -var transformFromAst = exports.transformFromAst = pipeline.transformFromAst.bind(pipeline); + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks -function transformFile(filename, opts, callback) { - if (typeof opts === "function") { - callback = opts; - opts = {}; + if (this._readableState) { + this._readableState.destroyed = true; } - opts.filename = filename; - - _fs2.default.readFile(filename, function (err, code) { - var result = void 0; + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } - if (!err) { - try { - result = transform(code, opts); - } catch (_err) { - err = _err; + this._destroy(err || null, function (err) { + if (!cb && err) { + processNextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; } - } - - if (err) { - callback(err); - } else { - callback(null, result); + } else if (cb) { + cb(err); } }); } -function transformFileSync(filename) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - opts.filename = filename; - return transform(_fs2.default.readFileSync(filename, "utf8"), opts); + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } } -},{"../../package":53,"../helpers/resolve-plugin":33,"../helpers/resolve-preset":34,"../tools/build-external-helpers":37,"../transformation/file":38,"../transformation/file/options/config":42,"../transformation/file/options/option-manager":44,"../transformation/pipeline":49,"../util":52,"babel-messages":79,"babel-template":108,"babel-traverse":112,"babel-types":145,"fs":790}],28:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.default = getPossiblePluginNames; -function getPossiblePluginNames(pluginName) { - return ["babel-plugin-" + pluginName, pluginName]; +function emitErrorNT(self, err) { + self.emit('error', err); } -module.exports = exports["default"]; -},{}],29:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.default = getPossiblePresetNames; -function getPossiblePresetNames(presetName) { - var possibleNames = ["babel-preset-" + presetName, presetName]; +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":14}],24:[function(require,module,exports){ +module.exports = require('events').EventEmitter; - var matches = presetName.match(/^(@[^/]+)\/(.+)$/); - if (matches) { - var orgName = matches[1], - presetPath = matches[2]; +},{"events":7}],25:[function(require,module,exports){ +module.exports = require('./readable').PassThrough - possibleNames.push(orgName + "/babel-preset-" + presetPath); +},{"./readable":26}],26:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":17,"./lib/_stream_passthrough.js":18,"./lib/_stream_readable.js":19,"./lib/_stream_transform.js":20,"./lib/_stream_writable.js":21}],27:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":26}],28:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":21}],29:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - return possibleNames; +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -module.exports = exports["default"]; -},{}],30:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} -var _getIterator3 = _interopRequireDefault(_getIterator2); +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} -exports.default = function (dest, src) { - if (!dest || !src) return; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - return (0, _mergeWith2.default)(dest, src, function (a, b) { - if (b && Array.isArray(a)) { - var newArray = b.slice(0); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +},{"buffer":5}],30:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +module.exports = Stream; - var item = _ref; +var EE = require('events').EventEmitter; +var inherits = require('inherits'); - if (newArray.indexOf(item) < 0) { - newArray.push(item); - } - } +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); - return newArray; - } - }); -}; +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; -var _mergeWith = require("lodash/mergeWith"); -var _mergeWith2 = _interopRequireDefault(_mergeWith); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":89,"lodash/mergeWith":491}],31:[function(require,module,exports){ -"use strict"; +function Stream() { + EE.call(this); +} -exports.__esModule = true; +Stream.prototype.pipe = function(dest, options) { + var source = this; -exports.default = function (ast, comments, tokens) { - if (ast) { - if (ast.type === "Program") { - return t.file(ast, comments || [], tokens || []); - } else if (ast.type === "File") { - return ast; + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } } } - throw new Error("Not a valid ast?"); -}; + source.on('data', ondata); -var _babelTypes = require("babel-types"); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } -var t = _interopRequireWildcard(_babelTypes); + dest.on('drain', ondrain); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } -module.exports = exports["default"]; -},{"babel-types":145}],32:[function(require,module,exports){ -"use strict"; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; -exports.__esModule = true; -exports.default = resolveFromPossibleNames; + dest.end(); + } -var _resolve = require("./resolve"); -var _resolve2 = _interopRequireDefault(_resolve); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (typeof dest.destroy === 'function') dest.destroy(); + } -function resolveFromPossibleNames(possibleNames, dirname) { - return possibleNames.reduce(function (accum, curr) { - return accum || (0, _resolve2.default)(curr, dirname); - }, null); -} -module.exports = exports["default"]; -},{"./resolve":35}],33:[function(require,module,exports){ -(function (process){ -"use strict"; + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } -exports.__esModule = true; -exports.default = resolvePlugin; + source.on('error', onerror); + dest.on('error', onerror); -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); + source.removeListener('end', onend); + source.removeListener('close', onclose); -var _getPossiblePluginNames = require("./get-possible-plugin-names"); + source.removeListener('error', onerror); + dest.removeListener('error', onerror); -var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + dest.removeListener('close', cleanup); + } -function resolvePlugin(pluginName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); + source.on('end', cleanup); + source.on('close', cleanup); - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-plugin-names":28,"./resolve-from-possible-names":32,"_process":803}],34:[function(require,module,exports){ -(function (process){ -"use strict"; + dest.on('close', cleanup); -exports.__esModule = true; -exports.default = resolvePreset; + dest.emit('pipe', source); -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); +},{"events":7,"inherits":9,"readable-stream/duplex.js":16,"readable-stream/passthrough.js":25,"readable-stream/readable.js":26,"readable-stream/transform.js":27,"readable-stream/writable.js":28}],31:[function(require,module,exports){ +'use strict'; -var _getPossiblePresetNames = require("./get-possible-preset-names"); +var Buffer = require('safe-buffer').Buffer; -var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames); +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; -function resolvePreset(presetName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname); +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); } -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-preset-names":29,"./resolve-from-possible-names":32,"_process":803}],35:[function(require,module,exports){ -(function (process){ -"use strict"; -exports.__esModule = true; +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; -var _typeof2 = require("babel-runtime/helpers/typeof"); +StringDecoder.prototype.end = utf8End; -var _typeof3 = _interopRequireDefault(_typeof2); +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; -exports.default = function (loc) { - var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; +} - var relativeMod = relativeModules[relative]; +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} - if (!relativeMod) { - relativeMod = new _module2.default(); +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } +} - var filename = _path2.default.join(relative, ".babelrc"); - relativeMod.id = filename; - relativeMod.filename = filename; - - relativeMod.paths = _module2.default._nodeModulePaths(relative); - relativeModules[relative] = relativeMod; - } - - try { - return _module2.default._resolveFilename(loc, relativeMod); - } catch (err) { - return null; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } -}; + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} -var _module = require("module"); +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} -var _module2 = _interopRequireDefault(_module); +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} -var _path = require("path"); +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} -var _path2 = _interopRequireDefault(_path); +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} -var relativeModules = {}; +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"_process":803,"babel-runtime/helpers/typeof":107,"module":790,"path":801}],36:[function(require,module,exports){ -"use strict"; +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} -exports.__esModule = true; +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":29}],32:[function(require,module,exports){ +exports.isatty = function () { return false; }; -var _map = require("babel-runtime/core-js/map"); +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.ReadStream = ReadStream; -var _map2 = _interopRequireDefault(_map); +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.WriteStream = WriteStream; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +},{}],33:[function(require,module,exports){ +(function (global){ -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +/** + * Module exports. + */ -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); +module.exports = deprecate; -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ -var _inherits2 = require("babel-runtime/helpers/inherits"); +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } -var _inherits3 = _interopRequireDefault(_inherits2); + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return deprecated; +} -var Store = function (_Map) { - (0, _inherits3.default)(Store, _Map); +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ - function Store() { - (0, _classCallCheck3.default)(this, Store); +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} - var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],34:[function(require,module,exports){ +arguments[4][9][0].apply(exports,arguments) +},{"dup":9}],35:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],36:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - _this.dynamicData = {}; - return _this; +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); } - Store.prototype.setDynamic = function setDynamic(key, fn) { - this.dynamicData[key] = fn; - }; - - Store.prototype.get = function get(key) { - if (this.has(key)) { - return _Map.prototype.get.call(this, key); + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; } else { - if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { - var val = this.dynamicData[key](); - this.set(key, val); - return val; - } + str += ' ' + inspect(x); } - }; - - return Store; -}(_map2.default); - -exports.default = Store; -module.exports = exports["default"]; -},{"babel-runtime/core-js/map":91,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106}],37:[function(require,module,exports){ -"use strict"; + } + return str; +}; -exports.__esModule = true; -exports.default = function (whitelist) { - var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } - var namespace = t.identifier("babelHelpers"); + if (process.noDeprecation === true) { + return fn; + } - var builder = function builder(body) { - return buildHelpers(body, namespace, whitelist); - }; + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - var tree = void 0; + return deprecated; +}; - var build = { - global: buildGlobal, - umd: buildUmd, - var: buildVar - }[outputType]; - if (build) { - tree = build(namespace, builder); - } else { - throw new Error(messages.get("unsupportedOutputType", outputType)); +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } } - - return (0, _babelGenerator2.default)(tree).code; + return debugs[set]; }; -var _babelHelpers = require("babel-helpers"); - -var helpers = _interopRequireWildcard(_babelHelpers); -var _babelGenerator = require("babel-generator"); +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); -var _babelMessages = require("babel-messages"); +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; -var messages = _interopRequireWildcard(_babelMessages); +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; -var _babelTemplate = require("babel-template"); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; -var _babelTypes = require("babel-types"); + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} -var t = _interopRequireWildcard(_babelTypes); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function stylizeNoColor(str, styleType) { + return str; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n"); +function arrayToHash(array) { + var hash = {}; -function buildGlobal(namespace, builder) { - var body = []; - var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); - var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); + array.forEach(function(val, idx) { + hash[val] = true; + }); - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))])); + return hash; +} - builder(body); - return tree; -} +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } -function buildUmd(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))])); + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - builder(body); + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - return t.program([buildUmdWrapper({ - FACTORY_PARAMETERS: t.identifier("global"), - BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])), - COMMON_ARGUMENTS: t.identifier("exports"), - AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), - FACTORY_BODY: body, - UMD_ROOT: t.identifier("this") - })]); -} + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } -function buildVar(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))])); - builder(body); - body.push(t.expressionStatement(namespace)); - return t.program(body); -} + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } -function buildHelpers(body, namespace, whitelist) { - helpers.list.forEach(function (name) { - if (whitelist && whitelist.indexOf(name) < 0) return; + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } - var key = t.identifier(name); - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)))); - }); -} -module.exports = exports["default"]; -},{"babel-generator":65,"babel-helpers":78,"babel-messages":79,"babel-template":108,"babel-types":145}],38:[function(require,module,exports){ -(function (process){ -"use strict"; + var base = '', array = false, braces = ['{', '}']; -exports.__esModule = true; -exports.File = undefined; + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } -var _create = require("babel-runtime/core-js/object/create"); + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } -var _create2 = _interopRequireDefault(_create); + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } -var _assign = require("babel-runtime/core-js/object/assign"); + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } -var _assign2 = _interopRequireDefault(_assign); + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + ctx.seen.push(value); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + ctx.seen.pop(); -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + return reduceToSingleString(output, base, braces); +} -var _inherits2 = require("babel-runtime/helpers/inherits"); -var _inherits3 = _interopRequireDefault(_inherits2); - -var _babelHelpers = require("babel-helpers"); - -var _babelHelpers2 = _interopRequireDefault(_babelHelpers); - -var _metadata = require("./metadata"); +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} -var metadataVisitor = _interopRequireWildcard(_metadata); -var _convertSourceMap = require("convert-source-map"); +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} -var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); -var _optionManager = require("./options/option-manager"); +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} -var _optionManager2 = _interopRequireDefault(_optionManager); -var _pluginPass = require("../plugin-pass"); +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } -var _pluginPass2 = _interopRequireDefault(_pluginPass); + return name + ': ' + str; +} -var _babelTraverse = require("babel-traverse"); -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); -var _sourceMap = require("source-map"); + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } -var _sourceMap2 = _interopRequireDefault(_sourceMap); + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} -var _babelGenerator = require("babel-generator"); -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; -var _babelCodeFrame = require("babel-code-frame"); +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; -var _defaults = require("lodash/defaults"); +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -var _defaults2 = _interopRequireDefault(_defaults); +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; -var _logger = require("./logger"); +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -var _logger2 = _interopRequireDefault(_logger); +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -var _store = require("../../store"); +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -var _store2 = _interopRequireDefault(_store); +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -var _babylon = require("babylon"); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -var _util = require("../../util"); +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -var util = _interopRequireWildcard(_util); +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -var _path = require("path"); +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; -var _path2 = _interopRequireDefault(_path); +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; -var _babelTypes = require("babel-types"); +exports.isBuffer = require('./support/isBuffer'); -var t = _interopRequireWildcard(_babelTypes); +function objectToString(o) { + return Object.prototype.toString.call(o); +} -var _resolve = require("../../helpers/resolve"); -var _resolve2 = _interopRequireDefault(_resolve); +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} -var _blockHoist = require("../internal-plugins/block-hoist"); -var _blockHoist2 = _interopRequireDefault(_blockHoist); +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; -var _shadowFunctions = require("../internal-plugins/shadow-functions"); +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} -var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var shebangRegex = /^#!.*/; +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); -var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; -var errorVisitor = { - enter: function enter(path, state) { - var loc = path.node.loc; - if (loc) { - state.loc = loc; - path.stop(); - } + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } + return origin; }; -var File = function (_Store) { - (0, _inherits3.default)(File, _Store); - - function File() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var pipeline = arguments[1]; - (0, _classCallCheck3.default)(this, File); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.pipeline = pipeline; - - _this.log = new _logger2.default(_this, opts.filename || "unknown"); - _this.opts = _this.initOptions(opts); - - _this.parserOpts = { - sourceType: _this.opts.sourceType, - sourceFileName: _this.opts.filename, - plugins: [] - }; +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} - _this.pluginVisitors = []; - _this.pluginPasses = []; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":35,"_process":15,"inherits":34}],37:[function(require,module,exports){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - _this.buildPluginsForOptions(_this.opts); +var assert = require("assert"); +var types = require("recast").types; +var n = types.namedTypes; +var b = types.builders; +var hasOwn = Object.prototype.hasOwnProperty; - if (_this.opts.passPerPreset) { - _this.perPresetOpts = []; - _this.opts.presets.forEach(function (presetOpts) { - var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts); - _this.perPresetOpts.push(perPresetOpts); - _this.buildPluginsForOptions(perPresetOpts); - }); - } +exports.defaults = function(obj) { + var len = arguments.length; + var extension; - _this.metadata = { - usedHelpers: [], - marked: [], - modules: { - imports: [], - exports: { - exported: [], - specifiers: [] + for (var i = 1; i < len; ++i) { + if ((extension = arguments[i])) { + for (var key in extension) { + if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) { + obj[key] = extension[key]; } } - }; + } + } - _this.dynamicImportTypes = {}; - _this.dynamicImportIds = {}; - _this.dynamicImports = []; - _this.declarations = {}; - _this.usedHelpers = {}; + return obj; +}; - _this.path = null; - _this.ast = {}; +exports.runtimeProperty = function(name) { + return b.memberExpression( + b.identifier("regeneratorRuntime"), + b.identifier(name), + false + ); +}; - _this.code = ""; - _this.shebang = ""; +// Inspired by the isReference function from ast-util: +// https://github.com/eventualbuddha/ast-util/blob/9bf91c5ce8/lib/index.js#L466-L506 +exports.isReference = function(path, name) { + var node = path.value; - _this.hub = new _babelTraverse.Hub(_this); - return _this; + if (!n.Identifier.check(node)) { + return false; } - File.prototype.getMetadata = function getMetadata() { - var has = false; - for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (name && node.name !== name) { + return false; + } - var node = _ref; + var parent = path.parent.value; - if (t.isModuleDeclaration(node)) { - has = true; - break; - } - } - if (has) { - this.path.traverse(metadataVisitor, this); - } - }; + switch (parent.type) { + case "VariableDeclarator": + return path.name === "init"; - File.prototype.initOptions = function initOptions(opts) { - opts = new _optionManager2.default(this.log, this.pipeline).init(opts); + case "MemberExpression": + return path.name === "object" || ( + parent.computed && path.name === "property" + ); - if (opts.inputSourceMap) { - opts.sourceMaps = true; + case "FunctionExpression": + case "FunctionDeclaration": + case "ArrowFunctionExpression": + if (path.name === "id") { + return false; } - if (opts.moduleId) { - opts.moduleIds = true; + if (path.parentPath.name === "params" && + parent.params === path.parentPath.value && + parent.params[path.name] === node) { + return false; } - opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename)); - - opts.ignore = util.arrayify(opts.ignore, util.regexify); + return true; - if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); + case "ClassDeclaration": + case "ClassExpression": + return path.name !== "id"; - (0, _defaults2.default)(opts, { - moduleRoot: opts.sourceRoot - }); + case "CatchClause": + return path.name !== "param"; - (0, _defaults2.default)(opts, { - sourceRoot: opts.moduleRoot - }); + case "Property": + case "MethodDefinition": + return path.name !== "key"; - (0, _defaults2.default)(opts, { - filenameRelative: opts.filename - }); + case "ImportSpecifier": + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "LabeledStatement": + return false; - var basenameRelative = _path2.default.basename(opts.filenameRelative); + default: + return true; + } +}; - (0, _defaults2.default)(opts, { - sourceFileName: basenameRelative, - sourceMapTarget: basenameRelative - }); +},{"assert":2,"recast":559}],38:[function(require,module,exports){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - return opts; - }; +var recast = require("recast"); +var types = recast.types; +var n = types.namedTypes; +var util = require("./util.js"); - File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) { - if (!Array.isArray(opts.plugins)) { - return; - } +exports.transform = function transform(node, options) { + options = util.defaults(options || {}, { + includeRuntime: false, + presetOptions: {}, + }); + options.presetOptions.globalRuntimeName = options.includeRuntime === true && "regeneratorRuntime"; - var plugins = opts.plugins.concat(INTERNAL_PLUGINS); - var currentPluginVisitors = []; - var currentPluginPasses = []; + var result = require("babel-core").transformFromAst(node, null, { + presets: [["regenerator-preset", options.presetOptions]], + code: false, + ast: true + }); - for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + node = result.ast; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + if (options.includeRuntime === true) { + injectRuntime(n.File.check(node) ? node.program : node); + } - var ref = _ref2; - var plugin = ref[0], - pluginOpts = ref[1]; + return node; +}; +function injectRuntime(program) { + n.Program.assert(program); - currentPluginVisitors.push(plugin.visitor); - currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts)); + // Include the runtime by modifying the AST rather than by concatenating + // strings. This technique will allow for more accurate source mapping. + var runtime = require("..").runtime; + var runtimeBody = recast.parse(runtime.getCode(), { + sourceFileName: runtime.path, + }).program.body; - if (plugin.manipulateOptions) { - plugin.manipulateOptions(opts, this.parserOpts, this); - } - } + var body = program.body; + body.unshift.apply(body, runtimeBody); +} - this.pluginVisitors.push(currentPluginVisitors); - this.pluginPasses.push(currentPluginPasses); - }; +},{"..":39,"./util.js":37,"babel-core":62,"recast":559}],39:[function(require,module,exports){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - File.prototype.getModuleName = function getModuleName() { - var opts = this.opts; - if (!opts.moduleIds) { - return null; - } +var fs = require("fs"); +var through = require("through"); +var babel = require("babel-core"); +var babylon = require("babylon"); +var traverse = require("babel-traverse").default; +var generate = require("babel-generator").default; +var transform = require("./lib/visit").transform; +var utils = require("./lib/util"); +var genOrAsyncFunExp = /\bfunction\s*\*|\basync\b/; - if (opts.moduleId != null && !opts.getModuleId) { - return opts.moduleId; - } +function exports(file, options) { + var data = []; + return through(write, end); - var filenameRelative = opts.filenameRelative; - var moduleName = ""; + function write(buf) { + data.push(buf); + } - if (opts.moduleRoot != null) { - moduleName = opts.moduleRoot + "/"; - } + function end() { + try { + this.queue(compile(data.join(""), options).code); + this.queue(null); + } catch (e) { this.emit('error', e); } + } +} - if (!opts.filenameRelative) { - return moduleName + opts.filename.replace(/^\//, ""); - } +// To get a writable stream for use as a browserify transform, call +// require("regenerator")(). +module.exports = exports; - if (opts.sourceRoot != null) { - var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); - filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); - } +// To include the runtime globally in the current node process, call +// require("regenerator").runtime(). +function runtime() { + regeneratorRuntime = require("regenerator-runtime"); +} +exports.runtime = runtime; +runtime.path = "regenerator-runtime/lib/index.js" - filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); +var cachedRuntimeCode; +function getRuntimeCode() { + if (cachedRuntimeCode) { + return cachedRuntimeCode; + } + var source = fs.readFileSync(runtime.path, "utf8").replace(/^'use strict';/, "'use strict';\nvar exports = {};"); + var ast = babylon.parse(source); - moduleName += filenameRelative; + traverse(ast, { + Program: function (path) { + path.scope.rename("exports", "regeneratorRuntime"); + }, + }); - moduleName = moduleName.replace(/\\/g, "/"); + return (cachedRuntimeCode = generate(ast).code); +} +runtime.getCode = getRuntimeCode; - if (opts.getModuleId) { - return opts.getModuleId(moduleName) || moduleName; - } else { - return moduleName; +var getTransformOptions = function (opts) { + opts = utils.defaults(opts || {}, { + strict: false + }); + + return { + presets: [[require("regenerator-preset"), opts]], + parserOpts: { + sourceType: "module", + allowImportExportEverywhere: true, + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, + strictMode: false, + plugins: ["*", "jsx", "flow"] } - }; + } +}; - File.prototype.resolveModuleSource = function resolveModuleSource(source) { - var resolveModuleSource = this.opts.resolveModuleSource; - if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); - return source; - }; +function compile(source, options) { + var result; - File.prototype.addImport = function addImport(source, imported) { - var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported; + options = utils.defaults(options || {}, { + includeRuntime: false + }); - var alias = source + ":" + imported; - var id = this.dynamicImportIds[alias]; + // Shortcut: Transform only if generators or async functions present. + if (genOrAsyncFunExp.test(source)) { + var globalRuntimeName = options.includeRuntime === true && "regeneratorRuntime"; + result = babel.transform(source, getTransformOptions({ + globalRuntimeName: globalRuntimeName, + })); + } else { + result = { code: source }; + } - if (!id) { - source = this.resolveModuleSource(source); - id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); + if (options.includeRuntime === true) { + result.code = getRuntimeCode() + "\n" + result.code; + } - var specifiers = []; + return result; +} - if (imported === "*") { - specifiers.push(t.importNamespaceSpecifier(id)); - } else if (imported === "default") { - specifiers.push(t.importDefaultSpecifier(id)); - } else { - specifiers.push(t.importSpecifier(id, t.identifier(imported))); - } +// Allow packages that depend on Regenerator to use the same copy of +// ast-types, in case multiple versions are installed by NPM. +exports.types = require("recast").types; - var declar = t.importDeclaration(specifiers, t.stringLiteral(source)); - declar._blockHoist = 3; +// Transforms a string of source code, returning a { code, map? } result. +exports.compile = compile; - this.path.unshiftContainer("body", declar); - } +// To modify an AST directly, call require("regenerator").transform(ast). +exports.transform = transform; - return id; - }; +},{"./lib/util":37,"./lib/visit":38,"babel-core":62,"babel-generator":101,"babel-traverse":150,"babylon":187,"fs":1,"recast":559,"regenerator-preset":578,"regenerator-runtime":579,"through":575}],40:[function(require,module,exports){ +'use strict'; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +}; - File.prototype.addHelper = function addHelper(name) { - var declar = this.declarations[name]; - if (declar) return declar; +},{}],41:[function(require,module,exports){ +'use strict'; - if (!this.usedHelpers[name]) { - this.metadata.usedHelpers.push(name); - this.usedHelpers[name] = true; - } +function assembleStyles () { + var styles = { + modifiers: { + reset: [0, 0], + bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + colors: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39] + }, + bgColors: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49] + } + }; - var generator = this.get("helperGenerator"); - var runtime = this.get("helpersNamespace"); - if (generator) { - var res = generator(name); - if (res) return res; - } else if (runtime) { - return t.memberExpression(runtime, t.identifier(name)); - } + // fix humans + styles.colors.grey = styles.colors.gray; - var ref = (0, _babelHelpers2.default)(name); - var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + Object.keys(styles).forEach(function (groupName) { + var group = styles[groupName]; - if (t.isFunctionExpression(ref) && !ref.id) { - ref.body._compact = true; - ref._generated = true; - ref.id = uid; - ref.type = "FunctionDeclaration"; - this.path.unshiftContainer("body", ref); - } else { - ref._compact = true; - this.scope.push({ - id: uid, - init: ref, - unique: true - }); - } + Object.keys(group).forEach(function (styleName) { + var style = group[styleName]; - return uid; - }; + styles[styleName] = group[styleName] = { + open: '\u001b[' + style[0] + 'm', + close: '\u001b[' + style[1] + 'm' + }; + }); - File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { - var stringIds = raw.elements.map(function (string) { - return string.value; - }); - var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + }); - var declar = this.declarations[name]; - if (declar) return declar; + return styles; +} - var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); - var helperId = this.addHelper(helperName); - var init = t.callExpression(helperId, [strings, raw]); - init._compact = true; - this.scope.push({ - id: uid, - init: init, - _blockHoist: 1.9 }); - return uid; - }; +},{}],42:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./es7")); - File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) { - var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; + var types = fork.use(require("../lib/types")); + var defaults = fork.use(require("../lib/shared")).defaults; + var def = types.Type.def; + var or = types.Type.or; - var loc = node && (node.loc || node._loc); + def("Noop") + .bases("Node") + .build(); - var err = new Error(msg); + def("DoExpression") + .bases("Expression") + .build("body") + .field("body", [def("Statement")]); - if (loc) { - err.loc = loc.start; - } else { - (0, _babelTraverse2.default)(node, errorVisitor, this.scope, err); + def("Super") + .bases("Expression") + .build(); - err.message += " (This is an error on an internal node. Probably an internal error"; + def("BindExpression") + .bases("Expression") + .build("object", "callee") + .field("object", or(def("Expression"), null)) + .field("callee", def("Expression")); - if (err.loc) { - err.message += ". Location has been estimated."; - } + def("Decorator") + .bases("Node") + .build("expression") + .field("expression", def("Expression")); - err.message += ")"; - } + def("Property") + .field("decorators", + or([def("Decorator")], null), + defaults["null"]); - return err; - }; + def("MethodDefinition") + .field("decorators", + or([def("Decorator")], null), + defaults["null"]); - File.prototype.mergeSourceMap = function mergeSourceMap(map) { - var inputMap = this.opts.inputSourceMap; + def("MetaProperty") + .bases("Expression") + .build("meta", "property") + .field("meta", def("Identifier")) + .field("property", def("Identifier")); - if (inputMap) { - var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap); - var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map); + def("ParenthesizedExpression") + .bases("Expression") + .build("expression") + .field("expression", def("Expression")); - var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({ - file: inputMapConsumer.file, - sourceRoot: inputMapConsumer.sourceRoot - }); + def("ImportSpecifier") + .bases("ModuleSpecifier") + .build("imported", "local") + .field("imported", def("Identifier")); - var source = outputMapConsumer.sources[0]; + def("ImportDefaultSpecifier") + .bases("ModuleSpecifier") + .build("local"); - inputMapConsumer.eachMapping(function (mapping) { - var generatedPosition = outputMapConsumer.generatedPositionFor({ - line: mapping.generatedLine, - column: mapping.generatedColumn, - source: source - }); - if (generatedPosition.column != null) { - mergedGenerator.addMapping({ - source: mapping.source, + def("ImportNamespaceSpecifier") + .bases("ModuleSpecifier") + .build("local"); - original: mapping.source == null ? null : { - line: mapping.originalLine, - column: mapping.originalColumn - }, + def("ExportDefaultDeclaration") + .bases("Declaration") + .build("declaration") + .field("declaration", or(def("Declaration"), def("Expression"))); - generated: generatedPosition - }); - } - }); + def("ExportNamedDeclaration") + .bases("Declaration") + .build("declaration", "specifiers", "source") + .field("declaration", or(def("Declaration"), null)) + .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray) + .field("source", or(def("Literal"), null), defaults["null"]); - var mergedMap = mergedGenerator.toJSON(); - inputMap.mappings = mergedMap.mappings; - return inputMap; - } else { - return map; - } - }; + def("ExportSpecifier") + .bases("ModuleSpecifier") + .build("local", "exported") + .field("exported", def("Identifier")); - File.prototype.parse = function parse(code) { - var parseCode = _babylon.parse; - var parserOpts = this.opts.parserOpts; + def("ExportNamespaceSpecifier") + .bases("Specifier") + .build("exported") + .field("exported", def("Identifier")); - if (parserOpts) { - parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); + def("ExportDefaultSpecifier") + .bases("Specifier") + .build("exported") + .field("exported", def("Identifier")); - if (parserOpts.parser) { - if (typeof parserOpts.parser === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var parser = (0, _resolve2.default)(parserOpts.parser, dirname); - if (parser) { - parseCode = require(parser).parse; - } else { - throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname)); - } - } else { - parseCode = parserOpts.parser; - } + def("ExportAllDeclaration") + .bases("Declaration") + .build("exported", "source") + .field("exported", or(def("Identifier"), null)) + .field("source", def("Literal")); - parserOpts.parser = { - parse: function parse(source) { - return (0, _babylon.parse)(source, parserOpts); - } - }; - } - } + def("CommentBlock") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); - this.log.debug("Parse start"); - var ast = parseCode(code, parserOpts || this.parserOpts); - this.log.debug("Parse stop"); - return ast; - }; + def("CommentLine") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); +}; +},{"../lib/shared":58,"../lib/types":59,"./es7":47}],43:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./babel")); + fork.use(require("./flow")); - File.prototype._addAst = function _addAst(ast) { - this.path = _babelTraverse.NodePath.get({ - hub: this.hub, - parentPath: null, - parent: ast, - container: ast, - key: "program" - }).setContext(); - this.scope = this.path.scope; - this.ast = ast; - this.getMetadata(); - }; + // var types = fork.types; + var types = fork.use(require("../lib/types")); + // var defaults = fork.shared.defaults; + var defaults = fork.use(require("../lib/shared")).defaults; + var def = types.Type.def; + var or = types.Type.or; - File.prototype.addAst = function addAst(ast) { - this.log.debug("Start set AST"); - this._addAst(ast); - this.log.debug("End set AST"); - }; + def("Directive") + .bases("Node") + .build("value") + .field("value", def("DirectiveLiteral")); - File.prototype.transform = function transform() { - for (var i = 0; i < this.pluginPasses.length; i++) { - var pluginPasses = this.pluginPasses[i]; - this.call("pre", pluginPasses); - this.log.debug("Start transform traverse"); + def("DirectiveLiteral") + .bases("Node", "Expression") + .build("value") + .field("value", String, defaults["use strict"]); - var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); - (0, _babelTraverse2.default)(this.ast, visitor, this.scope); + def("BlockStatement") + .bases("Statement") + .build("body") + .field("body", [def("Statement")]) + .field("directives", [def("Directive")], defaults.emptyArray); - this.log.debug("End transform traverse"); - this.call("post", pluginPasses); - } + def("Program") + .bases("Node") + .build("body") + .field("body", [def("Statement")]) + .field("directives", [def("Directive")], defaults.emptyArray); - return this.generate(); - }; + // Split Literal + def("StringLiteral") + .bases("Literal") + .build("value") + .field("value", String); - File.prototype.wrap = function wrap(code, callback) { - code = code + ""; + def("NumericLiteral") + .bases("Literal") + .build("value") + .field("value", Number); - try { - if (this.shouldIgnore()) { - return this.makeResult({ code: code, ignored: true }); - } else { - return callback(); - } - } catch (err) { - if (err._babel) { - throw err; - } else { - err._babel = true; - } + def("NullLiteral") + .bases("Literal") + .build(); - var message = err.message = this.opts.filename + ": " + err.message; + def("BooleanLiteral") + .bases("Literal") + .build("value") + .field("value", Boolean); - var loc = err.loc; - if (loc) { - err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); - message += "\n" + err.codeFrame; - } + def("RegExpLiteral") + .bases("Literal") + .build("pattern", "flags") + .field("pattern", String) + .field("flags", String); - if (process.browser) { - err.message = message; - } + var ObjectExpressionProperty = or( + def("Property"), + def("ObjectMethod"), + def("ObjectProperty"), + def("SpreadProperty") + ); - if (err.stack) { - var newStack = err.stack.replace(err.message, message); - err.stack = newStack; - } - - throw err; - } - }; + // Split Property -> ObjectProperty and ObjectMethod + def("ObjectExpression") + .bases("Expression") + .build("properties") + .field("properties", [ObjectExpressionProperty]); - File.prototype.addCode = function addCode(code) { - code = (code || "") + ""; - code = this.parseInputSourceMap(code); - this.code = code; - }; + // ObjectMethod hoist .value properties to own properties + def("ObjectMethod") + .bases("Node", "Function") + .build("kind", "key", "params", "body", "computed") + .field("kind", or("method", "get", "set")) + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("params", [def("Pattern")]) + .field("body", def("BlockStatement")) + .field("computed", Boolean, defaults["false"]) + .field("generator", Boolean, defaults["false"]) + .field("async", Boolean, defaults["false"]) + .field("decorators", + or([def("Decorator")], null), + defaults["null"]); - File.prototype.parseCode = function parseCode() { - this.parseShebang(); - var ast = this.parse(this.code); - this.addAst(ast); - }; + def("ObjectProperty") + .bases("Node") + .build("key", "value") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("value", or(def("Expression"), def("Pattern"))) + .field("computed", Boolean, defaults["false"]); - File.prototype.shouldIgnore = function shouldIgnore() { - var opts = this.opts; - return util.shouldIgnore(opts.filename, opts.ignore, opts.only); - }; + var ClassBodyElement = or( + def("MethodDefinition"), + def("VariableDeclarator"), + def("ClassPropertyDefinition"), + def("ClassProperty"), + def("ClassMethod") + ); - File.prototype.call = function call(key, pluginPasses) { - for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + // MethodDefinition -> ClassMethod + def("ClassBody") + .bases("Declaration") + .build("body") + .field("body", [ClassBodyElement]); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + def("ClassMethod") + .bases("Declaration", "Function") + .build("kind", "key", "params", "body", "computed", "static") + .field("kind", or("get", "set", "method", "constructor")) + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("params", [def("Pattern")]) + .field("body", def("BlockStatement")) + .field("computed", Boolean, defaults["false"]) + .field("static", Boolean, defaults["false"]) + .field("generator", Boolean, defaults["false"]) + .field("async", Boolean, defaults["false"]) + .field("decorators", + or([def("Decorator")], null), + defaults["null"]); - var pass = _ref3; + var ObjectPatternProperty = or( + def("Property"), + def("PropertyPattern"), + def("SpreadPropertyPattern"), + def("SpreadProperty"), // Used by Esprima + def("ObjectProperty"), // Babel 6 + def("RestProperty") // Babel 6 + ); - var plugin = pass.plugin; - var fn = plugin[key]; - if (fn) fn.call(pass, this); - } - }; + // Split into RestProperty and SpreadProperty + def("ObjectPattern") + .bases("Pattern") + .build("properties") + .field("properties", [ObjectPatternProperty]) + .field("decorators", + or([def("Decorator")], null), + defaults["null"]); - File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { - var opts = this.opts; + def("SpreadProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); - if (opts.inputSourceMap !== false) { - var inputMap = _convertSourceMap2.default.fromSource(code); - if (inputMap) { - opts.inputSourceMap = inputMap.toObject(); - code = _convertSourceMap2.default.removeComments(code); - } - } + def("RestProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); - return code; - }; + def("ForAwaitStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or( + def("VariableDeclaration"), + def("Expression"))) + .field("right", def("Expression")) + .field("body", def("Statement")); - File.prototype.parseShebang = function parseShebang() { - var shebangMatch = shebangRegex.exec(this.code); - if (shebangMatch) { - this.shebang = shebangMatch[0]; - this.code = this.code.replace(shebangRegex, ""); - } - }; + // The callee node of a dynamic import(...) expression. + def("Import") + .bases("Expression") + .build(); +}; - File.prototype.makeResult = function makeResult(_ref4) { - var code = _ref4.code, - map = _ref4.map, - ast = _ref4.ast, - ignored = _ref4.ignored; +},{"../lib/shared":58,"../lib/types":59,"./babel":42,"./flow":49}],44:[function(require,module,exports){ +module.exports = function (fork) { + var types = fork.use(require("../lib/types")); + var Type = types.Type; + var def = Type.def; + var or = Type.or; + var shared = fork.use(require("../lib/shared")); + var defaults = shared.defaults; + var geq = shared.geq; - var result = { - metadata: null, - options: this.opts, - ignored: !!ignored, - code: null, - ast: null, - map: map || null - }; + // Abstract supertype of all syntactic entities that are allowed to have a + // .loc field. + def("Printable") + .field("loc", or( + def("SourceLocation"), + null + ), defaults["null"], true); - if (this.opts.code) { - result.code = code; - } + def("Node") + .bases("Printable") + .field("type", String) + .field("comments", or( + [def("Comment")], + null + ), defaults["null"], true); - if (this.opts.ast) { - result.ast = ast; - } + def("SourceLocation") + .build("start", "end", "source") + .field("start", def("Position")) + .field("end", def("Position")) + .field("source", or(String, null), defaults["null"]); - if (this.opts.metadata) { - result.metadata = this.metadata; - } + def("Position") + .build("line", "column") + .field("line", geq(1)) + .field("column", geq(0)); - return result; - }; + def("File") + .bases("Node") + .build("program", "name") + .field("program", def("Program")) + .field("name", or(String, null), defaults["null"]); - File.prototype.generate = function generate() { - var opts = this.opts; - var ast = this.ast; + def("Program") + .bases("Node") + .build("body") + .field("body", [def("Statement")]); - var result = { ast: ast }; - if (!opts.code) return this.makeResult(result); + def("Function") + .bases("Node") + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("params", [def("Pattern")]) + .field("body", def("BlockStatement")); - var gen = _babelGenerator2.default; - if (opts.generatorOpts.generator) { - gen = opts.generatorOpts.generator; + def("Statement").bases("Node"); - if (typeof gen === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var generator = (0, _resolve2.default)(gen, dirname); - if (generator) { - gen = require(generator).print; - } else { - throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname)); - } - } - } +// The empty .build() here means that an EmptyStatement can be constructed +// (i.e. it's not abstract) but that it needs no arguments. + def("EmptyStatement").bases("Statement").build(); - this.log.debug("Generation start"); + def("BlockStatement") + .bases("Statement") + .build("body") + .field("body", [def("Statement")]); - var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); - result.code = _result.code; - result.map = _result.map; + // TODO Figure out how to silently coerce Expressions to + // ExpressionStatements where a Statement was expected. + def("ExpressionStatement") + .bases("Statement") + .build("expression") + .field("expression", def("Expression")); - this.log.debug("Generation end"); + def("IfStatement") + .bases("Statement") + .build("test", "consequent", "alternate") + .field("test", def("Expression")) + .field("consequent", def("Statement")) + .field("alternate", or(def("Statement"), null), defaults["null"]); - if (this.shebang) { - result.code = this.shebang + "\n" + result.code; - } + def("LabeledStatement") + .bases("Statement") + .build("label", "body") + .field("label", def("Identifier")) + .field("body", def("Statement")); - if (result.map) { - result.map = this.mergeSourceMap(result.map); - } + def("BreakStatement") + .bases("Statement") + .build("label") + .field("label", or(def("Identifier"), null), defaults["null"]); - if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { - result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment(); - } + def("ContinueStatement") + .bases("Statement") + .build("label") + .field("label", or(def("Identifier"), null), defaults["null"]); - if (opts.sourceMaps === "inline") { - result.map = null; - } + def("WithStatement") + .bases("Statement") + .build("object", "body") + .field("object", def("Expression")) + .field("body", def("Statement")); - return this.makeResult(result); - }; + def("SwitchStatement") + .bases("Statement") + .build("discriminant", "cases", "lexical") + .field("discriminant", def("Expression")) + .field("cases", [def("SwitchCase")]) + .field("lexical", Boolean, defaults["false"]); - return File; -}(_store2.default); + def("ReturnStatement") + .bases("Statement") + .build("argument") + .field("argument", or(def("Expression"), null)); -exports.default = File; -exports.File = File; -}).call(this,require('_process')) -},{"../../helpers/resolve":35,"../../store":36,"../../util":52,"../internal-plugins/block-hoist":47,"../internal-plugins/shadow-functions":48,"../plugin-pass":50,"./logger":39,"./metadata":40,"./options/option-manager":44,"_process":803,"babel-code-frame":25,"babel-generator":65,"babel-helpers":78,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/object/assign":93,"babel-runtime/core-js/object/create":94,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106,"babel-traverse":112,"babel-types":145,"babylon":149,"convert-source-map":154,"lodash/defaults":459,"path":801,"source-map":534}],39:[function(require,module,exports){ -"use strict"; + def("ThrowStatement") + .bases("Statement") + .build("argument") + .field("argument", def("Expression")); -exports.__esModule = true; + def("TryStatement") + .bases("Statement") + .build("block", "handler", "finalizer") + .field("block", def("BlockStatement")) + .field("handler", or(def("CatchClause"), null), function () { + return this.handlers && this.handlers[0] || null; + }) + .field("handlers", [def("CatchClause")], function () { + return this.handler ? [this.handler] : []; + }, true) // Indicates this field is hidden from eachField iteration. + .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) + .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + def("CatchClause") + .bases("Node") + .build("param", "guard", "body") + .field("param", def("Pattern")) + .field("guard", or(def("Expression"), null), defaults["null"]) + .field("body", def("BlockStatement")); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + def("WhileStatement") + .bases("Statement") + .build("test", "body") + .field("test", def("Expression")) + .field("body", def("Statement")); -var _node = require("debug/node"); + def("DoWhileStatement") + .bases("Statement") + .build("body", "test") + .field("body", def("Statement")) + .field("test", def("Expression")); -var _node2 = _interopRequireDefault(_node); + def("ForStatement") + .bases("Statement") + .build("init", "test", "update", "body") + .field("init", or( + def("VariableDeclaration"), + def("Expression"), + null)) + .field("test", or(def("Expression"), null)) + .field("update", or(def("Expression"), null)) + .field("body", def("Statement")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + def("ForInStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or( + def("VariableDeclaration"), + def("Expression"))) + .field("right", def("Expression")) + .field("body", def("Statement")); -var verboseDebug = (0, _node2.default)("babel:verbose"); -var generalDebug = (0, _node2.default)("babel"); + def("DebuggerStatement").bases("Statement").build(); -var seenDeprecatedMessages = []; + def("Declaration").bases("Statement"); -var Logger = function () { - function Logger(file, filename) { - (0, _classCallCheck3.default)(this, Logger); + def("FunctionDeclaration") + .bases("Function", "Declaration") + .build("id", "params", "body") + .field("id", def("Identifier")); - this.filename = filename; - this.file = file; - } + def("FunctionExpression") + .bases("Function", "Expression") + .build("id", "params", "body"); - Logger.prototype._buildMessage = function _buildMessage(msg) { - var parts = "[BABEL] " + this.filename; - if (msg) parts += ": " + msg; - return parts; - }; + def("VariableDeclaration") + .bases("Declaration") + .build("kind", "declarations") + .field("kind", or("var", "let", "const")) + .field("declarations", [def("VariableDeclarator")]); - Logger.prototype.warn = function warn(msg) { - console.warn(this._buildMessage(msg)); - }; + def("VariableDeclarator") + .bases("Node") + .build("id", "init") + .field("id", def("Pattern")) + .field("init", or(def("Expression"), null)); - Logger.prototype.error = function error(msg) { - var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; + // TODO Are all Expressions really Patterns? + def("Expression").bases("Node", "Pattern"); - throw new Constructor(this._buildMessage(msg)); - }; + def("ThisExpression").bases("Expression").build(); - Logger.prototype.deprecate = function deprecate(msg) { - if (this.file.opts && this.file.opts.suppressDeprecationMessages) return; + def("ArrayExpression") + .bases("Expression") + .build("elements") + .field("elements", [or(def("Expression"), null)]); - msg = this._buildMessage(msg); + def("ObjectExpression") + .bases("Expression") + .build("properties") + .field("properties", [def("Property")]); - if (seenDeprecatedMessages.indexOf(msg) >= 0) return; + // TODO Not in the Mozilla Parser API, but used by Esprima. + def("Property") + .bases("Node") // Want to be able to visit Property Nodes. + .build("kind", "key", "value") + .field("kind", or("init", "get", "set")) + .field("key", or(def("Literal"), def("Identifier"))) + .field("value", def("Expression")); - seenDeprecatedMessages.push(msg); + def("SequenceExpression") + .bases("Expression") + .build("expressions") + .field("expressions", [def("Expression")]); - console.error(msg); - }; + var UnaryOperator = or( + "-", "+", "!", "~", + "typeof", "void", "delete"); - Logger.prototype.verbose = function verbose(msg) { - if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg)); - }; + def("UnaryExpression") + .bases("Expression") + .build("operator", "argument", "prefix") + .field("operator", UnaryOperator) + .field("argument", def("Expression")) + // Esprima doesn't bother with this field, presumably because it's + // always true for unary operators. + .field("prefix", Boolean, defaults["true"]); - Logger.prototype.debug = function debug(msg) { - if (generalDebug.enabled) generalDebug(this._buildMessage(msg)); - }; + var BinaryOperator = or( + "==", "!=", "===", "!==", + "<", "<=", ">", ">=", + "<<", ">>", ">>>", + "+", "-", "*", "/", "%", + "&", // TODO Missing from the Parser API. + "|", "^", "in", + "instanceof", ".."); - Logger.prototype.deopt = function deopt(node, msg) { - this.debug(msg); - }; + def("BinaryExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", BinaryOperator) + .field("left", def("Expression")) + .field("right", def("Expression")); - return Logger; -}(); + var AssignmentOperator = or( + "=", "+=", "-=", "*=", "/=", "%=", + "<<=", ">>=", ">>>=", + "|=", "^=", "&="); -exports.default = Logger; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":103,"debug/node":270}],40:[function(require,module,exports){ -"use strict"; + def("AssignmentExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", AssignmentOperator) + .field("left", def("Pattern")) + .field("right", def("Expression")); -exports.__esModule = true; -exports.ImportDeclaration = exports.ModuleDeclaration = undefined; + var UpdateOperator = or("++", "--"); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + def("UpdateExpression") + .bases("Expression") + .build("operator", "argument", "prefix") + .field("operator", UpdateOperator) + .field("argument", def("Expression")) + .field("prefix", Boolean); -var _getIterator3 = _interopRequireDefault(_getIterator2); + var LogicalOperator = or("||", "&&"); -exports.ExportDeclaration = ExportDeclaration; -exports.Scope = Scope; + def("LogicalExpression") + .bases("Expression") + .build("operator", "left", "right") + .field("operator", LogicalOperator) + .field("left", def("Expression")) + .field("right", def("Expression")); -var _babelTypes = require("babel-types"); + def("ConditionalExpression") + .bases("Expression") + .build("test", "consequent", "alternate") + .field("test", def("Expression")) + .field("consequent", def("Expression")) + .field("alternate", def("Expression")); -var t = _interopRequireWildcard(_babelTypes); + def("NewExpression") + .bases("Expression") + .build("callee", "arguments") + .field("callee", def("Expression")) + // The Mozilla Parser API gives this type as [or(def("Expression"), + // null)], but null values don't really make sense at the call site. + // TODO Report this nonsense. + .field("arguments", [def("Expression")]); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + def("CallExpression") + .bases("Expression") + .build("callee", "arguments") + .field("callee", def("Expression")) + // See comment for NewExpression above. + .field("arguments", [def("Expression")]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + def("MemberExpression") + .bases("Expression") + .build("object", "property", "computed") + .field("object", def("Expression")) + .field("property", or(def("Identifier"), def("Expression"))) + .field("computed", Boolean, function () { + var type = this.property.type; + if (type === 'Literal' || + type === 'MemberExpression' || + type === 'BinaryExpression') { + return true; + } + return false; + }); -var ModuleDeclaration = exports.ModuleDeclaration = { - enter: function enter(path, file) { - var node = path.node; + def("Pattern").bases("Node"); - if (node.source) { - node.source.value = file.resolveModuleSource(node.source.value); - } - } -}; + def("SwitchCase") + .bases("Node") + .build("test", "consequent") + .field("test", or(def("Expression"), null)) + .field("consequent", [def("Statement")]); -var ImportDeclaration = exports.ImportDeclaration = { - exit: function exit(path, file) { - var node = path.node; + def("Identifier") + // But aren't Expressions and Patterns already Nodes? TODO Report this. + .bases("Node", "Expression", "Pattern") + .build("name") + .field("name", String); + def("Literal") + // But aren't Expressions already Nodes? TODO Report this. + .bases("Node", "Expression") + .build("value") + .field("value", or(String, Boolean, null, Number, RegExp)) + .field("regex", or({ + pattern: String, + flags: String + }, null), function () { + if (this.value instanceof RegExp) { + var flags = ""; - var specifiers = []; - var imported = []; - file.metadata.modules.imports.push({ - source: node.source.value, - imported: imported, - specifiers: specifiers - }); + if (this.value.ignoreCase) flags += "i"; + if (this.value.multiline) flags += "m"; + if (this.value.global) flags += "g"; - for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + return { + pattern: this.value.source, + flags: flags + }; + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + return null; + }); - var specifier = _ref; + // Abstract (non-buildable) comment supertype. Not a Node. + def("Comment") + .bases("Printable") + .field("value", String) + // A .leading comment comes before the node, whereas a .trailing + // comment comes after it. These two fields should not both be true, + // but they might both be false when the comment falls inside a node + // and the node has no children for the comment to lead or trail, + // e.g. { /*dangling*/ }. + .field("leading", Boolean, defaults["true"]) + .field("trailing", Boolean, defaults["false"]); +}; +},{"../lib/shared":58,"../lib/types":59}],45:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./core")); + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; - var local = specifier.node.local.name; + // Note that none of these types are buildable because the Mozilla Parser + // API doesn't specify any builder functions, and nobody uses E4X anymore. - if (specifier.isImportDefaultSpecifier()) { - imported.push("default"); - specifiers.push({ - kind: "named", - imported: "default", - local: local - }); - } + def("XMLDefaultDeclaration") + .bases("Declaration") + .field("namespace", def("Expression")); - if (specifier.isImportSpecifier()) { - var importedName = specifier.node.imported.name; - imported.push(importedName); - specifiers.push({ - kind: "named", - imported: importedName, - local: local - }); - } + def("XMLAnyName").bases("Expression"); - if (specifier.isImportNamespaceSpecifier()) { - imported.push("*"); - specifiers.push({ - kind: "namespace", - local: local - }); - } - } - } -}; + def("XMLQualifiedIdentifier") + .bases("Expression") + .field("left", or(def("Identifier"), def("XMLAnyName"))) + .field("right", or(def("Identifier"), def("Expression"))) + .field("computed", Boolean); -function ExportDeclaration(path, file) { - var node = path.node; + def("XMLFunctionQualifiedIdentifier") + .bases("Expression") + .field("right", or(def("Identifier"), def("Expression"))) + .field("computed", Boolean); + def("XMLAttributeSelector") + .bases("Expression") + .field("attribute", def("Expression")); - var source = node.source ? node.source.value : null; - var exports = file.metadata.modules.exports; + def("XMLFilterExpression") + .bases("Expression") + .field("left", def("Expression")) + .field("right", def("Expression")); - var declar = path.get("declaration"); - if (declar.isStatement()) { - var bindings = declar.getBindingIdentifiers(); + def("XMLElement") + .bases("XML", "Expression") + .field("contents", [def("XML")]); - for (var name in bindings) { - exports.exported.push(name); - exports.specifiers.push({ - kind: "local", - local: name, - exported: path.isExportDefaultDeclaration() ? "default" : name - }); - } - } + def("XMLList") + .bases("XML", "Expression") + .field("contents", [def("XML")]); - if (path.isExportNamedDeclaration() && node.specifiers) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + def("XML").bases("Node"); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + def("XMLEscape") + .bases("XML") + .field("expression", def("Expression")); - var specifier = _ref2; + def("XMLText") + .bases("XML") + .field("text", String); - var exported = specifier.exported.name; - exports.exported.push(exported); + def("XMLStartTag") + .bases("XML") + .field("contents", [def("XML")]); - if (t.isExportDefaultSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external", - local: exported, - exported: exported, - source: source - }); - } + def("XMLEndTag") + .bases("XML") + .field("contents", [def("XML")]); - if (t.isExportNamespaceSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external-namespace", - exported: exported, - source: source - }); - } + def("XMLPointTag") + .bases("XML") + .field("contents", [def("XML")]); - var local = specifier.local; - if (!local) continue; + def("XMLName") + .bases("XML") + .field("contents", or(String, [def("XML")])); - if (source) { - exports.specifiers.push({ - kind: "external", - local: local.name, - exported: exported, - source: source - }); - } + def("XMLAttribute") + .bases("XML") + .field("value", String); - if (!source) { - exports.specifiers.push({ - kind: "local", - local: local.name, - exported: exported - }); - } - } - } + def("XMLCdata") + .bases("XML") + .field("contents", String); - if (path.isExportAllDeclaration()) { - exports.specifiers.push({ - kind: "external-all", - source: source - }); - } -} + def("XMLComment") + .bases("XML") + .field("contents", String); -function Scope(path) { - path.skip(); -} -},{"babel-runtime/core-js/get-iterator":89,"babel-types":145}],41:[function(require,module,exports){ -(function (process){ -"use strict"; + def("XMLProcessingInstruction") + .bases("XML") + .field("target", String) + .field("contents", or(String, null)); +}; +},{"../lib/types":59,"./core":44}],46:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./core")); + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(require("../lib/shared")).defaults; -exports.__esModule = true; + def("Function") + .field("generator", Boolean, defaults["false"]) + .field("expression", Boolean, defaults["false"]) + .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) + // TODO This could be represented as a RestElement in .params. + .field("rest", or(def("Identifier"), null), defaults["null"]); -var _assign = require("babel-runtime/core-js/object/assign"); + // The ESTree way of representing a ...rest parameter. + def("RestElement") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")); -var _assign2 = _interopRequireDefault(_assign); + def("SpreadElementPattern") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + def("FunctionDeclaration") + .build("id", "params", "body", "generator", "expression"); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + def("FunctionExpression") + .build("id", "params", "body", "generator", "expression"); -exports.default = buildConfigChain; + // The Parser API calls this ArrowExpression, but Esprima and all other + // actual parsers use ArrowFunctionExpression. + def("ArrowFunctionExpression") + .bases("Function", "Expression") + .build("params", "body", "expression") + // The forced null value here is compatible with the overridden + // definition of the "id" field in the Function interface. + .field("id", null, defaults["null"]) + // Arrow function bodies are allowed to be expressions. + .field("body", or(def("BlockStatement"), def("Expression"))) + // The current spec forbids arrow generators, so I have taken the + // liberty of enforcing that. TODO Report this. + .field("generator", false, defaults["false"]); -var _resolve = require("../../../helpers/resolve"); + def("YieldExpression") + .bases("Expression") + .build("argument", "delegate") + .field("argument", or(def("Expression"), null)) + .field("delegate", Boolean, defaults["false"]); -var _resolve2 = _interopRequireDefault(_resolve); + def("GeneratorExpression") + .bases("Expression") + .build("body", "blocks", "filter") + .field("body", def("Expression")) + .field("blocks", [def("ComprehensionBlock")]) + .field("filter", or(def("Expression"), null)); -var _json = require("json5"); + def("ComprehensionExpression") + .bases("Expression") + .build("body", "blocks", "filter") + .field("body", def("Expression")) + .field("blocks", [def("ComprehensionBlock")]) + .field("filter", or(def("Expression"), null)); -var _json2 = _interopRequireDefault(_json); + def("ComprehensionBlock") + .bases("Node") + .build("left", "right", "each") + .field("left", def("Pattern")) + .field("right", def("Expression")) + .field("each", Boolean); -var _pathIsAbsolute = require("path-is-absolute"); + def("Property") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("value", or(def("Expression"), def("Pattern"))) + .field("method", Boolean, defaults["false"]) + .field("shorthand", Boolean, defaults["false"]) + .field("computed", Boolean, defaults["false"]); -var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); + def("PropertyPattern") + .bases("Pattern") + .build("key", "pattern") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("pattern", def("Pattern")) + .field("computed", Boolean, defaults["false"]); -var _path = require("path"); + def("ObjectPattern") + .bases("Pattern") + .build("properties") + .field("properties", [or(def("PropertyPattern"), def("Property"))]); -var _path2 = _interopRequireDefault(_path); + def("ArrayPattern") + .bases("Pattern") + .build("elements") + .field("elements", [or(def("Pattern"), null)]); -var _fs = require("fs"); + def("MethodDefinition") + .bases("Declaration") + .build("kind", "key", "value", "static") + .field("kind", or("constructor", "method", "get", "set")) + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("value", def("Function")) + .field("computed", Boolean, defaults["false"]) + .field("static", Boolean, defaults["false"]); -var _fs2 = _interopRequireDefault(_fs); + def("SpreadElement") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + def("ArrayExpression") + .field("elements", [or( + def("Expression"), + def("SpreadElement"), + def("RestElement"), + null + )]); -var existsCache = {}; -var jsonCache = {}; + def("NewExpression") + .field("arguments", [or(def("Expression"), def("SpreadElement"))]); -var BABELIGNORE_FILENAME = ".babelignore"; -var BABELRC_FILENAME = ".babelrc"; -var PACKAGE_FILENAME = "package.json"; + def("CallExpression") + .field("arguments", [or(def("Expression"), def("SpreadElement"))]); -function exists(filename) { - var cached = existsCache[filename]; - if (cached == null) { - return existsCache[filename] = _fs2.default.existsSync(filename); - } else { - return cached; - } -} + // Note: this node type is *not* an AssignmentExpression with a Pattern on + // the left-hand side! The existing AssignmentExpression type already + // supports destructuring assignments. AssignmentPattern nodes may appear + // wherever a Pattern is allowed, and the right-hand side represents a + // default value to be destructured against the left-hand side, if no + // value is otherwise provided. For example: default parameter values. + def("AssignmentPattern") + .bases("Pattern") + .build("left", "right") + .field("left", def("Pattern")) + .field("right", def("Expression")); -function buildConfigChain() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var log = arguments[1]; + var ClassBodyElement = or( + def("MethodDefinition"), + def("VariableDeclarator"), + def("ClassPropertyDefinition"), + def("ClassProperty") + ); - var filename = opts.filename; - var builder = new ConfigChainBuilder(log); + def("ClassProperty") + .bases("Declaration") + .build("key") + .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) + .field("computed", Boolean, defaults["false"]); - if (opts.babelrc !== false) { - builder.findConfigs(filename); - } + def("ClassPropertyDefinition") // static property + .bases("Declaration") + .build("definition") + // Yes, Virginia, circular definitions are permitted. + .field("definition", ClassBodyElement); - builder.mergeConfig({ - options: opts, - alias: "base", - dirname: filename && _path2.default.dirname(filename) - }); + def("ClassBody") + .bases("Declaration") + .build("body") + .field("body", [ClassBodyElement]); - return builder.configs; -} + def("ClassDeclaration") + .bases("Declaration") + .build("id", "body", "superClass") + .field("id", or(def("Identifier"), null)) + .field("body", def("ClassBody")) + .field("superClass", or(def("Expression"), null), defaults["null"]); -var ConfigChainBuilder = function () { - function ConfigChainBuilder(log) { - (0, _classCallCheck3.default)(this, ConfigChainBuilder); + def("ClassExpression") + .bases("Expression") + .build("id", "body", "superClass") + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("body", def("ClassBody")) + .field("superClass", or(def("Expression"), null), defaults["null"]) + .field("implements", [def("ClassImplements")], defaults.emptyArray); - this.resolvedConfigs = []; - this.configs = []; - this.log = log; - } + def("ClassImplements") + .bases("Node") + .build("id") + .field("id", def("Identifier")) + .field("superClass", or(def("Expression"), null), defaults["null"]); - ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { - if (!loc) return; + // Specifier and ModuleSpecifier are abstract non-standard types + // introduced for definitional convenience. + def("Specifier").bases("Node"); - if (!(0, _pathIsAbsolute2.default)(loc)) { - loc = _path2.default.join(process.cwd(), loc); - } + // This supertype is shared/abused by both def/babel.js and + // def/esprima.js. In the future, it will be possible to load only one set + // of definitions appropriate for a given parser, but until then we must + // rely on default functions to reconcile the conflicting AST formats. + def("ModuleSpecifier") + .bases("Specifier") + // This local field is used by Babel/Acorn. It should not technically + // be optional in the Babel/Acorn AST format, but it must be optional + // in the Esprima AST format. + .field("local", or(def("Identifier"), null), defaults["null"]) + // The id and name fields are used by Esprima. The id field should not + // technically be optional in the Esprima AST format, but it must be + // optional in the Babel/Acorn AST format. + .field("id", or(def("Identifier"), null), defaults["null"]) + .field("name", or(def("Identifier"), null), defaults["null"]); - var foundConfig = false; - var foundIgnore = false; + def("TaggedTemplateExpression") + .bases("Expression") + .build("tag", "quasi") + .field("tag", def("Expression")) + .field("quasi", def("TemplateLiteral")); - while (loc !== (loc = _path2.default.dirname(loc))) { - if (!foundConfig) { - var configLoc = _path2.default.join(loc, BABELRC_FILENAME); - if (exists(configLoc)) { - this.addConfig(configLoc); - foundConfig = true; - } + def("TemplateLiteral") + .bases("Expression") + .build("quasis", "expressions") + .field("quasis", [def("TemplateElement")]) + .field("expressions", [def("Expression")]); - var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME); - if (!foundConfig && exists(pkgLoc)) { - foundConfig = this.addConfig(pkgLoc, "babel", JSON); - } - } - - if (!foundIgnore) { - var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME); - if (exists(ignoreLoc)) { - this.addIgnoreConfig(ignoreLoc); - foundIgnore = true; - } - } + def("TemplateElement") + .bases("Node") + .build("value", "tail") + .field("value", {"cooked": String, "raw": String}) + .field("tail", Boolean); +}; - if (foundIgnore && foundConfig) return; - } - }; +},{"../lib/shared":58,"../lib/types":59,"./core":44}],47:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require('./es6')); - ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) { - var file = _fs2.default.readFileSync(loc, "utf8"); - var lines = file.split("\n"); + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; + var builtin = types.builtInTypes; + var defaults = fork.use(require("../lib/shared")).defaults; - lines = lines.map(function (line) { - return line.replace(/#(.*?)$/, "").trim(); - }).filter(function (line) { - return !!line; - }); + def("Function") + .field("async", Boolean, defaults["false"]); - if (lines.length) { - this.mergeConfig({ - options: { ignore: lines }, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - } - }; + def("SpreadProperty") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); - ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { - var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default; + def("ObjectExpression") + .field("properties", [or(def("Property"), def("SpreadProperty"))]); - if (this.resolvedConfigs.indexOf(loc) >= 0) { - return false; - } + def("SpreadPropertyPattern") + .bases("Pattern") + .build("argument") + .field("argument", def("Pattern")); - this.resolvedConfigs.push(loc); + def("ObjectPattern") + .field("properties", [or( + def("Property"), + def("PropertyPattern"), + def("SpreadPropertyPattern") + )]); - var content = _fs2.default.readFileSync(loc, "utf8"); - var options = void 0; + def("AwaitExpression") + .bases("Expression") + .build("argument", "all") + .field("argument", or(def("Expression"), null)) + .field("all", Boolean, defaults["false"]); +}; +},{"../lib/shared":58,"../lib/types":59,"./es6":46}],48:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./es7")); - try { - options = jsonCache[content] = jsonCache[content] || json.parse(content); - if (key) options = options[key]; - } catch (err) { - err.message = loc + ": Error while parsing JSON - " + err.message; - throw err; - } + var types = fork.use(require("../lib/types")); + var defaults = fork.use(require("../lib/shared")).defaults; + var def = types.Type.def; + var or = types.Type.or; - this.mergeConfig({ - options: options, - alias: loc, - dirname: _path2.default.dirname(loc) - }); + def("VariableDeclaration") + .field("declarations", [or( + def("VariableDeclarator"), + def("Identifier") // Esprima deviation. + )]); - return !!options; - }; + def("Property") + .field("value", or( + def("Expression"), + def("Pattern") // Esprima deviation. + )); - ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { - var options = _ref.options, - alias = _ref.alias, - loc = _ref.loc, - dirname = _ref.dirname; + def("ArrayPattern") + .field("elements", [or( + def("Pattern"), + def("SpreadElement"), + null + )]); - if (!options) { - return false; - } + def("ObjectPattern") + .field("properties", [or( + def("Property"), + def("PropertyPattern"), + def("SpreadPropertyPattern"), + def("SpreadProperty") // Used by Esprima. + )]); - options = (0, _assign2.default)({}, options); +// Like ModuleSpecifier, except type:"ExportSpecifier" and buildable. +// export {} [from ...]; + def("ExportSpecifier") + .bases("ModuleSpecifier") + .build("id", "name"); - dirname = dirname || process.cwd(); - loc = loc || alias; +// export <*> from ...; + def("ExportBatchSpecifier") + .bases("Specifier") + .build(); - if (options.extends) { - var extendsLoc = (0, _resolve2.default)(options.extends, dirname); - if (extendsLoc) { - this.addConfig(extendsLoc); - } else { - if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); - } - delete options.extends; - } +// Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. +// import {} from ...; + def("ImportSpecifier") + .bases("ModuleSpecifier") + .build("id", "name"); - this.configs.push({ - options: options, - alias: alias, - loc: loc, - dirname: dirname - }); +// import <* as id> from ...; + def("ImportNamespaceSpecifier") + .bases("ModuleSpecifier") + .build("id"); - var envOpts = void 0; - var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; - if (options.env) { - envOpts = options.env[envKey]; - delete options.env; - } +// import from ...; + def("ImportDefaultSpecifier") + .bases("ModuleSpecifier") + .build("id"); - this.mergeConfig({ - options: envOpts, - alias: alias + ".env." + envKey, - dirname: dirname - }); - }; + def("ExportDeclaration") + .bases("Declaration") + .build("default", "declaration", "specifiers", "source") + .field("default", Boolean) + .field("declaration", or( + def("Declaration"), + def("Expression"), // Implies default. + null + )) + .field("specifiers", [or( + def("ExportSpecifier"), + def("ExportBatchSpecifier") + )], defaults.emptyArray) + .field("source", or( + def("Literal"), + null + ), defaults["null"]); - return ConfigChainBuilder; -}(); + def("ImportDeclaration") + .bases("Declaration") + .build("specifiers", "source", "importKind") + .field("specifiers", [or( + def("ImportSpecifier"), + def("ImportNamespaceSpecifier"), + def("ImportDefaultSpecifier") + )], defaults.emptyArray) + .field("source", def("Literal")) + .field("importKind", or( + "value", + "type" + ), function() { + return "value"; + }); -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../helpers/resolve":35,"_process":803,"babel-runtime/core-js/object/assign":93,"babel-runtime/helpers/classCallCheck":103,"fs":790,"json5":288,"path":801,"path-is-absolute":509}],42:[function(require,module,exports){ -"use strict"; + def("Block") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); -module.exports = { - filename: { - type: "filename", - description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", - default: "unknown", - shorthand: "f" - }, + def("Line") + .bases("Comment") + .build("value", /*optional:*/ "leading", "trailing"); +}; +},{"../lib/shared":58,"../lib/types":59,"./es7":47}],49:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./es7")); - filenameRelative: { - hidden: true, - type: "string" - }, + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(require("../lib/shared")).defaults; - inputSourceMap: { - hidden: true - }, + // Type Annotations + def("Type").bases("Node"); - env: { - hidden: true, - default: {} - }, + def("AnyTypeAnnotation") + .bases("Type") + .build(); - mode: { - description: "", - hidden: true - }, + def("EmptyTypeAnnotation") + .bases("Type") + .build(); - retainLines: { - type: "boolean", - default: false, - description: "retain line numbers - will result in really ugly code" - }, + def("MixedTypeAnnotation") + .bases("Type") + .build(); - highlightCode: { - description: "enable/disable ANSI syntax highlighting of code frames (on by default)", - type: "boolean", - default: true - }, + def("VoidTypeAnnotation") + .bases("Type") + .build(); - suppressDeprecationMessages: { - type: "boolean", - default: false, - hidden: true - }, + def("NumberTypeAnnotation") + .bases("Type") + .build(); - presets: { - type: "list", - description: "", - default: [] - }, + def("NumberLiteralTypeAnnotation") + .bases("Type") + .build("value", "raw") + .field("value", Number) + .field("raw", String); - plugins: { - type: "list", - default: [], - description: "" - }, + // Babylon 6 differs in AST from Flow + // same as NumberLiteralTypeAnnotation + def("NumericLiteralTypeAnnotation") + .bases("Type") + .build("value", "raw") + .field("value", Number) + .field("raw", String); - ignore: { - type: "list", - description: "list of glob paths to **not** compile", - default: [] - }, + def("StringTypeAnnotation") + .bases("Type") + .build(); - only: { - type: "list", - description: "list of glob paths to **only** compile" - }, + def("StringLiteralTypeAnnotation") + .bases("Type") + .build("value", "raw") + .field("value", String) + .field("raw", String); - code: { - hidden: true, - default: true, - type: "boolean" - }, + def("BooleanTypeAnnotation") + .bases("Type") + .build(); - metadata: { - hidden: true, - default: true, - type: "boolean" - }, + def("BooleanLiteralTypeAnnotation") + .bases("Type") + .build("value", "raw") + .field("value", Boolean) + .field("raw", String); - ast: { - hidden: true, - default: true, - type: "boolean" - }, + def("TypeAnnotation") + .bases("Node") + .build("typeAnnotation") + .field("typeAnnotation", def("Type")); - extends: { - type: "string", - hidden: true - }, + def("NullableTypeAnnotation") + .bases("Type") + .build("typeAnnotation") + .field("typeAnnotation", def("Type")); - comments: { - type: "boolean", - default: true, - description: "write comments to generated output (true by default)" - }, + def("NullLiteralTypeAnnotation") + .bases("Type") + .build(); - shouldPrintComment: { - hidden: true, - description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" - }, + def("NullTypeAnnotation") + .bases("Type") + .build(); - wrapPluginVisitorMethod: { - hidden: true, - description: "optional callback to wrap all visitor methods" - }, + def("ThisTypeAnnotation") + .bases("Type") + .build(); - compact: { - type: "booleanString", - default: "auto", - description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" - }, + def("ExistsTypeAnnotation") + .bases("Type") + .build(); - minified: { - type: "boolean", - default: false, - description: "save as much bytes when printing [true|false]" - }, + def("ExistentialTypeParam") + .bases("Type") + .build(); - sourceMap: { - alias: "sourceMaps", - hidden: true - }, + def("FunctionTypeAnnotation") + .bases("Type") + .build("params", "returnType", "rest", "typeParameters") + .field("params", [def("FunctionTypeParam")]) + .field("returnType", def("Type")) + .field("rest", or(def("FunctionTypeParam"), null)) + .field("typeParameters", or(def("TypeParameterDeclaration"), null)); - sourceMaps: { - type: "booleanString", - description: "[true|false|inline]", - default: false, - shorthand: "s" - }, + def("FunctionTypeParam") + .bases("Node") + .build("name", "typeAnnotation", "optional") + .field("name", def("Identifier")) + .field("typeAnnotation", def("Type")) + .field("optional", Boolean); - sourceMapTarget: { - type: "string", - description: "set `file` on returned source map" - }, + def("ArrayTypeAnnotation") + .bases("Type") + .build("elementType") + .field("elementType", def("Type")); - sourceFileName: { - type: "string", - description: "set `sources[0]` on returned source map" - }, + def("ObjectTypeAnnotation") + .bases("Type") + .build("properties", "indexers", "callProperties") + .field("properties", [def("ObjectTypeProperty")]) + .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray) + .field("callProperties", + [def("ObjectTypeCallProperty")], + defaults.emptyArray) + .field("exact", Boolean, defaults["false"]); - sourceRoot: { - type: "filename", - description: "the root from which all sources are relative" - }, + def("ObjectTypeProperty") + .bases("Node") + .build("key", "value", "optional") + .field("key", or(def("Literal"), def("Identifier"))) + .field("value", def("Type")) + .field("optional", Boolean) + .field("variance", + or("plus", "minus", null), + defaults["null"]); - babelrc: { - description: "Whether or not to look up .babelrc and .babelignore files", - type: "boolean", - default: true - }, + def("ObjectTypeIndexer") + .bases("Node") + .build("id", "key", "value") + .field("id", def("Identifier")) + .field("key", def("Type")) + .field("value", def("Type")) + .field("variance", + or("plus", "minus", null), + defaults["null"]); - sourceType: { - description: "", - default: "module" - }, + def("ObjectTypeCallProperty") + .bases("Node") + .build("value") + .field("value", def("FunctionTypeAnnotation")) + .field("static", Boolean, defaults["false"]); - auxiliaryCommentBefore: { - type: "string", - description: "print a comment before any injected non-user code" - }, + def("QualifiedTypeIdentifier") + .bases("Node") + .build("qualification", "id") + .field("qualification", + or(def("Identifier"), + def("QualifiedTypeIdentifier"))) + .field("id", def("Identifier")); - auxiliaryCommentAfter: { - type: "string", - description: "print a comment after any injected non-user code" - }, + def("GenericTypeAnnotation") + .bases("Type") + .build("id", "typeParameters") + .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))) + .field("typeParameters", or(def("TypeParameterInstantiation"), null)); - resolveModuleSource: { - hidden: true - }, + def("MemberTypeAnnotation") + .bases("Type") + .build("object", "property") + .field("object", def("Identifier")) + .field("property", + or(def("MemberTypeAnnotation"), + def("GenericTypeAnnotation"))); - getModuleId: { - hidden: true - }, + def("UnionTypeAnnotation") + .bases("Type") + .build("types") + .field("types", [def("Type")]); - moduleRoot: { - type: "filename", - description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" - }, - - moduleIds: { - type: "boolean", - default: false, - shorthand: "M", - description: "insert an explicit id for modules" - }, + def("IntersectionTypeAnnotation") + .bases("Type") + .build("types") + .field("types", [def("Type")]); - moduleId: { - description: "specify a custom name for module ids", - type: "string" - }, + def("TypeofTypeAnnotation") + .bases("Type") + .build("argument") + .field("argument", def("Type")); - passPerPreset: { - description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.", - type: "boolean", - default: false, - hidden: true - }, + def("Identifier") + .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]); - parserOpts: { - description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", - default: false - }, + def("TypeParameterDeclaration") + .bases("Node") + .build("params") + .field("params", [def("TypeParameter")]); - generatorOpts: { - description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", - default: false - } -}; -},{}],43:[function(require,module,exports){ -"use strict"; + def("TypeParameterInstantiation") + .bases("Node") + .build("params") + .field("params", [def("Type")]); -exports.__esModule = true; -exports.config = undefined; -exports.normaliseOptions = normaliseOptions; + def("TypeParameter") + .bases("Type") + .build("name", "variance", "bound") + .field("name", String) + .field("variance", + or("plus", "minus", null), + defaults["null"]) + .field("bound", + or(def("TypeAnnotation"), null), + defaults["null"]); -var _parsers = require("./parsers"); + def("Function") + .field("returnType", + or(def("TypeAnnotation"), null), + defaults["null"]) + .field("typeParameters", + or(def("TypeParameterDeclaration"), null), + defaults["null"]); -var parsers = _interopRequireWildcard(_parsers); + def("ClassProperty") + .build("key", "value", "typeAnnotation", "static") + .field("value", or(def("Expression"), null)) + .field("typeAnnotation", or(def("TypeAnnotation"), null)) + .field("static", Boolean, defaults["false"]) + .field("variance", + or("plus", "minus", null), + defaults["null"]); -var _config = require("./config"); + def("ClassImplements") + .field("typeParameters", + or(def("TypeParameterInstantiation"), null), + defaults["null"]); -var _config2 = _interopRequireDefault(_config); + def("InterfaceDeclaration") + .bases("Declaration") + .build("id", "body", "extends") + .field("id", def("Identifier")) + .field("typeParameters", + or(def("TypeParameterDeclaration"), null), + defaults["null"]) + .field("body", def("ObjectTypeAnnotation")) + .field("extends", [def("InterfaceExtends")]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + def("DeclareInterface") + .bases("InterfaceDeclaration") + .build("id", "body", "extends"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + def("InterfaceExtends") + .bases("Node") + .build("id") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterInstantiation"), null)); -exports.config = _config2.default; -function normaliseOptions() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + def("TypeAlias") + .bases("Declaration") + .build("id", "typeParameters", "right") + .field("id", def("Identifier")) + .field("typeParameters", or(def("TypeParameterDeclaration"), null)) + .field("right", def("Type")); - for (var key in options) { - var val = options[key]; - if (val == null) continue; + def("DeclareTypeAlias") + .bases("TypeAlias") + .build("id", "typeParameters", "right"); - var opt = _config2.default[key]; - if (opt && opt.alias) opt = _config2.default[opt.alias]; - if (!opt) continue; + def("TypeCastExpression") + .bases("Expression") + .build("expression", "typeAnnotation") + .field("expression", def("Expression")) + .field("typeAnnotation", def("TypeAnnotation")); - var parser = parsers[opt.type]; - if (parser) val = parser(val); + def("TupleTypeAnnotation") + .bases("Type") + .build("types") + .field("types", [def("Type")]); - options[key] = val; - } + def("DeclareVariable") + .bases("Statement") + .build("id") + .field("id", def("Identifier")); - return options; -} -},{"./config":42,"./parsers":45}],44:[function(require,module,exports){ -(function (process){ -"use strict"; + def("DeclareFunction") + .bases("Statement") + .build("id") + .field("id", def("Identifier")); -exports.__esModule = true; + def("DeclareClass") + .bases("InterfaceDeclaration") + .build("id"); -var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties"); + def("DeclareModule") + .bases("Statement") + .build("id", "body") + .field("id", or(def("Identifier"), def("Literal"))) + .field("body", def("BlockStatement")); -var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); + def("DeclareModuleExports") + .bases("Statement") + .build("typeAnnotation") + .field("typeAnnotation", def("Type")); -var _stringify = require("babel-runtime/core-js/json/stringify"); + def("DeclareExportDeclaration") + .bases("Declaration") + .build("default", "declaration", "specifiers", "source") + .field("default", Boolean) + .field("declaration", or( + def("DeclareVariable"), + def("DeclareFunction"), + def("DeclareClass"), + def("Type"), // Implies default. + null + )) + .field("specifiers", [or( + def("ExportSpecifier"), + def("ExportBatchSpecifier") + )], defaults.emptyArray) + .field("source", or( + def("Literal"), + null + ), defaults["null"]); -var _stringify2 = _interopRequireDefault(_stringify); + def("DeclareExportAllDeclaration") + .bases("Declaration") + .build("source") + .field("source", or( + def("Literal"), + null + ), defaults["null"]); +}; -var _assign = require("babel-runtime/core-js/object/assign"); +},{"../lib/shared":58,"../lib/types":59,"./es7":47}],50:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./es7")); -var _assign2 = _interopRequireDefault(_assign); + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; + var defaults = fork.use(require("../lib/shared")).defaults; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + def("JSXAttribute") + .bases("Node") + .build("name", "value") + .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))) + .field("value", or( + def("Literal"), // attr="value" + def("JSXExpressionContainer"), // attr={value} + null // attr= or just attr + ), defaults["null"]); -var _getIterator3 = _interopRequireDefault(_getIterator2); + def("JSXIdentifier") + .bases("Identifier") + .build("name") + .field("name", String); -var _typeof2 = require("babel-runtime/helpers/typeof"); + def("JSXNamespacedName") + .bases("Node") + .build("namespace", "name") + .field("namespace", def("JSXIdentifier")) + .field("name", def("JSXIdentifier")); -var _typeof3 = _interopRequireDefault(_typeof2); + def("JSXMemberExpression") + .bases("MemberExpression") + .build("object", "property") + .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))) + .field("property", def("JSXIdentifier")) + .field("computed", Boolean, defaults.false); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var JSXElementName = or( + def("JSXIdentifier"), + def("JSXNamespacedName"), + def("JSXMemberExpression") + ); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + def("JSXSpreadAttribute") + .bases("Node") + .build("argument") + .field("argument", def("Expression")); -var _node = require("../../../api/node"); + var JSXAttributes = [or( + def("JSXAttribute"), + def("JSXSpreadAttribute") + )]; -var context = _interopRequireWildcard(_node); + def("JSXExpressionContainer") + .bases("Expression") + .build("expression") + .field("expression", def("Expression")); -var _plugin2 = require("../../plugin"); + def("JSXElement") + .bases("Expression") + .build("openingElement", "closingElement", "children") + .field("openingElement", def("JSXOpeningElement")) + .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]) + .field("children", [or( + def("JSXElement"), + def("JSXExpressionContainer"), + def("JSXText"), + def("Literal") // TODO Esprima should return JSXText instead. + )], defaults.emptyArray) + .field("name", JSXElementName, function () { + // Little-known fact: the `this` object inside a default function + // is none other than the partially-built object itself, and any + // fields initialized directly from builder function arguments + // (like openingElement, closingElement, and children) are + // guaranteed to be available. + return this.openingElement.name; + }, true) // hidden from traversal + .field("selfClosing", Boolean, function () { + return this.openingElement.selfClosing; + }, true) // hidden from traversal + .field("attributes", JSXAttributes, function () { + return this.openingElement.attributes; + }, true); // hidden from traversal -var _plugin3 = _interopRequireDefault(_plugin2); + def("JSXOpeningElement") + .bases("Node") // TODO Does this make sense? Can't really be an JSXElement. + .build("name", "attributes", "selfClosing") + .field("name", JSXElementName) + .field("attributes", JSXAttributes, defaults.emptyArray) + .field("selfClosing", Boolean, defaults["false"]); -var _babelMessages = require("babel-messages"); + def("JSXClosingElement") + .bases("Node") // TODO Same concern. + .build("name") + .field("name", JSXElementName); -var messages = _interopRequireWildcard(_babelMessages); + def("JSXText") + .bases("Literal") + .build("value") + .field("value", String); -var _index = require("./index"); + def("JSXEmptyExpression").bases("Expression").build(); -var _resolvePlugin = require("../../../helpers/resolve-plugin"); +}; +},{"../lib/shared":58,"../lib/types":59,"./es7":47}],51:[function(require,module,exports){ +module.exports = function (fork) { + fork.use(require("./core")); + var types = fork.use(require("../lib/types")); + var def = types.Type.def; + var or = types.Type.or; + var shared = fork.use(require("../lib/shared")); + var geq = shared.geq; + var defaults = shared.defaults; -var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin); + def("Function") + // SpiderMonkey allows expression closures: function(x) x+1 + .field("body", or(def("BlockStatement"), def("Expression"))); -var _resolvePreset = require("../../../helpers/resolve-preset"); + def("ForInStatement") + .build("left", "right", "body", "each") + .field("each", Boolean, defaults["false"]); -var _resolvePreset2 = _interopRequireDefault(_resolvePreset); + def("ForOfStatement") + .bases("Statement") + .build("left", "right", "body") + .field("left", or( + def("VariableDeclaration"), + def("Expression"))) + .field("right", def("Expression")) + .field("body", def("Statement")); -var _cloneDeepWith = require("lodash/cloneDeepWith"); + def("LetStatement") + .bases("Statement") + .build("head", "body") + // TODO Deviating from the spec by reusing VariableDeclarator here. + .field("head", [def("VariableDeclarator")]) + .field("body", def("Statement")); -var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); + def("LetExpression") + .bases("Expression") + .build("head", "body") + // TODO Deviating from the spec by reusing VariableDeclarator here. + .field("head", [def("VariableDeclarator")]) + .field("body", def("Expression")); -var _clone = require("lodash/clone"); + def("GraphExpression") + .bases("Expression") + .build("index", "expression") + .field("index", geq(0)) + .field("expression", def("Literal")); -var _clone2 = _interopRequireDefault(_clone); + def("GraphIndexExpression") + .bases("Expression") + .build("index") + .field("index", geq(0)); +}; +},{"../lib/shared":58,"../lib/types":59,"./core":44}],52:[function(require,module,exports){ +module.exports = function (defs) { + var used = []; + var usedResult = []; + var fork = {}; -var _merge = require("../../../helpers/merge"); + function use(plugin) { + var idx = used.indexOf(plugin); + if (idx === -1) { + idx = used.length; + used.push(plugin); + usedResult[idx] = plugin(fork); + } + return usedResult[idx]; + } -var _merge2 = _interopRequireDefault(_merge); + fork.use = use; -var _config2 = require("./config"); + var types = use(require('./lib/types')); -var _config3 = _interopRequireDefault(_config2); + defs.forEach(use); -var _removed = require("./removed"); + types.finalize(); -var _removed2 = _interopRequireDefault(_removed); + var exports = { + Type: types.Type, + builtInTypes: types.builtInTypes, + namedTypes: types.namedTypes, + builders: types.builders, + defineMethod: types.defineMethod, + getFieldNames: types.getFieldNames, + getFieldValue: types.getFieldValue, + eachField: types.eachField, + someField: types.someField, + getSupertypeNames: types.getSupertypeNames, + astNodesAreEquivalent: use(require("./lib/equiv")), + finalize: types.finalize, + Path: use(require('./lib/path')), + NodePath: use(require("./lib/node-path")), + PathVisitor: use(require("./lib/path-visitor")), + use: use + }; -var _buildConfigChain = require("./build-config-chain"); + exports.visit = exports.PathVisitor.visit; -var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); + return exports; +}; +},{"./lib/equiv":53,"./lib/node-path":54,"./lib/path":56,"./lib/path-visitor":55,"./lib/types":59}],53:[function(require,module,exports){ +module.exports = function (fork) { + var types = fork.use(require('../lib/types')); + var getFieldNames = types.getFieldNames; + var getFieldValue = types.getFieldValue; + var isArray = types.builtInTypes.array; + var isObject = types.builtInTypes.object; + var isDate = types.builtInTypes.Date; + var isRegExp = types.builtInTypes.RegExp; + var hasOwn = Object.prototype.hasOwnProperty; -var _path = require("path"); + function astNodesAreEquivalent(a, b, problemPath) { + if (isArray.check(problemPath)) { + problemPath.length = 0; + } else { + problemPath = null; + } -var _path2 = _interopRequireDefault(_path); + return areEquivalent(a, b, problemPath); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + astNodesAreEquivalent.assert = function (a, b) { + var problemPath = []; + if (!astNodesAreEquivalent(a, b, problemPath)) { + if (problemPath.length === 0) { + if (a !== b) { + throw new Error("Nodes must be equal"); + } + } else { + throw new Error( + "Nodes differ in the following path: " + + problemPath.map(subscriptForProperty).join("") + ); + } + } + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function subscriptForProperty(property) { + if (/[_$a-z][_$a-z0-9]*/i.test(property)) { + return "." + property; + } + return "[" + JSON.stringify(property) + "]"; + } -var OptionManager = function () { - function OptionManager(log) { - (0, _classCallCheck3.default)(this, OptionManager); + function areEquivalent(a, b, problemPath) { + if (a === b) { + return true; + } - this.resolvedConfigs = []; - this.options = OptionManager.createBareOptions(); - this.log = log; - } + if (isArray.check(a)) { + return arraysAreEquivalent(a, b, problemPath); + } - OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { - for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (isObject.check(a)) { + return objectsAreEquivalent(a, b, problemPath); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (isDate.check(a)) { + return isDate.check(b) && (+a === +b); + } - var cache = _ref; + if (isRegExp.check(a)) { + return isRegExp.check(b) && ( + a.source === b.source && + a.global === b.global && + a.multiline === b.multiline && + a.ignoreCase === b.ignoreCase + ); + } - if (cache.container === fn) return cache.plugin; + return a == b; } - var obj = void 0; + function arraysAreEquivalent(a, b, problemPath) { + isArray.assert(a); + var aLength = a.length; - if (typeof fn === "function") { - obj = fn(context); - } else { - obj = fn; - } + if (!isArray.check(b) || b.length !== aLength) { + if (problemPath) { + problemPath.push("length"); + } + return false; + } - if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") { - var _plugin = new _plugin3.default(obj, alias); - OptionManager.memoisedPlugins.push({ - container: fn, - plugin: _plugin - }); - return _plugin; - } else { - throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); - } - }; + for (var i = 0; i < aLength; ++i) { + if (problemPath) { + problemPath.push(i); + } - OptionManager.createBareOptions = function createBareOptions() { - var opts = {}; + if (i in a !== i in b) { + return false; + } - for (var _key in _config3.default) { - var opt = _config3.default[_key]; - opts[_key] = (0, _clone2.default)(opt.default); - } - - return opts; - }; + if (!areEquivalent(a[i], b[i], problemPath)) { + return false; + } - OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { - plugin = plugin.__esModule ? plugin.default : plugin; + if (problemPath) { + var problemPathTail = problemPath.pop(); + if (problemPathTail !== i) { + throw new Error("" + problemPathTail); + } + } + } - if (!(plugin instanceof _plugin3.default)) { - if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { - plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); - } else { - throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); - } + return true; } - plugin.init(loc, i); + function objectsAreEquivalent(a, b, problemPath) { + isObject.assert(a); + if (!isObject.check(b)) { + return false; + } - return plugin; - }; + // Fast path for a common property of AST nodes. + if (a.type !== b.type) { + if (problemPath) { + problemPath.push("type"); + } + return false; + } - OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { - return plugins.map(function (val, i) { - var plugin = void 0, - options = void 0; + var aNames = getFieldNames(a); + var aNameCount = aNames.length; - if (!val) { - throw new TypeError("Falsy value found in plugins"); - } + var bNames = getFieldNames(b); + var bNameCount = bNames.length; - if (Array.isArray(val)) { - plugin = val[0]; - options = val[1]; - } else { - plugin = val; - } + if (aNameCount === bNameCount) { + for (var i = 0; i < aNameCount; ++i) { + var name = aNames[i]; + var aChild = getFieldValue(a, name); + var bChild = getFieldValue(b, name); - var alias = typeof plugin === "string" ? plugin : loc + "$" + i; + if (problemPath) { + problemPath.push(name); + } - if (typeof plugin === "string") { - var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname); - if (pluginLoc) { - plugin = require(pluginLoc); - } else { - throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname)); - } - } + if (!areEquivalent(aChild, bChild, problemPath)) { + return false; + } - plugin = OptionManager.normalisePlugin(plugin, loc, i, alias); + if (problemPath) { + var problemPathTail = problemPath.pop(); + if (problemPathTail !== name) { + throw new Error("" + problemPathTail); + } + } + } - return [plugin, options]; - }); - }; + return true; + } - OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) { - var _this = this; + if (!problemPath) { + return false; + } - var rawOpts = _ref2.options, - extendingOpts = _ref2.extending, - alias = _ref2.alias, - loc = _ref2.loc, - dirname = _ref2.dirname; + // Since aNameCount !== bNameCount, we need to find some name that's + // missing in aNames but present in bNames, or vice-versa. - alias = alias || "foreign"; - if (!rawOpts) return; + var seenNames = Object.create(null); - if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { - this.log.error("Invalid options type for " + alias, TypeError); - } + for (i = 0; i < aNameCount; ++i) { + seenNames[aNames[i]] = true; + } - var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) { - if (val instanceof _plugin3.default) { - return val; - } - }); + for (i = 0; i < bNameCount; ++i) { + name = bNames[i]; - dirname = dirname || process.cwd(); - loc = loc || alias; + if (!hasOwn.call(seenNames, name)) { + problemPath.push(name); + return false; + } - for (var _key2 in opts) { - var option = _config3.default[_key2]; + delete seenNames[name]; + } - if (!option && this.log) { - if (_removed2.default[_key2]) { - this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError); - } else { - var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; - var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; + for (name in seenNames) { + problemPath.push(name); + break; + } + return false; + } + + return astNodesAreEquivalent; +}; - this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError); +},{"../lib/types":59}],54:[function(require,module,exports){ +module.exports = function (fork) { + var types = fork.use(require("./types")); + var n = types.namedTypes; + var b = types.builders; + var isNumber = types.builtInTypes.number; + var isArray = types.builtInTypes.array; + var Path = fork.use(require("./path")); + var Scope = fork.use(require("./scope")); + + function NodePath(value, parentPath, name) { + if (!(this instanceof NodePath)) { + throw new Error("NodePath constructor cannot be invoked without 'new'"); } - } + Path.call(this, value, parentPath, name); } - (0, _index.normaliseOptions)(opts); + var NPp = NodePath.prototype = Object.create(Path.prototype, { + constructor: { + value: NodePath, + enumerable: false, + writable: true, + configurable: true + } + }); - if (opts.plugins) { - opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); - } + Object.defineProperties(NPp, { + node: { + get: function () { + Object.defineProperty(this, "node", { + configurable: true, // Enable deletion. + value: this._computeNode() + }); - if (opts.presets) { - if (opts.passPerPreset) { - opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) { - _this.mergeOptions({ - options: preset, - extending: preset, - alias: presetLoc, - loc: presetLoc, - dirname: dirname - }); - }); - } else { - this.mergePresets(opts.presets, dirname); - delete opts.presets; - } - } + return this.node; + } + }, - if (rawOpts === extendingOpts) { - (0, _assign2.default)(extendingOpts, opts); - } else { - (0, _merge2.default)(extendingOpts || this.options, opts); - } - }; + parent: { + get: function () { + Object.defineProperty(this, "parent", { + configurable: true, // Enable deletion. + value: this._computeParent() + }); - OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { - var _this2 = this; + return this.parent; + } + }, - this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { - _this2.mergeOptions({ - options: presetOpts, - alias: presetLoc, - loc: presetLoc, - dirname: _path2.default.dirname(presetLoc || "") - }); - }); - }; + scope: { + get: function () { + Object.defineProperty(this, "scope", { + configurable: true, // Enable deletion. + value: this._computeScope() + }); - OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { - return presets.map(function (val) { - var options = void 0; - if (Array.isArray(val)) { - if (val.length > 2) { - throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); + return this.scope; + } } + }); - var _val = val; - val = _val[0]; - options = _val[1]; - } + NPp.replace = function () { + delete this.node; + delete this.parent; + delete this.scope; + return Path.prototype.replace.apply(this, arguments); + }; - var presetLoc = void 0; - try { - if (typeof val === "string") { - presetLoc = (0, _resolvePreset2.default)(val, dirname); + NPp.prune = function () { + var remainingNodePath = this.parent; - if (!presetLoc) { - throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); - } + this.replace(); - val = require(presetLoc); + return cleanUpNodesAfterPrune(remainingNodePath); + }; + + // The value of the first ancestor Path whose value is a Node. + NPp._computeNode = function () { + var value = this.value; + if (n.Node.check(value)) { + return value; } - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) { - if (val.default) { - val = val.default; - } else { - var _val2 = val, - __esModule = _val2.__esModule, - rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]); + var pp = this.parentPath; + return pp && pp.node || null; + }; - val = rest; - } - } + // The first ancestor Path whose value is a Node distinct from this.node. + NPp._computeParent = function () { + var value = this.value; + var pp = this.parentPath; - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; + if (!n.Node.check(value)) { + while (pp && !n.Node.check(pp.value)) { + pp = pp.parentPath; + } - if (typeof val !== "function" && options !== undefined) { - throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); + if (pp) { + pp = pp.parentPath; + } } - if (typeof val === "function") val = val(context, options, { dirname: dirname }); - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { - throw new Error("Unsupported preset format: " + val + "."); + while (pp && !n.Node.check(pp.value)) { + pp = pp.parentPath; } - onResolve && onResolve(val, presetLoc); - } catch (e) { - if (presetLoc) { - e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; + return pp || null; + }; + + // The closest enclosing scope that governs this node. + NPp._computeScope = function () { + var value = this.value; + var pp = this.parentPath; + var scope = pp && pp.scope; + + if (n.Node.check(value) && + Scope.isEstablishedBy(value)) { + scope = new Scope(this, scope); } - throw e; - } - return val; - }); - }; - OptionManager.prototype.normaliseOptions = function normaliseOptions() { - var opts = this.options; + return scope || null; + }; - for (var _key3 in _config3.default) { - var option = _config3.default[_key3]; - var val = opts[_key3]; + NPp.getValueProperty = function (name) { + return types.getFieldValue(this.value, name); + }; - if (!val && option.optional) continue; + /** + * Determine whether this.node needs to be wrapped in parentheses in order + * for a parser to reproduce the same local AST structure. + * + * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression + * whose operator is "+" needs parentheses, because `1 + 2 * 3` would + * parse differently. + * + * If assumeExpressionContext === true, we don't worry about edge cases + * like an anonymous FunctionExpression appearing lexically first in its + * enclosing statement and thus needing parentheses to avoid being parsed + * as a FunctionDeclaration with a missing name. + */ + NPp.needsParens = function (assumeExpressionContext) { + var pp = this.parentPath; + if (!pp) { + return false; + } - if (option.alias) { - opts[option.alias] = opts[option.alias] || val; - } else { - opts[_key3] = val; - } - } - }; + var node = this.value; - OptionManager.prototype.init = function init() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + // Only expressions need parentheses. + if (!n.Expression.check(node)) { + return false; + } - for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; + // Identifiers never need parentheses. + if (node.type === "Identifier") { + return false; + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } + while (!n.Node.check(pp.value)) { + pp = pp.parentPath; + if (!pp) { + return false; + } + } - var _config = _ref3; + var parent = pp.value; - this.mergeOptions(_config); - } + switch (node.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return parent.type === "MemberExpression" + && this.name === "object" + && parent.object === node; - this.normaliseOptions(opts); + case "BinaryExpression": + case "LogicalExpression": + switch (parent.type) { + case "CallExpression": + return this.name === "callee" + && parent.callee === node; - return this.options; - }; + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return true; - return OptionManager; -}(); + case "MemberExpression": + return this.name === "object" + && parent.object === node; -exports.default = OptionManager; + case "BinaryExpression": + case "LogicalExpression": + var po = parent.operator; + var pp = PRECEDENCE[po]; + var no = node.operator; + var np = PRECEDENCE[no]; + if (pp > np) { + return true; + } -OptionManager.memoisedPlugins = []; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../api/node":27,"../../../helpers/merge":30,"../../../helpers/resolve-plugin":33,"../../../helpers/resolve-preset":34,"../../plugin":51,"./build-config-chain":41,"./config":42,"./index":43,"./removed":46,"_process":803,"babel-messages":79,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/json/stringify":90,"babel-runtime/core-js/object/assign":93,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/objectWithoutProperties":105,"babel-runtime/helpers/typeof":107,"lodash/clone":455,"lodash/cloneDeepWith":457,"path":801}],45:[function(require,module,exports){ -"use strict"; + if (pp === np && this.name === "right") { + if (parent.right !== node) { + throw new Error("Nodes must be equal"); + } + return true; + } -exports.__esModule = true; -exports.filename = undefined; -exports.boolean = boolean; -exports.booleanString = booleanString; -exports.list = list; + default: + return false; + } -var _slash = require("slash"); + case "SequenceExpression": + switch (parent.type) { + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; -var _slash2 = _interopRequireDefault(_slash); + case "ExpressionStatement": + return this.name !== "expression"; -var _util = require("../../../util"); + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; + } -var util = _interopRequireWildcard(_util); + case "YieldExpression": + switch (parent.type) { + case "BinaryExpression": + case "LogicalExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "CallExpression": + case "MemberExpression": + case "NewExpression": + case "ConditionalExpression": + case "YieldExpression": + return true; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + default: + return false; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case "Literal": + return parent.type === "MemberExpression" + && isNumber.check(node.value) + && this.name === "object" + && parent.object === node; -var filename = exports.filename = _slash2.default; + case "AssignmentExpression": + case "ConditionalExpression": + switch (parent.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + return true; -function boolean(val) { - return !!val; -} + case "CallExpression": + return this.name === "callee" + && parent.callee === node; -function booleanString(val) { - return util.booleanify(val); -} + case "ConditionalExpression": + return this.name === "test" + && parent.test === node; -function list(val) { - return util.list(val); -} -},{"../../../util":52,"slash":523}],46:[function(require,module,exports){ -"use strict"; + case "MemberExpression": + return this.name === "object" + && parent.object === node; -module.exports = { - "auxiliaryComment": { - "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" - }, - "blacklist": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "breakConfig": { - "message": "This is not a necessary option in Babel 6" - }, - "experimental": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "externalHelpers": { - "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" - }, - "extra": { - "message": "" - }, - "jsxPragma": { - "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" - }, + default: + return false; + } - "loose": { - "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." - }, - "metadataUsedHelpers": { - "message": "Not required anymore as this is enabled by default" - }, - "modules": { - "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules" - }, - "nonStandard": { - "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" - }, - "optional": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "sourceMapName": { - "message": "Use the `sourceMapTarget` option" - }, - "stage": { - "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" - }, - "whitelist": { - "message": "Put the specific transforms you want in the `plugins` option" - } -}; -},{}],47:[function(require,module,exports){ -"use strict"; + default: + if (parent.type === "NewExpression" && + this.name === "callee" && + parent.callee === node) { + return containsCallExpression(node); + } + } -exports.__esModule = true; + if (assumeExpressionContext !== true && + !this.canBeFirstInStatement() && + this.firstInStatement()) + return true; -var _plugin = require("../plugin"); + return false; + }; -var _plugin2 = _interopRequireDefault(_plugin); + function isBinary(node) { + return n.BinaryExpression.check(node) + || n.LogicalExpression.check(node); + } -var _sortBy = require("lodash/sortBy"); + function isUnaryLike(node) { + return n.UnaryExpression.check(node) + // I considered making SpreadElement and SpreadProperty subtypes + // of UnaryExpression, but they're not really Expression nodes. + || (n.SpreadElement && n.SpreadElement.check(node)) + || (n.SpreadProperty && n.SpreadProperty.check(node)); + } -var _sortBy2 = _interopRequireDefault(_sortBy); + var PRECEDENCE = {}; + [["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ].forEach(function (tier, i) { + tier.forEach(function (op) { + PRECEDENCE[op] = i; + }); + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function containsCallExpression(node) { + if (n.CallExpression.check(node)) { + return true; + } -exports.default = new _plugin2.default({ + if (isArray.check(node)) { + return node.some(containsCallExpression); + } - name: "internal.blockHoist", + if (n.Node.check(node)) { + return types.someField(node, function (name, child) { + return containsCallExpression(child); + }); + } - visitor: { - Block: { - exit: function exit(_ref) { - var node = _ref.node; + return false; + } - var hasChange = false; - for (var i = 0; i < node.body.length; i++) { - var bodyNode = node.body[i]; - if (bodyNode && bodyNode._blockHoist != null) { - hasChange = true; - break; - } - } - if (!hasChange) return; + NPp.canBeFirstInStatement = function () { + var node = this.node; + return !n.FunctionExpression.check(node) + && !n.ObjectExpression.check(node); + }; - node.body = (0, _sortBy2.default)(node.body, function (bodyNode) { - var priority = bodyNode && bodyNode._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; + NPp.firstInStatement = function () { + return firstInStatement(this); + }; - return -1 * priority; - }); - } - } - } -}); -module.exports = exports["default"]; -},{"../plugin":51,"lodash/sortBy":495}],48:[function(require,module,exports){ -"use strict"; + function firstInStatement(path) { + for (var node, parent; path.parent; path = path.parent) { + node = path.node; + parent = path.parent.node; -exports.__esModule = true; + if (n.BlockStatement.check(parent) && + path.parent.name === "body" && + path.name === 0) { + if (parent.body[0] !== node) { + throw new Error("Nodes must be equal"); + } + return true; + } -var _symbol = require("babel-runtime/core-js/symbol"); + if (n.ExpressionStatement.check(parent) && + path.name === "expression") { + if (parent.expression !== node) { + throw new Error("Nodes must be equal"); + } + return true; + } -var _symbol2 = _interopRequireDefault(_symbol); + if (n.SequenceExpression.check(parent) && + path.parent.name === "expressions" && + path.name === 0) { + if (parent.expressions[0] !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -var _plugin = require("../plugin"); + if (n.CallExpression.check(parent) && + path.name === "callee") { + if (parent.callee !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -var _plugin2 = _interopRequireDefault(_plugin); + if (n.MemberExpression.check(parent) && + path.name === "object") { + if (parent.object !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -var _babelTypes = require("babel-types"); + if (n.ConditionalExpression.check(parent) && + path.name === "test") { + if (parent.test !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -var t = _interopRequireWildcard(_babelTypes); + if (isBinary(parent) && + path.name === "left") { + if (parent.left !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (n.UnaryExpression.check(parent) && + !parent.prefix && + path.name === "argument") { + if (parent.argument !== node) { + throw new Error("Nodes must be equal"); + } + continue; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return false; + } -var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); + return true; + } -var superVisitor = { - CallExpression: function CallExpression(path) { - if (!path.get("callee").isSuper()) return; + /** + * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up. + */ + function cleanUpNodesAfterPrune(remainingNodePath) { + if (n.VariableDeclaration.check(remainingNodePath.node)) { + var declarations = remainingNodePath.get('declarations').value; + if (!declarations || declarations.length === 0) { + return remainingNodePath.prune(); + } + } else if (n.ExpressionStatement.check(remainingNodePath.node)) { + if (!remainingNodePath.get('expression').value) { + return remainingNodePath.prune(); + } + } else if (n.IfStatement.check(remainingNodePath.node)) { + cleanUpIfStatementAfterPrune(remainingNodePath); + } - var node = path.node; + return remainingNodePath; + } - if (node[SUPER_THIS_BOUND]) return; - node[SUPER_THIS_BOUND] = true; + function cleanUpIfStatementAfterPrune(ifStatement) { + var testExpression = ifStatement.get('test').value; + var alternate = ifStatement.get('alternate').value; + var consequent = ifStatement.get('consequent').value; - path.replaceWith(t.assignmentExpression("=", this.id, node)); - } -}; + if (!consequent && !alternate) { + var testExpressionStatement = b.expressionStatement(testExpression); -exports.default = new _plugin2.default({ - name: "internal.shadowFunctions", + ifStatement.replace(testExpressionStatement); + } else if (!consequent && alternate) { + var negatedTestExpression = b.unaryExpression('!', testExpression, true); - visitor: { - ThisExpression: function ThisExpression(path) { - remap(path, "this"); - }, - ReferencedIdentifier: function ReferencedIdentifier(path) { - if (path.node.name === "arguments") { - remap(path, "arguments"); - } + if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') { + negatedTestExpression = testExpression.argument; + } + + ifStatement.get("test").replace(negatedTestExpression); + ifStatement.get("consequent").replace(alternate); + ifStatement.get("alternate").replace(); + } } - } -}); + return NodePath; +}; -function shouldShadow(path, shadowPath) { - if (path.is("_forceShadow")) { - return true; - } else { - return shadowPath; - } -} +},{"./path":56,"./scope":57,"./types":59}],55:[function(require,module,exports){ +var hasOwn = Object.prototype.hasOwnProperty; -function remap(path, key) { - var shadowPath = path.inShadow(key); - if (!shouldShadow(path, shadowPath)) return; +module.exports = function (fork) { + var types = fork.use(require("./types")); + var NodePath = fork.use(require("./node-path")); + var Printable = types.namedTypes.Printable; + var isArray = types.builtInTypes.array; + var isObject = types.builtInTypes.object; + var isFunction = types.builtInTypes.function; + var undefined; - var shadowFunction = path.node._shadowedFunctionLiteral; + function PathVisitor() { + if (!(this instanceof PathVisitor)) { + throw new Error( + "PathVisitor constructor cannot be invoked without 'new'" + ); + } - var currentFunction = void 0; - var passedShadowFunction = false; + // Permanent state. + this._reusableContextStack = []; - var fnPath = path.find(function (innerPath) { - if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { - return true; - } - if (path === innerPath) return false; - if (innerPath.isProgram() || innerPath.isFunction()) { - currentFunction = currentFunction || innerPath; + this._methodNameTable = computeMethodNameTable(this); + this._shouldVisitComments = + hasOwn.call(this._methodNameTable, "Block") || + hasOwn.call(this._methodNameTable, "Line"); + + this.Context = makeContextConstructor(this); + + // State reset every time PathVisitor.prototype.visit is called. + this._visiting = false; + this._changeReported = false; } - if (innerPath.isProgram()) { - passedShadowFunction = true; + function computeMethodNameTable(visitor) { + var typeNames = Object.create(null); - return true; - } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { - if (shadowFunction) { - if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; - } else { - if (!innerPath.is("shadow")) return true; - } + for (var methodName in visitor) { + if (/^visit[A-Z]/.test(methodName)) { + typeNames[methodName.slice("visit".length)] = true; + } + } - passedShadowFunction = true; - return false; + var supertypeTable = types.computeSupertypeLookupTable(typeNames); + var methodNameTable = Object.create(null); + + var typeNames = Object.keys(supertypeTable); + var typeNameCount = typeNames.length; + for (var i = 0; i < typeNameCount; ++i) { + var typeName = typeNames[i]; + methodName = "visit" + supertypeTable[typeName]; + if (isFunction.check(visitor[methodName])) { + methodNameTable[typeName] = methodName; + } + } + + return methodNameTable; } - return false; - }); + PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { + if (methods instanceof PathVisitor) { + return methods; + } - if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { - fnPath = path.findParent(function (p) { - return p.isProgram() || p.isFunction(); - }); - } + if (!isObject.check(methods)) { + // An empty visitor? + return new PathVisitor; + } - if (fnPath === currentFunction) return; + function Visitor() { + if (!(this instanceof Visitor)) { + throw new Error( + "Visitor constructor cannot be invoked without 'new'" + ); + } + PathVisitor.call(this); + } - if (!passedShadowFunction) return; + var Vp = Visitor.prototype = Object.create(PVp); + Vp.constructor = Visitor; - var cached = fnPath.getData(key); - if (cached) return path.replaceWith(cached); + extend(Vp, methods); + extend(Visitor, PathVisitor); - var id = path.scope.generateUidIdentifier(key); + isFunction.assert(Visitor.fromMethodsObject); + isFunction.assert(Visitor.visit); - fnPath.setData(key, id); + return new Visitor; + }; - var classPath = fnPath.findParent(function (p) { - return p.isClass(); - }); - var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); + function extend(target, source) { + for (var property in source) { + if (hasOwn.call(source, property)) { + target[property] = source[property]; + } + } - if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { - fnPath.scope.push({ id: id }); + return target; + } - fnPath.traverse(superVisitor, { id: id }); - } else { - var init = key === "this" ? t.thisExpression() : t.identifier(key); + PathVisitor.visit = function visit(node, methods) { + return PathVisitor.fromMethodsObject(methods).visit(node); + }; - if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction; + var PVp = PathVisitor.prototype; - fnPath.scope.push({ id: id, init: init }); - } + PVp.visit = function () { + if (this._visiting) { + throw new Error( + "Recursively calling visitor.visit(path) resets visitor state. " + + "Try this.visit(path) or this.traverse(path) instead." + ); + } - return path.replaceWith(id); -} -module.exports = exports["default"]; -},{"../plugin":51,"babel-runtime/core-js/symbol":98,"babel-types":145}],49:[function(require,module,exports){ -"use strict"; + // Private state that needs to be reset before every traversal. + this._visiting = true; + this._changeReported = false; + this._abortRequested = false; -exports.__esModule = true; + var argc = arguments.length; + var args = new Array(argc) + for (var i = 0; i < argc; ++i) { + args[i] = arguments[i]; + } -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (!(args[0] instanceof NodePath)) { + args[0] = new NodePath({root: args[0]}).get("root"); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + // Called with the same arguments as .visit. + this.reset.apply(this, args); -var _normalizeAst = require("../helpers/normalize-ast"); + try { + var root = this.visitWithoutReset(args[0]); + var didNotThrow = true; + } finally { + this._visiting = false; -var _normalizeAst2 = _interopRequireDefault(_normalizeAst); + if (!didNotThrow && this._abortRequested) { + // If this.visitWithoutReset threw an exception and + // this._abortRequested was set to true, return the root of + // the AST instead of letting the exception propagate, so that + // client code does not have to provide a try-catch block to + // intercept the AbortRequest exception. Other kinds of + // exceptions will propagate without being intercepted and + // rethrown by a catch block, so their stacks will accurately + // reflect the original throwing context. + return args[0].value; + } + } -var _plugin = require("./plugin"); + return root; + }; -var _plugin2 = _interopRequireDefault(_plugin); + PVp.AbortRequest = function AbortRequest() {}; + PVp.abort = function () { + var visitor = this; + visitor._abortRequested = true; + var request = new visitor.AbortRequest(); -var _file = require("./file"); + // If you decide to catch this exception and stop it from propagating, + // make sure to call its cancel method to avoid silencing other + // exceptions that might be thrown later in the traversal. + request.cancel = function () { + visitor._abortRequested = false; + }; -var _file2 = _interopRequireDefault(_file); + throw request; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + PVp.reset = function (path/*, additional arguments */) { + // Empty stub; may be reassigned or overridden by subclasses. + }; -var Pipeline = function () { - function Pipeline() { - (0, _classCallCheck3.default)(this, Pipeline); - } + PVp.visitWithoutReset = function (path) { + if (this instanceof this.Context) { + // Since this.Context.prototype === this, there's a chance we + // might accidentally call context.visitWithoutReset. If that + // happens, re-invoke the method against context.visitor. + return this.visitor.visitWithoutReset(path); + } - Pipeline.prototype.lint = function lint(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!(path instanceof NodePath)) { + throw new Error(""); + } - opts.code = false; - opts.mode = "lint"; - return this.transform(code, opts); - }; + var value = path.value; - Pipeline.prototype.pretransform = function pretransform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file; - }); - }; - - Pipeline.prototype.transform = function transform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file.transform(); - }); - }; + var methodName = value && + typeof value === "object" && + typeof value.type === "string" && + this._methodNameTable[value.type]; - Pipeline.prototype.analyse = function analyse(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var visitor = arguments[2]; + if (methodName) { + var context = this.acquireContext(path); + try { + return context.invokeVisitorMethod(methodName); + } finally { + this.releaseContext(context); + } - opts.code = false; - if (visitor) { - opts.plugins = opts.plugins || []; - opts.plugins.push(new _plugin2.default({ visitor: visitor })); - } - return this.transform(code, opts).metadata; - }; + } else { + // If there was no visitor method to call, visit the children of + // this node generically. + return visitChildren(path, this); + } + }; - Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) { - ast = (0, _normalizeAst2.default)(ast); + function visitChildren(path, visitor) { + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(visitor instanceof PathVisitor)) { + throw new Error(""); + } - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.addAst(ast); - return file.transform(); - }); - }; + var value = path.value; - return Pipeline; -}(); + if (isArray.check(value)) { + path.each(visitor.visitWithoutReset, visitor); + } else if (!isObject.check(value)) { + // No children to visit. + } else { + var childNames = types.getFieldNames(value); -exports.default = Pipeline; -module.exports = exports["default"]; -},{"../helpers/normalize-ast":31,"./file":38,"./plugin":51,"babel-runtime/helpers/classCallCheck":103}],50:[function(require,module,exports){ -"use strict"; + // The .comments field of the Node type is hidden, so we only + // visit it if the visitor defines visitBlock or visitLine, and + // value.comments is defined. + if (visitor._shouldVisitComments && + value.comments && + childNames.indexOf("comments") < 0) { + childNames.push("comments"); + } -exports.__esModule = true; + var childCount = childNames.length; + var childPaths = []; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + for (var i = 0; i < childCount; ++i) { + var childName = childNames[i]; + if (!hasOwn.call(value, childName)) { + value[childName] = types.getFieldValue(value, childName); + } + childPaths.push(path.get(childName)); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + for (var i = 0; i < childCount; ++i) { + visitor.visitWithoutReset(childPaths[i]); + } + } -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + return path.value; + } -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + PVp.acquireContext = function (path) { + if (this._reusableContextStack.length === 0) { + return new this.Context(path); + } + return this._reusableContextStack.pop().reset(path); + }; -var _inherits2 = require("babel-runtime/helpers/inherits"); + PVp.releaseContext = function (context) { + if (!(context instanceof this.Context)) { + throw new Error(""); + } + this._reusableContextStack.push(context); + context.currentPath = null; + }; -var _inherits3 = _interopRequireDefault(_inherits2); + PVp.reportChanged = function () { + this._changeReported = true; + }; -var _store = require("../store"); + PVp.wasChangeReported = function () { + return this._changeReported; + }; -var _store2 = _interopRequireDefault(_store); + function makeContextConstructor(visitor) { + function Context(path) { + if (!(this instanceof Context)) { + throw new Error(""); + } + if (!(this instanceof PathVisitor)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } -var _file5 = require("./file"); + Object.defineProperty(this, "visitor", { + value: visitor, + writable: false, + enumerable: true, + configurable: false + }); -var _file6 = _interopRequireDefault(_file5); + this.currentPath = path; + this.needToCallTraverse = true; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + Object.seal(this); + } -var PluginPass = function (_Store) { - (0, _inherits3.default)(PluginPass, _Store); + if (!(visitor instanceof PathVisitor)) { + throw new Error(""); + } - function PluginPass(file, plugin) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - (0, _classCallCheck3.default)(this, PluginPass); + // Note that the visitor object is the prototype of Context.prototype, + // so all visitor methods are inherited by context objects. + var Cp = Context.prototype = Object.create(visitor); - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + Cp.constructor = Context; + extend(Cp, sharedContextProtoMethods); - _this.plugin = plugin; - _this.key = plugin.key; - _this.file = file; - _this.opts = options; - return _this; - } + return Context; + } - PluginPass.prototype.addHelper = function addHelper() { - var _file; +// Every PathVisitor has a different this.Context constructor and +// this.Context.prototype object, but those prototypes can all use the +// same reset, invokeVisitorMethod, and traverse function objects. + var sharedContextProtoMethods = Object.create(null); - return (_file = this.file).addHelper.apply(_file, arguments); - }; + sharedContextProtoMethods.reset = + function reset(path) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } - PluginPass.prototype.addImport = function addImport() { - var _file2; + this.currentPath = path; + this.needToCallTraverse = true; - return (_file2 = this.file).addImport.apply(_file2, arguments); - }; + return this; + }; - PluginPass.prototype.getModuleName = function getModuleName() { - var _file3; + sharedContextProtoMethods.invokeVisitorMethod = + function invokeVisitorMethod(methodName) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } - return (_file3 = this.file).getModuleName.apply(_file3, arguments); - }; + var result = this.visitor[methodName].call(this, this.currentPath); - PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { - var _file4; + if (result === false) { + // Visitor methods return false to indicate that they have handled + // their own traversal needs, and we should not complain if + // this.needToCallTraverse is still true. + this.needToCallTraverse = false; - return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); - }; + } else if (result !== undefined) { + // Any other non-undefined value returned from the visitor method + // is interpreted as a replacement value. + this.currentPath = this.currentPath.replace(result)[0]; - return PluginPass; -}(_store2.default); + if (this.needToCallTraverse) { + // If this.traverse still hasn't been called, visit the + // children of the replacement node. + this.traverse(this.currentPath); + } + } -exports.default = PluginPass; -module.exports = exports["default"]; -},{"../store":36,"./file":38,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106}],51:[function(require,module,exports){ -"use strict"; + if (this.needToCallTraverse !== false) { + throw new Error( + "Must either call this.traverse or return false in " + methodName + ); + } -exports.__esModule = true; + var path = this.currentPath; + return path && path.value; + }; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + sharedContextProtoMethods.traverse = + function traverse(path, newVisitor) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + this.needToCallTraverse = false; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + return visitChildren(path, PathVisitor.fromMethodsObject( + newVisitor || this.visitor + )); + }; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + sharedContextProtoMethods.visit = + function visit(path, newVisitor) { + if (!(this instanceof this.Context)) { + throw new Error(""); + } + if (!(path instanceof NodePath)) { + throw new Error(""); + } + if (!(this.currentPath instanceof NodePath)) { + throw new Error(""); + } -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + this.needToCallTraverse = false; -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + return PathVisitor.fromMethodsObject( + newVisitor || this.visitor + ).visitWithoutReset(path); + }; -var _inherits2 = require("babel-runtime/helpers/inherits"); + sharedContextProtoMethods.reportChanged = function reportChanged() { + this.visitor.reportChanged(); + }; -var _inherits3 = _interopRequireDefault(_inherits2); + sharedContextProtoMethods.abort = function abort() { + this.needToCallTraverse = false; + this.visitor.abort(); + }; -var _optionManager = require("./file/options/option-manager"); + return PathVisitor; +}; -var _optionManager2 = _interopRequireDefault(_optionManager); +},{"./node-path":54,"./types":59}],56:[function(require,module,exports){ +var Ap = Array.prototype; +var slice = Ap.slice; +var map = Ap.map; +var Op = Object.prototype; +var hasOwn = Op.hasOwnProperty; -var _babelMessages = require("babel-messages"); +module.exports = function (fork) { + var types = fork.use(require("./types")); + var isArray = types.builtInTypes.array; + var isNumber = types.builtInTypes.number; -var messages = _interopRequireWildcard(_babelMessages); + function Path(value, parentPath, name) { + if (!(this instanceof Path)) { + throw new Error("Path constructor cannot be invoked without 'new'"); + } -var _store = require("../store"); + if (parentPath) { + if (!(parentPath instanceof Path)) { + throw new Error(""); + } + } else { + parentPath = null; + name = null; + } -var _store2 = _interopRequireDefault(_store); + // The value encapsulated by this Path, generally equal to + // parentPath.value[name] if we have a parentPath. + this.value = value; -var _babelTraverse = require("babel-traverse"); + // The immediate parent Path of this Path. + this.parentPath = parentPath; -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + // The name of the property of parentPath.value through which this + // Path's value was reached. + this.name = name; -var _assign = require("lodash/assign"); + // Calling path.get("child") multiple times always returns the same + // child Path object, for both performance and consistency reasons. + this.__childCache = null; + } -var _assign2 = _interopRequireDefault(_assign); + var Pp = Path.prototype; -var _clone = require("lodash/clone"); + function getChildCache(path) { + // Lazily create the child cache. This also cheapens cache + // invalidation, since you can just reset path.__childCache to null. + return path.__childCache || (path.__childCache = Object.create(null)); + } -var _clone2 = _interopRequireDefault(_clone); + function getChildPath(path, name) { + var cache = getChildCache(path); + var actualChildValue = path.getValueProperty(name); + var childPath = cache[name]; + if (!hasOwn.call(cache, name) || + // Ensure consistency between cache and reality. + childPath.value !== actualChildValue) { + childPath = cache[name] = new path.constructor( + actualChildValue, path, name + ); + } + return childPath; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +// This method is designed to be overridden by subclasses that need to +// handle missing properties, etc. + Pp.getValueProperty = function getValueProperty(name) { + return this.value[name]; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + Pp.get = function get(name) { + var path = this; + var names = arguments; + var count = names.length; -var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; + for (var i = 0; i < count; ++i) { + path = getChildPath(path, names[i]); + } -var Plugin = function (_Store) { - (0, _inherits3.default)(Plugin, _Store); + return path; + }; - function Plugin(plugin, key) { - (0, _classCallCheck3.default)(this, Plugin); + Pp.each = function each(callback, context) { + var childPaths = []; + var len = this.value.length; + var i = 0; - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + // Collect all the original child paths before invoking the callback. + for (var i = 0; i < len; ++i) { + if (hasOwn.call(this.value, i)) { + childPaths[i] = this.get(i); + } + } - _this.initialized = false; - _this.raw = (0, _assign2.default)({}, plugin); - _this.key = _this.take("name") || key; + // Invoke the callback on just the original child paths, regardless of + // any modifications made to the array by the callback. I chose these + // semantics over cleverly invoking the callback on new elements because + // this way is much easier to reason about. + context = context || this; + for (i = 0; i < len; ++i) { + if (hasOwn.call(childPaths, i)) { + callback.call(context, childPaths[i]); + } + } + }; - _this.manipulateOptions = _this.take("manipulateOptions"); - _this.post = _this.take("post"); - _this.pre = _this.take("pre"); - _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); - return _this; - } + Pp.map = function map(callback, context) { + var result = []; - Plugin.prototype.take = function take(key) { - var val = this.raw[key]; - delete this.raw[key]; - return val; - }; + this.each(function (childPath) { + result.push(callback.call(this, childPath)); + }, context); - Plugin.prototype.chain = function chain(target, key) { - if (!target[key]) return this[key]; - if (!this[key]) return target[key]; + return result; + }; - var fns = [target[key], this[key]]; + Pp.filter = function filter(callback, context) { + var result = []; - return function () { - var val = void 0; + this.each(function (childPath) { + if (callback.call(this, childPath)) { + result.push(childPath); + } + }, context); - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } + return result; + }; - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + function emptyMoves() {} + function getMoves(path, offset, start, end) { + isArray.assert(path.value); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (offset === 0) { + return emptyMoves; } - var fn = _ref; - - if (fn) { - var ret = fn.apply(this, args); - if (ret != null) val = ret; + var length = path.value.length; + if (length < 1) { + return emptyMoves; } - } - return val; - }; - }; - Plugin.prototype.maybeInherit = function maybeInherit(loc) { - var inherits = this.take("inherits"); - if (!inherits) return; + var argc = arguments.length; + if (argc === 2) { + start = 0; + end = length; + } else if (argc === 3) { + start = Math.max(start, 0); + end = length; + } else { + start = Math.max(start, 0); + end = Math.min(end, length); + } - inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits"); + isNumber.assert(start); + isNumber.assert(end); - this.manipulateOptions = this.chain(inherits, "manipulateOptions"); - this.post = this.chain(inherits, "post"); - this.pre = this.chain(inherits, "pre"); - this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]); - }; + var moves = Object.create(null); + var cache = getChildCache(path); - Plugin.prototype.init = function init(loc, i) { - if (this.initialized) return; - this.initialized = true; + for (var i = start; i < end; ++i) { + if (hasOwn.call(path.value, i)) { + var childPath = path.get(i); + if (childPath.name !== i) { + throw new Error(""); + } + var newIndex = i + offset; + childPath.name = newIndex; + moves[newIndex] = childPath; + delete cache[i]; + } + } - this.maybeInherit(loc); + delete cache.length; - for (var key in this.raw) { - throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); + return function () { + for (var newIndex in moves) { + var childPath = moves[newIndex]; + if (childPath.name !== +newIndex) { + throw new Error(""); + } + cache[newIndex] = childPath; + path.value[newIndex] = childPath.value; + } + }; } - }; - Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) { - for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + Pp.shift = function shift() { + var move = getMoves(this, -1); + var result = this.value.shift(); + move(); + return result; + }; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + Pp.unshift = function unshift(node) { + var move = getMoves(this, arguments.length); + var result = this.value.unshift.apply(this.value, arguments); + move(); + return result; + }; - var key = _ref2; + Pp.push = function push(node) { + isArray.assert(this.value); + delete getChildCache(this).length + return this.value.push.apply(this.value, arguments); + }; - if (visitor[key]) { - throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes."); - } - } + Pp.pop = function pop() { + isArray.assert(this.value); + var cache = getChildCache(this); + delete cache[this.value.length - 1]; + delete cache.length; + return this.value.pop(); + }; - _babelTraverse2.default.explode(visitor); - return visitor; - }; + Pp.insertAt = function insertAt(index, node) { + var argc = arguments.length; + var move = getMoves(this, argc - 1, index); + if (move === emptyMoves) { + return this; + } - return Plugin; -}(_store2.default); + index = Math.max(index, 0); -exports.default = Plugin; -module.exports = exports["default"]; -},{"../store":36,"./file/options/option-manager":44,"babel-messages":79,"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106,"babel-traverse":112,"lodash/assign":452,"lodash/clone":455}],52:[function(require,module,exports){ -"use strict"; + for (var i = 1; i < argc; ++i) { + this.value[index + i - 1] = arguments[i]; + } -exports.__esModule = true; -exports.inspect = exports.inherits = undefined; + move(); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + return this; + }; -var _getIterator3 = _interopRequireDefault(_getIterator2); + Pp.insertBefore = function insertBefore(node) { + var pp = this.parentPath; + var argc = arguments.length; + var insertAtArgs = [this.name]; + for (var i = 0; i < argc; ++i) { + insertAtArgs.push(arguments[i]); + } + return pp.insertAt.apply(pp, insertAtArgs); + }; -var _util = require("util"); + Pp.insertAfter = function insertAfter(node) { + var pp = this.parentPath; + var argc = arguments.length; + var insertAtArgs = [this.name + 1]; + for (var i = 0; i < argc; ++i) { + insertAtArgs.push(arguments[i]); + } + return pp.insertAt.apply(pp, insertAtArgs); + }; -Object.defineProperty(exports, "inherits", { - enumerable: true, - get: function get() { - return _util.inherits; - } -}); -Object.defineProperty(exports, "inspect", { - enumerable: true, - get: function get() { - return _util.inspect; - } -}); -exports.canCompile = canCompile; -exports.list = list; -exports.regexify = regexify; -exports.arrayify = arrayify; -exports.booleanify = booleanify; -exports.shouldIgnore = shouldIgnore; + function repairRelationshipWithParent(path) { + if (!(path instanceof Path)) { + throw new Error(""); + } -var _escapeRegExp = require("lodash/escapeRegExp"); + var pp = path.parentPath; + if (!pp) { + // Orphan paths have no relationship to repair. + return path; + } -var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); + var parentValue = pp.value; + var parentCache = getChildCache(pp); -var _startsWith = require("lodash/startsWith"); + // Make sure parentCache[path.name] is populated. + if (parentValue[path.name] === path.value) { + parentCache[path.name] = path; + } else if (isArray.check(parentValue)) { + // Something caused path.name to become out of date, so attempt to + // recover by searching for path.value in parentValue. + var i = parentValue.indexOf(path.value); + if (i >= 0) { + parentCache[path.name = i] = path; + } + } else { + // If path.value disagrees with parentValue[path.name], and + // path.name is not an array index, let path.value become the new + // parentValue[path.name] and update parentCache accordingly. + parentValue[path.name] = path.value; + parentCache[path.name] = path; + } -var _startsWith2 = _interopRequireDefault(_startsWith); + if (parentValue[path.name] !== path.value) { + throw new Error(""); + } + if (path.parentPath.get(path.name) !== path) { + throw new Error(""); + } -var _minimatch = require("minimatch"); + return path; + } -var _minimatch2 = _interopRequireDefault(_minimatch); + Pp.replace = function replace(replacement) { + var results = []; + var parentValue = this.parentPath.value; + var parentCache = getChildCache(this.parentPath); + var count = arguments.length; -var _includes = require("lodash/includes"); + repairRelationshipWithParent(this); -var _includes2 = _interopRequireDefault(_includes); + if (isArray.check(parentValue)) { + var originalLength = parentValue.length; + var move = getMoves(this.parentPath, count - 1, this.name + 1); -var _isRegExp = require("lodash/isRegExp"); + var spliceArgs = [this.name, 1]; + for (var i = 0; i < count; ++i) { + spliceArgs.push(arguments[i]); + } -var _isRegExp2 = _interopRequireDefault(_isRegExp); + var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); -var _path = require("path"); + if (splicedOut[0] !== this.value) { + throw new Error(""); + } + if (parentValue.length !== (originalLength - 1 + count)) { + throw new Error(""); + } -var _path2 = _interopRequireDefault(_path); + move(); -var _slash = require("slash"); + if (count === 0) { + delete this.value; + delete parentCache[this.name]; + this.__childCache = null; -var _slash2 = _interopRequireDefault(_slash); + } else { + if (parentValue[this.name] !== replacement) { + throw new Error(""); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.value !== replacement) { + this.value = replacement; + this.__childCache = null; + } -function canCompile(filename, altExts) { - var exts = altExts || canCompile.EXTENSIONS; - var ext = _path2.default.extname(filename); - return (0, _includes2.default)(exts, ext); -} + for (i = 0; i < count; ++i) { + results.push(this.parentPath.get(this.name + i)); + } -canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; + if (results[0] !== this) { + throw new Error(""); + } + } -function list(val) { - if (!val) { - return []; - } else if (Array.isArray(val)) { - return val; - } else if (typeof val === "string") { - return val.split(","); - } else { - return [val]; - } -} + } else if (count === 1) { + if (this.value !== replacement) { + this.__childCache = null; + } + this.value = parentValue[this.name] = replacement; + results.push(this); -function regexify(val) { - if (!val) { - return new RegExp(/.^/); - } + } else if (count === 0) { + delete parentValue[this.name]; + delete this.value; + this.__childCache = null; - if (Array.isArray(val)) { - val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); - } + // Leave this path cached as parentCache[this.name], even though + // it no longer has a value defined. - if (typeof val === "string") { - val = (0, _slash2.default)(val); + } else { + throw new Error("Could not replace path"); + } - if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); - if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); + return results; + }; - var regex = _minimatch2.default.makeRe(val, { nocase: true }); - return new RegExp(regex.source.slice(1, -1), "i"); - } + return Path; +}; - if ((0, _isRegExp2.default)(val)) { - return val; - } +},{"./types":59}],57:[function(require,module,exports){ +var hasOwn = Object.prototype.hasOwnProperty; - throw new TypeError("illegal type for regexify"); -} +module.exports = function (fork) { + var types = fork.use(require("./types")); + var Type = types.Type; + var namedTypes = types.namedTypes; + var Node = namedTypes.Node; + var Expression = namedTypes.Expression; + var isArray = types.builtInTypes.array; + var b = types.builders; -function arrayify(val, mapFn) { - if (!val) return []; - if (typeof val === "boolean") return arrayify([val], mapFn); - if (typeof val === "string") return arrayify(list(val), mapFn); + function Scope(path, parentScope) { + if (!(this instanceof Scope)) { + throw new Error("Scope constructor cannot be invoked without 'new'"); + } + if (!(path instanceof fork.use(require("./node-path")))) { + throw new Error(""); + } + ScopeType.assert(path.value); - if (Array.isArray(val)) { - if (mapFn) val = val.map(mapFn); - return val; - } + var depth; - return [val]; -} + if (parentScope) { + if (!(parentScope instanceof Scope)) { + throw new Error(""); + } + depth = parentScope.depth + 1; + } else { + parentScope = null; + depth = 0; + } -function booleanify(val) { - if (val === "true" || val == 1) { - return true; - } + Object.defineProperties(this, { + path: { value: path }, + node: { value: path.value }, + isGlobal: { value: !parentScope, enumerable: true }, + depth: { value: depth }, + parent: { value: parentScope }, + bindings: { value: {} }, + types: { value: {} }, + }); + } - if (val === "false" || val == 0 || !val) { - return false; - } + var scopeTypes = [ + // Program nodes introduce global scopes. + namedTypes.Program, - return val; -} + // Function is the supertype of FunctionExpression, + // FunctionDeclaration, ArrowExpression, etc. + namedTypes.Function, -function shouldIgnore(filename) { - var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var only = arguments[2]; + // In case you didn't know, the caught parameter shadows any variable + // of the same name in an outer scope. + namedTypes.CatchClause + ]; - filename = filename.replace(/\\/g, "/"); + var ScopeType = Type.or.apply(Type, scopeTypes); - if (only) { - for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + Scope.isEstablishedBy = function(node) { + return ScopeType.check(node); + }; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + var Sp = Scope.prototype; - var pattern = _ref; +// Will be overridden after an instance lazily calls scanScope. + Sp.didScan = false; - if (_shouldIgnore(pattern, filename)) return false; - } - return true; - } else if (ignore.length) { - for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + Sp.declares = function(name) { + this.scan(); + return hasOwn.call(this.bindings, name); + }; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + Sp.declaresType = function(name) { + this.scan(); + return hasOwn.call(this.types, name); + }; - var _pattern = _ref2; + Sp.declareTemporary = function(prefix) { + if (prefix) { + if (!/^[a-z$_]/i.test(prefix)) { + throw new Error(""); + } + } else { + prefix = "t$"; + } - if (_shouldIgnore(_pattern, filename)) return true; - } - } + // Include this.depth in the name to make sure the name does not + // collide with any variables in nested/enclosing scopes. + prefix += this.depth.toString(36) + "$"; - return false; -} + this.scan(); -function _shouldIgnore(pattern, filename) { - if (typeof pattern === "function") { - return pattern(filename); - } else { - return pattern.test(filename); - } -} -},{"babel-runtime/core-js/get-iterator":89,"lodash/escapeRegExp":461,"lodash/includes":471,"lodash/isRegExp":483,"lodash/startsWith":496,"minimatch":506,"path":801,"slash":523,"util":821}],53:[function(require,module,exports){ -module.exports={ - "_from": "babel-core@^6.18.2", - "_id": "babel-core@6.25.0", - "_inBundle": false, - "_integrity": "sha1-fdQrBGPHQunVKW3rPsZ6kyLa1yk=", - "_location": "/babel-core", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "babel-core@^6.18.2", - "name": "babel-core", - "escapedName": "babel-core", - "rawSpec": "^6.18.2", - "saveSpec": null, - "fetchSpec": "^6.18.2" - }, - "_requiredBy": [ - "/", - "/babel-cli", - "/babel-register" - ], - "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.25.0.tgz", - "_shasum": "7dd42b0463c742e9d5296deb3ec67a9322dad729", - "_spec": "babel-core@^6.18.2", - "_where": "/Users/ben/dev/regenerator", - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bundleDependencies": false, - "dependencies": { - "babel-code-frame": "^6.22.0", - "babel-generator": "^6.25.0", - "babel-helpers": "^6.24.1", - "babel-messages": "^6.23.0", - "babel-register": "^6.24.1", - "babel-runtime": "^6.22.0", - "babel-template": "^6.25.0", - "babel-traverse": "^6.25.0", - "babel-types": "^6.25.0", - "babylon": "^6.17.2", - "convert-source-map": "^1.1.0", - "debug": "^2.1.1", - "json5": "^0.5.0", - "lodash": "^4.2.0", - "minimatch": "^3.0.2", - "path-is-absolute": "^1.0.0", - "private": "^0.1.6", - "slash": "^1.0.0", - "source-map": "^0.5.0" - }, - "deprecated": false, - "description": "Babel compiler core.", - "devDependencies": { - "babel-helper-fixtures": "^6.22.0", - "babel-helper-transform-fixture-test-runner": "^6.24.1", - "babel-polyfill": "^6.23.0" - }, - "homepage": "https://babeljs.io/", - "keywords": [ - "6to5", - "babel", - "classes", - "const", - "es6", - "harmony", - "let", - "modules", - "transpile", - "transpiler", - "var", - "babel-core", - "compiler" - ], - "license": "MIT", - "name": "babel-core", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-core" - }, - "scripts": { - "bench": "make bench", - "test": "make test" - }, - "version": "6.25.0" -} + var index = 0; + while (this.declares(prefix + index)) { + ++index; + } -},{}],54:[function(require,module,exports){ -"use strict"; + var name = prefix + index; + return this.bindings[name] = types.builders.identifier(name); + }; -exports.__esModule = true; + Sp.injectTemporary = function(identifier, init) { + identifier || (identifier = this.declareTemporary()); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var bodyPath = this.path.get("body"); + if (namedTypes.BlockStatement.check(bodyPath.value)) { + bodyPath = bodyPath.get("body"); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + bodyPath.unshift( + b.variableDeclaration( + "var", + [b.variableDeclarator(identifier, init || null)] + ) + ); -var _trimRight = require("trim-right"); + return identifier; + }; -var _trimRight2 = _interopRequireDefault(_trimRight); + Sp.scan = function(force) { + if (force || !this.didScan) { + for (var name in this.bindings) { + // Empty out this.bindings, just in cases. + delete this.bindings[name]; + } + scanScope(this.path, this.bindings, this.types); + this.didScan = true; + } + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + Sp.getBindings = function () { + this.scan(); + return this.bindings; + }; -var SPACES_RE = /^[ \t]+$/; - -var Buffer = function () { - function Buffer(map) { - (0, _classCallCheck3.default)(this, Buffer); - this._map = null; - this._buf = []; - this._last = ""; - this._queue = []; - this._position = { - line: 1, - column: 0 - }; - this._sourcePosition = { - identifierName: null, - line: null, - column: null, - filename: null + Sp.getTypes = function () { + this.scan(); + return this.types; }; - this._map = map; - } - - Buffer.prototype.get = function get() { - this._flush(); + function scanScope(path, bindings, scopeTypes) { + var node = path.value; + ScopeType.assert(node); - var map = this._map; - var result = { - code: (0, _trimRight2.default)(this._buf.join("")), - map: null, - rawMappings: map && map.getRawMappings() - }; + if (namedTypes.CatchClause.check(node)) { + // A catch clause establishes a new scope but the only variable + // bound in that scope is the catch parameter. Any other + // declarations create bindings in the outer scope. + addPattern(path.get("param"), bindings); - if (map) { - Object.defineProperty(result, "map", { - configurable: true, - enumerable: true, - get: function get() { - return this.map = map.get(); - }, - set: function set(value) { - Object.defineProperty(this, "map", { value: value, writable: true }); + } else { + recursiveScanScope(path, bindings, scopeTypes); } - }); } - return result; - }; - - Buffer.prototype.append = function append(str) { - this._flush(); - var _sourcePosition = this._sourcePosition, - line = _sourcePosition.line, - column = _sourcePosition.column, - filename = _sourcePosition.filename, - identifierName = _sourcePosition.identifierName; + function recursiveScanScope(path, bindings, scopeTypes) { + var node = path.value; - this._append(str, line, column, identifierName, filename); - }; + if (path.parent && + namedTypes.FunctionExpression.check(path.parent.node) && + path.parent.node.id) { + addPattern(path.parent.get("id"), bindings); + } - Buffer.prototype.queue = function queue(str) { - if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { - this._queue.shift(); - }var _sourcePosition2 = this._sourcePosition, - line = _sourcePosition2.line, - column = _sourcePosition2.column, - filename = _sourcePosition2.filename, - identifierName = _sourcePosition2.identifierName; + if (!node) { + // None of the remaining cases matter if node is falsy. - this._queue.unshift([str, line, column, identifierName, filename]); - }; + } else if (isArray.check(node)) { + path.each(function(childPath) { + recursiveScanChild(childPath, bindings, scopeTypes); + }); - Buffer.prototype._flush = function _flush() { - var item = void 0; - while (item = this._queue.pop()) { - this._append.apply(this, item); - } - }; + } else if (namedTypes.Function.check(node)) { + path.get("params").each(function(paramPath) { + addPattern(paramPath, bindings); + }); - Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { - if (this._map && str[0] !== "\n") { - this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); - } + recursiveScanChild(path.get("body"), bindings, scopeTypes); - this._buf.push(str); - this._last = str[str.length - 1]; + } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) { + addTypePattern(path.get("id"), scopeTypes); - for (var i = 0; i < str.length; i++) { - if (str[i] === "\n") { - this._position.line++; - this._position.column = 0; - } else { - this._position.column++; - } - } - }; + } else if (namedTypes.VariableDeclarator.check(node)) { + addPattern(path.get("id"), bindings); + recursiveScanChild(path.get("init"), bindings, scopeTypes); - Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { - if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); - }; + } else if (node.type === "ImportSpecifier" || + node.type === "ImportNamespaceSpecifier" || + node.type === "ImportDefaultSpecifier") { + addPattern( + // Esprima used to use the .name field to refer to the local + // binding identifier for ImportSpecifier nodes, but .id for + // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. + // ESTree/Acorn/ESpree use .local for all three node types. + path.get(node.local ? "local" : + node.name ? "name" : "id"), + bindings + ); - Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { - if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); - }; + } else if (Node.check(node) && !Expression.check(node)) { + types.eachField(node, function(name, child) { + var childPath = path.get(name); + if (!pathHasValue(childPath, child)) { + throw new Error(""); + } + recursiveScanChild(childPath, bindings, scopeTypes); + }); + } + } - Buffer.prototype.endsWith = function endsWith(suffix) { - if (suffix.length === 1) { - var last = void 0; - if (this._queue.length > 0) { - var str = this._queue[0][0]; - last = str[str.length - 1]; - } else { - last = this._last; - } + function pathHasValue(path, value) { + if (path.value === value) { + return true; + } - return last === suffix; - } + // Empty arrays are probably produced by defaults.emptyArray, in which + // case is makes sense to regard them as equivalent, if not ===. + if (Array.isArray(path.value) && + path.value.length === 0 && + Array.isArray(value) && + value.length === 0) { + return true; + } - var end = this._last + this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - if (suffix.length <= end.length) { - return end.slice(-suffix.length) === suffix; + return false; } - return false; - }; + function recursiveScanChild(path, bindings, scopeTypes) { + var node = path.value; - Buffer.prototype.hasContent = function hasContent() { - return this._queue.length > 0 || !!this._last; - }; + if (!node || Expression.check(node)) { + // Ignore falsy values and Expressions. - Buffer.prototype.source = function source(prop, loc) { - if (prop && !loc) return; + } else if (namedTypes.FunctionDeclaration.check(node) && + node.id !== null) { + addPattern(path.get("id"), bindings); - var pos = loc ? loc[prop] : null; + } else if (namedTypes.ClassDeclaration && + namedTypes.ClassDeclaration.check(node)) { + addPattern(path.get("id"), bindings); - this._sourcePosition.identifierName = loc && loc.identifierName || null; - this._sourcePosition.line = pos ? pos.line : null; - this._sourcePosition.column = pos ? pos.column : null; - this._sourcePosition.filename = loc && loc.filename || null; - }; + } else if (ScopeType.check(node)) { + if (namedTypes.CatchClause.check(node)) { + var catchParamName = node.param.name; + var hadBinding = hasOwn.call(bindings, catchParamName); - Buffer.prototype.withSource = function withSource(prop, loc, cb) { - if (!this._map) return cb(); + // Any declarations that occur inside the catch body that do + // not have the same name as the catch parameter should count + // as bindings in the outer scope. + recursiveScanScope(path.get("body"), bindings, scopeTypes); - var originalLine = this._sourcePosition.line; - var originalColumn = this._sourcePosition.column; - var originalFilename = this._sourcePosition.filename; - var originalIdentifierName = this._sourcePosition.identifierName; + // If a new binding matching the catch parameter name was + // created while scanning the catch body, ignore it because it + // actually refers to the catch parameter and not the outer + // scope that we're currently scanning. + if (!hadBinding) { + delete bindings[catchParamName]; + } + } - this.source(prop, loc); + } else { + recursiveScanScope(path, bindings, scopeTypes); + } + } - cb(); + function addPattern(patternPath, bindings) { + var pattern = patternPath.value; + namedTypes.Pattern.assert(pattern); - this._sourcePosition.line = originalLine; - this._sourcePosition.column = originalColumn; - this._sourcePosition.filename = originalFilename; - this._sourcePosition.identifierName = originalIdentifierName; - }; + if (namedTypes.Identifier.check(pattern)) { + if (hasOwn.call(bindings, pattern.name)) { + bindings[pattern.name].push(patternPath); + } else { + bindings[pattern.name] = [patternPath]; + } - Buffer.prototype.getCurrentColumn = function getCurrentColumn() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - var lastIndex = extra.lastIndexOf("\n"); + } else if (namedTypes.ObjectPattern && + namedTypes.ObjectPattern.check(pattern)) { + patternPath.get('properties').each(function(propertyPath) { + var property = propertyPath.value; + if (namedTypes.Pattern.check(property)) { + addPattern(propertyPath, bindings); + } else if (namedTypes.Property.check(property)) { + addPattern(propertyPath.get('value'), bindings); + } else if (namedTypes.SpreadProperty && + namedTypes.SpreadProperty.check(property)) { + addPattern(propertyPath.get('argument'), bindings); + } + }); - return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; - }; + } else if (namedTypes.ArrayPattern && + namedTypes.ArrayPattern.check(pattern)) { + patternPath.get('elements').each(function(elementPath) { + var element = elementPath.value; + if (namedTypes.Pattern.check(element)) { + addPattern(elementPath, bindings); + } else if (namedTypes.SpreadElement && + namedTypes.SpreadElement.check(element)) { + addPattern(elementPath.get("argument"), bindings); + } + }); - Buffer.prototype.getCurrentLine = function getCurrentLine() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); + } else if (namedTypes.PropertyPattern && + namedTypes.PropertyPattern.check(pattern)) { + addPattern(patternPath.get('pattern'), bindings); - var count = 0; - for (var i = 0; i < extra.length; i++) { - if (extra[i] === "\n") count++; + } else if ((namedTypes.SpreadElementPattern && + namedTypes.SpreadElementPattern.check(pattern)) || + (namedTypes.SpreadPropertyPattern && + namedTypes.SpreadPropertyPattern.check(pattern))) { + addPattern(patternPath.get('argument'), bindings); + } } - return this._position.line + count; - }; + function addTypePattern(patternPath, types) { + var pattern = patternPath.value; + namedTypes.Pattern.assert(pattern); - return Buffer; -}(); + if (namedTypes.Identifier.check(pattern)) { + if (hasOwn.call(types, pattern.name)) { + types[pattern.name].push(patternPath); + } else { + types[pattern.name] = [patternPath]; + } -exports.default = Buffer; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":103,"trim-right":539}],55:[function(require,module,exports){ -"use strict"; + } + } -exports.__esModule = true; -exports.File = File; -exports.Program = Program; -exports.BlockStatement = BlockStatement; -exports.Noop = Noop; -exports.Directive = Directive; + Sp.lookup = function(name) { + for (var scope = this; scope; scope = scope.parent) + if (scope.declares(name)) + break; + return scope; + }; -var _types = require("./types"); + Sp.lookupType = function(name) { + for (var scope = this; scope; scope = scope.parent) + if (scope.declaresType(name)) + break; + return scope; + }; -Object.defineProperty(exports, "DirectiveLiteral", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -function File(node) { - this.print(node.program, node); -} + Sp.getGlobalScope = function() { + var scope = this; + while (!scope.isGlobal) + scope = scope.parent; + return scope; + }; -function Program(node) { - this.printInnerComments(node, false); + return Scope; +}; - this.printSequence(node.directives, node); - if (node.directives && node.directives.length) this.newline(); +},{"./node-path":54,"./types":59}],58:[function(require,module,exports){ +module.exports = function (fork) { + var exports = {}; + var types = fork.use(require("../lib/types")); + var Type = types.Type; + var builtin = types.builtInTypes; + var isNumber = builtin.number; - this.printSequence(node.body, node); -} + // An example of constructing a new type with arbitrary constraints from + // an existing type. + exports.geq = function (than) { + return new Type(function (value) { + return isNumber.check(value) && value >= than; + }, isNumber + " >= " + than); + }; -function BlockStatement(node) { - this.token("{"); - this.printInnerComments(node); + // Default value-returning functions that may optionally be passed as a + // third argument to Def.prototype.field. + exports.defaults = { + // Functions were used because (among other reasons) that's the most + // elegant way to allow for the emptyArray one always to give a new + // array instance. + "null": function () { return null }, + "emptyArray": function () { return [] }, + "false": function () { return false }, + "true": function () { return true }, + "undefined": function () {} + }; - var hasDirectives = node.directives && node.directives.length; + var naiveIsPrimitive = Type.or( + builtin.string, + builtin.number, + builtin.boolean, + builtin.null, + builtin.undefined + ); - if (node.body.length || hasDirectives) { - this.newline(); + exports.isPrimitive = new Type(function (value) { + if (value === null) + return true; + var type = typeof value; + return !(type === "object" || + type === "function"); + }, naiveIsPrimitive.toString()); - this.printSequence(node.directives, node, { indent: true }); - if (hasDirectives) this.newline(); + return exports; +}; +},{"../lib/types":59}],59:[function(require,module,exports){ +var Ap = Array.prototype; +var slice = Ap.slice; +var map = Ap.map; +var each = Ap.forEach; +var Op = Object.prototype; +var objToStr = Op.toString; +var funObjStr = objToStr.call(function(){}); +var strObjStr = objToStr.call(""); +var hasOwn = Op.hasOwnProperty; - this.printSequence(node.body, node, { indent: true }); - this.removeTrailingNewline(); +module.exports = function () { - this.source("end", node.loc); + var exports = {}; - if (!this.endsWith("\n")) this.newline(); + // A type is an object with a .check method that takes a value and returns + // true or false according to whether the value matches the type. - this.rightBrace(); - } else { - this.source("end", node.loc); - this.token("}"); - } -} + function Type(check, name) { + var self = this; + if (!(self instanceof Type)) { + throw new Error("Type constructor cannot be invoked without 'new'"); + } -function Noop() {} + // Unfortunately we can't elegantly reuse isFunction and isString, + // here, because this code is executed while defining those types. + if (objToStr.call(check) !== funObjStr) { + throw new Error(check + " is not a function"); + } -function Directive(node) { - this.print(node.value, node); - this.semicolon(); -} -},{"./types":64}],56:[function(require,module,exports){ -"use strict"; + // The `name` parameter can be either a function or a string. + var nameObjStr = objToStr.call(name); + if (!(nameObjStr === funObjStr || + nameObjStr === strObjStr)) { + throw new Error(name + " is neither a function nor a string"); + } -exports.__esModule = true; -exports.ClassDeclaration = ClassDeclaration; -exports.ClassBody = ClassBody; -exports.ClassProperty = ClassProperty; -exports.ClassMethod = ClassMethod; -function ClassDeclaration(node) { - this.printJoin(node.decorators, node); - this.word("class"); + Object.defineProperties(self, { + name: {value: name}, + check: { + value: function (value, deep) { + var result = check.call(self, value, deep); + if (!result && deep && objToStr.call(deep) === funObjStr) + deep(self, value); + return result; + } + } + }); + } - if (node.id) { - this.space(); - this.print(node.id, node); - } + var Tp = Type.prototype; - this.print(node.typeParameters, node); + // Throughout this file we use Object.defineProperty to prevent + // redefinition of exported properties. + exports.Type = Type; - if (node.superClass) { - this.space(); - this.word("extends"); - this.space(); - this.print(node.superClass, node); - this.print(node.superTypeParameters, node); - } + // Like .check, except that failure triggers an AssertionError. + Tp.assert = function (value, deep) { + if (!this.check(value, deep)) { + var str = shallowStringify(value); + throw new Error(str + " does not match type " + this); + } + return true; + }; - if (node.implements) { - this.space(); - this.word("implements"); - this.space(); - this.printList(node.implements, node); - } + function shallowStringify(value) { + if (isObject.check(value)) + return "{" + Object.keys(value).map(function (key) { + return key + ": " + value[key]; + }).join(", ") + "}"; - this.space(); - this.print(node.body, node); -} + if (isArray.check(value)) + return "[" + value.map(shallowStringify).join(", ") + "]"; -exports.ClassExpression = ClassDeclaration; -function ClassBody(node) { - this.token("{"); - this.printInnerComments(node); - if (node.body.length === 0) { - this.token("}"); - } else { - this.newline(); + return JSON.stringify(value); + } - this.indent(); - this.printSequence(node.body, node); - this.dedent(); - - if (!this.endsWith("\n")) this.newline(); + Tp.toString = function () { + var name = this.name; - this.rightBrace(); - } -} + if (isString.check(name)) + return name; -function ClassProperty(node) { - this.printJoin(node.decorators, node); + if (isFunction.check(name)) + return name.call(this) + ""; - if (node.static) { - this.word("static"); - this.space(); - } - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - this._variance(node); - this.print(node.key, node); - } - this.print(node.typeAnnotation, node); - if (node.value) { - this.space(); - this.token("="); - this.space(); - this.print(node.value, node); - } - this.semicolon(); -} + return name + " type"; + }; -function ClassMethod(node) { - this.printJoin(node.decorators, node); + var builtInCtorFns = []; + var builtInCtorTypes = []; + var builtInTypes = {}; + exports.builtInTypes = builtInTypes; - if (node.static) { - this.word("static"); - this.space(); - } + function defBuiltInType(example, name) { + var objStr = objToStr.call(example); - if (node.kind === "constructorCall") { - this.word("call"); - this.space(); - } + var type = new Type(function (value) { + return objToStr.call(value) === objStr; + }, name); - this._method(node); -} -},{}],57:[function(require,module,exports){ -"use strict"; + builtInTypes[name] = type; -exports.__esModule = true; -exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; -exports.UnaryExpression = UnaryExpression; -exports.DoExpression = DoExpression; -exports.ParenthesizedExpression = ParenthesizedExpression; -exports.UpdateExpression = UpdateExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.NewExpression = NewExpression; -exports.SequenceExpression = SequenceExpression; -exports.ThisExpression = ThisExpression; -exports.Super = Super; -exports.Decorator = Decorator; -exports.CallExpression = CallExpression; -exports.Import = Import; -exports.EmptyStatement = EmptyStatement; -exports.ExpressionStatement = ExpressionStatement; -exports.AssignmentPattern = AssignmentPattern; -exports.AssignmentExpression = AssignmentExpression; -exports.BindExpression = BindExpression; -exports.MemberExpression = MemberExpression; -exports.MetaProperty = MetaProperty; + if (example && typeof example.constructor === "function") { + builtInCtorFns.push(example.constructor); + builtInCtorTypes.push(type); + } -var _babelTypes = require("babel-types"); + return type; + } -var t = _interopRequireWildcard(_babelTypes); + // These types check the underlying [[Class]] attribute of the given + // value, rather than using the problematic typeof operator. Note however + // that no subtyping is considered; so, for instance, isObject.check + // returns false for [], /./, new Date, and null. + var isString = defBuiltInType("truthy", "string"); + var isFunction = defBuiltInType(function () {}, "function"); + var isArray = defBuiltInType([], "array"); + var isObject = defBuiltInType({}, "object"); + var isRegExp = defBuiltInType(/./, "RegExp"); + var isDate = defBuiltInType(new Date, "Date"); + var isNumber = defBuiltInType(3, "number"); + var isBoolean = defBuiltInType(true, "boolean"); + var isNull = defBuiltInType(null, "null"); + var isUndefined = defBuiltInType(void 0, "undefined"); -var _node = require("../node"); + // There are a number of idiomatic ways of expressing types, so this + // function serves to coerce them all to actual Type objects. Note that + // providing the name argument is not necessary in most cases. + function toType(from, name) { + // The toType function should of course be idempotent. + if (from instanceof Type) + return from; -var n = _interopRequireWildcard(_node); + // The Def type is used as a helper for constructing compound + // interface types for AST nodes. + if (from instanceof Def) + return from.type; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + // Support [ElemType] syntax. + if (isArray.check(from)) + return Type.fromArray(from); -function UnaryExpression(node) { - if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { - this.word(node.operator); - this.space(); - } else { - this.token(node.operator); - } + // Support { someField: FieldType, ... } syntax. + if (isObject.check(from)) + return Type.fromObject(from); - this.print(node.argument, node); -} + if (isFunction.check(from)) { + var bicfIndex = builtInCtorFns.indexOf(from); + if (bicfIndex >= 0) { + return builtInCtorTypes[bicfIndex]; + } -function DoExpression(node) { - this.word("do"); - this.space(); - this.print(node.body, node); -} + // If isFunction.check(from), and from is not a built-in + // constructor, assume from is a binary predicate function we can + // use to define the type. + return new Type(from, name); + } -function ParenthesizedExpression(node) { - this.token("("); - this.print(node.expression, node); - this.token(")"); -} + // As a last resort, toType returns a type that matches any value that + // is === from. This is primarily useful for literal values like + // toType(null), but it has the additional advantage of allowing + // toType to be a total function. + return new Type(function (value) { + return value === from; + }, isUndefined.check(name) ? function () { + return from + ""; + } : name); + } -function UpdateExpression(node) { - if (node.prefix) { - this.token(node.operator); - this.print(node.argument, node); - } else { - this.print(node.argument, node); - this.token(node.operator); - } -} + // Returns a type that matches the given value iff any of type1, type2, + // etc. match the value. + Type.or = function (/* type1, type2, ... */) { + var types = []; + var len = arguments.length; + for (var i = 0; i < len; ++i) + types.push(toType(arguments[i])); -function ConditionalExpression(node) { - this.print(node.test, node); - this.space(); - this.token("?"); - this.space(); - this.print(node.consequent, node); - this.space(); - this.token(":"); - this.space(); - this.print(node.alternate, node); -} + return new Type(function (value, deep) { + for (var i = 0; i < len; ++i) + if (types[i].check(value, deep)) + return true; + return false; + }, function () { + return types.join(" | "); + }); + }; -function NewExpression(node, parent) { - this.word("new"); - this.space(); - this.print(node.callee, node); - if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return; + Type.fromArray = function (arr) { + if (!isArray.check(arr)) { + throw new Error(""); + } + if (arr.length !== 1) { + throw new Error("only one element type is permitted for typed arrays"); + } + return toType(arr[0]).arrayOf(); + }; - this.token("("); - this.printList(node.arguments, node); - this.token(")"); -} + Tp.arrayOf = function () { + var elemType = this; + return new Type(function (value, deep) { + return isArray.check(value) && value.every(function (elem) { + return elemType.check(elem, deep); + }); + }, function () { + return "[" + elemType + "]"; + }); + }; -function SequenceExpression(node) { - this.printList(node.expressions, node); -} + Type.fromObject = function (obj) { + var fields = Object.keys(obj).map(function (name) { + return new Field(name, obj[name]); + }); -function ThisExpression() { - this.word("this"); -} + return new Type(function (value, deep) { + return isObject.check(value) && fields.every(function (field) { + return field.type.check(value[field.name], deep); + }); + }, function () { + return "{ " + fields.join(", ") + " }"; + }); + }; -function Super() { - this.word("super"); -} + function Field(name, type, defaultFn, hidden) { + var self = this; -function Decorator(node) { - this.token("@"); - this.print(node.expression, node); - this.newline(); -} + if (!(self instanceof Field)) { + throw new Error("Field constructor cannot be invoked without 'new'"); + } + isString.assert(name); -function commaSeparatorNewline() { - this.token(","); - this.newline(); + type = toType(type); - if (!this.endsWith("\n")) this.space(); -} + var properties = { + name: {value: name}, + type: {value: type}, + hidden: {value: !!hidden} + }; -function CallExpression(node) { - this.print(node.callee, node); + if (isFunction.check(defaultFn)) { + properties.defaultFn = {value: defaultFn}; + } - this.token("("); + Object.defineProperties(self, properties); + } - var isPrettyCall = node._prettyCall; + var Fp = Field.prototype; - var separator = void 0; - if (isPrettyCall) { - separator = commaSeparatorNewline; - this.newline(); - this.indent(); - } + Fp.toString = function () { + return JSON.stringify(this.name) + ": " + this.type; + }; - this.printList(node.arguments, node, { separator: separator }); + Fp.getValue = function (obj) { + var value = obj[this.name]; - if (isPrettyCall) { - this.newline(); - this.dedent(); - } + if (!isUndefined.check(value)) + return value; - this.token(")"); -} + if (this.defaultFn) + value = this.defaultFn.call(obj); -function Import() { - this.word("import"); -} + return value; + }; -function buildYieldAwait(keyword) { - return function (node) { - this.word(keyword); + // Define a type whose name is registered in a namespace (the defCache) so + // that future definitions will return the same type given the same name. + // In particular, this system allows for circular and forward definitions. + // The Def object d returned from Type.def may be used to configure the + // type d.type by calling methods such as d.bases, d.build, and d.field. + Type.def = function (typeName) { + isString.assert(typeName); + return hasOwn.call(defCache, typeName) + ? defCache[typeName] + : defCache[typeName] = new Def(typeName); + }; - if (node.delegate) { - this.token("*"); - } + // In order to return the same Def instance every time Type.def is called + // with a particular name, those instances need to be stored in a cache. + var defCache = Object.create(null); - if (node.argument) { - this.space(); - var terminatorState = this.startTerminatorless(); - this.print(node.argument, node); - this.endTerminatorless(terminatorState); - } - }; -} + function Def(typeName) { + var self = this; + if (!(self instanceof Def)) { + throw new Error("Def constructor cannot be invoked without 'new'"); + } -var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); -var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); + Object.defineProperties(self, { + typeName: {value: typeName}, + baseNames: {value: []}, + ownFields: {value: Object.create(null)}, -function EmptyStatement() { - this.semicolon(true); -} + // These two are populated during finalization. + allSupertypes: {value: Object.create(null)}, // Includes own typeName. + supertypeList: {value: []}, // Linear inheritance hierarchy. + allFields: {value: Object.create(null)}, // Includes inherited fields. + fieldNames: {value: []}, // Non-hidden keys of allFields. -function ExpressionStatement(node) { - this.print(node.expression, node); - this.semicolon(); -} + type: { + value: new Type(function (value, deep) { + return self.check(value, deep); + }, typeName) + } + }); + } -function AssignmentPattern(node) { - this.print(node.left, node); - if (node.left.optional) this.token("?"); - this.print(node.left.typeAnnotation, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); -} + Def.fromValue = function (value) { + if (value && typeof value === "object") { + var type = value.type; + if (typeof type === "string" && + hasOwn.call(defCache, type)) { + var d = defCache[type]; + if (d.finalized) { + return d; + } + } + } -function AssignmentExpression(node, parent) { - var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); + return null; + }; - if (parens) { - this.token("("); - } + var Dp = Def.prototype; - this.print(node.left, node); + Dp.isSupertypeOf = function (that) { + if (that instanceof Def) { + if (this.finalized !== true || + that.finalized !== true) { + throw new Error(""); + } + return hasOwn.call(that.allSupertypes, this.typeName); + } else { + throw new Error(that + " is not a Def"); + } + }; - this.space(); - if (node.operator === "in" || node.operator === "instanceof") { - this.word(node.operator); - } else { - this.token(node.operator); - } - this.space(); + // Note that the list returned by this function is a copy of the internal + // supertypeList, *without* the typeName itself as the first element. + exports.getSupertypeNames = function (typeName) { + if (!hasOwn.call(defCache, typeName)) { + throw new Error(""); + } + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error(""); + } + return d.supertypeList.slice(1); + }; - this.print(node.right, node); + // Returns an object mapping from every known type in the defCache to the + // most specific supertype whose name is an own property of the candidates + // object. + exports.computeSupertypeLookupTable = function (candidates) { + var table = {}; + var typeNames = Object.keys(defCache); + var typeNameCount = typeNames.length; - if (parens) { - this.token(")"); - } -} + for (var i = 0; i < typeNameCount; ++i) { + var typeName = typeNames[i]; + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error("" + typeName); + } + for (var j = 0; j < d.supertypeList.length; ++j) { + var superTypeName = d.supertypeList[j]; + if (hasOwn.call(candidates, superTypeName)) { + table[typeName] = superTypeName; + break; + } + } + } -function BindExpression(node) { - this.print(node.object, node); - this.token("::"); - this.print(node.callee, node); -} + return table; + }; -exports.BinaryExpression = AssignmentExpression; -exports.LogicalExpression = AssignmentExpression; -function MemberExpression(node) { - this.print(node.object, node); + Dp.checkAllFields = function (value, deep) { + var allFields = this.allFields; + if (this.finalized !== true) { + throw new Error("" + this.typeName); + } - if (!node.computed && t.isMemberExpression(node.property)) { - throw new TypeError("Got a MemberExpression for MemberExpression property"); - } + function checkFieldByName(name) { + var field = allFields[name]; + var type = field.type; + var child = field.getValue(value); + return type.check(child, deep); + } - var computed = node.computed; - if (t.isLiteral(node.property) && typeof node.property.value === "number") { - computed = true; - } + return isObject.check(value) + && Object.keys(allFields).every(checkFieldByName); + }; - if (computed) { - this.token("["); - this.print(node.property, node); - this.token("]"); - } else { - this.token("."); - this.print(node.property, node); - } -} + Dp.check = function (value, deep) { + if (this.finalized !== true) { + throw new Error( + "prematurely checking unfinalized type " + this.typeName + ); + } -function MetaProperty(node) { - this.print(node.meta, node); - this.token("."); - this.print(node.property, node); -} -},{"../node":66,"babel-types":145}],58:[function(require,module,exports){ -"use strict"; + // A Def type can only match an object value. + if (!isObject.check(value)) + return false; -exports.__esModule = true; -exports.AnyTypeAnnotation = AnyTypeAnnotation; -exports.ArrayTypeAnnotation = ArrayTypeAnnotation; -exports.BooleanTypeAnnotation = BooleanTypeAnnotation; -exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; -exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; -exports.DeclareClass = DeclareClass; -exports.DeclareFunction = DeclareFunction; -exports.DeclareInterface = DeclareInterface; -exports.DeclareModule = DeclareModule; -exports.DeclareModuleExports = DeclareModuleExports; -exports.DeclareTypeAlias = DeclareTypeAlias; -exports.DeclareVariable = DeclareVariable; -exports.ExistentialTypeParam = ExistentialTypeParam; -exports.FunctionTypeAnnotation = FunctionTypeAnnotation; -exports.FunctionTypeParam = FunctionTypeParam; -exports.InterfaceExtends = InterfaceExtends; -exports._interfaceish = _interfaceish; -exports._variance = _variance; -exports.InterfaceDeclaration = InterfaceDeclaration; -exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; -exports.MixedTypeAnnotation = MixedTypeAnnotation; -exports.EmptyTypeAnnotation = EmptyTypeAnnotation; -exports.NullableTypeAnnotation = NullableTypeAnnotation; - -var _types = require("./types"); - -Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.NumericLiteral; - } -}); -Object.defineProperty(exports, "StringLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -exports.NumberTypeAnnotation = NumberTypeAnnotation; -exports.StringTypeAnnotation = StringTypeAnnotation; -exports.ThisTypeAnnotation = ThisTypeAnnotation; -exports.TupleTypeAnnotation = TupleTypeAnnotation; -exports.TypeofTypeAnnotation = TypeofTypeAnnotation; -exports.TypeAlias = TypeAlias; -exports.TypeAnnotation = TypeAnnotation; -exports.TypeParameter = TypeParameter; -exports.TypeParameterInstantiation = TypeParameterInstantiation; -exports.ObjectTypeAnnotation = ObjectTypeAnnotation; -exports.ObjectTypeCallProperty = ObjectTypeCallProperty; -exports.ObjectTypeIndexer = ObjectTypeIndexer; -exports.ObjectTypeProperty = ObjectTypeProperty; -exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; -exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; -exports.UnionTypeAnnotation = UnionTypeAnnotation; -exports.TypeCastExpression = TypeCastExpression; -exports.VoidTypeAnnotation = VoidTypeAnnotation; -function AnyTypeAnnotation() { - this.word("any"); -} - -function ArrayTypeAnnotation(node) { - this.print(node.elementType, node); - this.token("["); - this.token("]"); -} + var vDef = Def.fromValue(value); + if (!vDef) { + // If we couldn't infer the Def associated with the given value, + // and we expected it to be a SourceLocation or a Position, it was + // probably just missing a "type" field (because Esprima does not + // assign a type property to such nodes). Be optimistic and let + // this.checkAllFields make the final decision. + if (this.typeName === "SourceLocation" || + this.typeName === "Position") { + return this.checkAllFields(value, deep); + } -function BooleanTypeAnnotation() { - this.word("boolean"); -} + // Calling this.checkAllFields for any other type of node is both + // bad for performance and way too forgiving. + return false; + } -function BooleanLiteralTypeAnnotation(node) { - this.word(node.value ? "true" : "false"); -} + // If checking deeply and vDef === this, then we only need to call + // checkAllFields once. Calling checkAllFields is too strict when deep + // is false, because then we only care about this.isSupertypeOf(vDef). + if (deep && vDef === this) + return this.checkAllFields(value, deep); -function NullLiteralTypeAnnotation() { - this.word("null"); -} + // In most cases we rely exclusively on isSupertypeOf to make O(1) + // subtyping determinations. This suffices in most situations outside + // of unit tests, since interface conformance is checked whenever new + // instances are created using builder functions. + if (!this.isSupertypeOf(vDef)) + return false; -function DeclareClass(node) { - this.word("declare"); - this.space(); - this.word("class"); - this.space(); - this._interfaceish(node); -} + // The exception is when deep is true; then, we recursively check all + // fields. + if (!deep) + return true; -function DeclareFunction(node) { - this.word("declare"); - this.space(); - this.word("function"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation.typeAnnotation, node); - this.semicolon(); -} + // Use the more specific Def (vDef) to perform the deep check, but + // shallow-check fields defined by the less specific Def (this). + return vDef.checkAllFields(value, deep) + && this.checkAllFields(value, false); + }; -function DeclareInterface(node) { - this.word("declare"); - this.space(); - this.InterfaceDeclaration(node); -} + Dp.bases = function () { + var args = slice.call(arguments); + var bases = this.baseNames; -function DeclareModule(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.space(); - this.print(node.id, node); - this.space(); - this.print(node.body, node); -} + if (this.finalized) { + if (args.length !== bases.length) { + throw new Error(""); + } + for (var i = 0; i < args.length; i++) { + if (args[i] !== bases[i]) { + throw new Error(""); + } + } + return this; + } -function DeclareModuleExports(node) { - this.word("declare"); - this.space(); - this.word("module"); - this.token("."); - this.word("exports"); - this.print(node.typeAnnotation, node); -} + args.forEach(function (baseName) { + isString.assert(baseName); -function DeclareTypeAlias(node) { - this.word("declare"); - this.space(); - this.TypeAlias(node); -} + // This indexOf lookup may be O(n), but the typical number of base + // names is very small, and indexOf is a native Array method. + if (bases.indexOf(baseName) < 0) + bases.push(baseName); + }); -function DeclareVariable(node) { - this.word("declare"); - this.space(); - this.word("var"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - this.semicolon(); -} + return this; // For chaining. + }; -function ExistentialTypeParam() { - this.token("*"); -} + // False by default until .build(...) is called on an instance. + Object.defineProperty(Dp, "buildable", {value: false}); -function FunctionTypeAnnotation(node, parent) { - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node); + var builders = {}; + exports.builders = builders; - if (node.rest) { - if (node.params.length) { - this.token(","); - this.space(); - } - this.token("..."); - this.print(node.rest, node); - } + // This object is used as prototype for any node created by a builder. + var nodePrototype = {}; - this.token(")"); + // Call this function to define a new method to be shared by all AST + // nodes. The replaced method (if any) is returned for easy wrapping. + exports.defineMethod = function (name, func) { + var old = nodePrototype[name]; - if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { - this.token(":"); - } else { - this.space(); - this.token("=>"); - } + // Pass undefined as func to delete nodePrototype[name]. + if (isUndefined.check(func)) { + delete nodePrototype[name]; - this.space(); - this.print(node.returnType, node); -} + } else { + isFunction.assert(func); -function FunctionTypeParam(node) { - this.print(node.name, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.typeAnnotation, node); -} + Object.defineProperty(nodePrototype, name, { + enumerable: true, // For discoverability. + configurable: true, // For delete proto[name]. + value: func + }); + } -function InterfaceExtends(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); -} + return old; + }; -exports.ClassImplements = InterfaceExtends; -exports.GenericTypeAnnotation = InterfaceExtends; -function _interfaceish(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); - if (node.extends.length) { - this.space(); - this.word("extends"); - this.space(); - this.printList(node.extends, node); - } - if (node.mixins && node.mixins.length) { - this.space(); - this.word("mixins"); - this.space(); - this.printList(node.mixins, node); - } - this.space(); - this.print(node.body, node); -} + var isArrayOfString = isString.arrayOf(); -function _variance(node) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } -} + // Calling the .build method of a Def simultaneously marks the type as + // buildable (by defining builders[getBuilderName(typeName)]) and + // specifies the order of arguments that should be passed to the builder + // function to create an instance of the type. + Dp.build = function (/* param1, param2, ... */) { + var self = this; -function InterfaceDeclaration(node) { - this.word("interface"); - this.space(); - this._interfaceish(node); -} + var newBuildParams = slice.call(arguments); + isArrayOfString.assert(newBuildParams); -function andSeparator() { - this.space(); - this.token("&"); - this.space(); -} + // Calling Def.prototype.build multiple times has the effect of merely + // redefining this property. + Object.defineProperty(self, "buildParams", { + value: newBuildParams, + writable: false, + enumerable: false, + configurable: true + }); -function IntersectionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: andSeparator }); -} + if (self.buildable) { + // If this Def is already buildable, update self.buildParams and + // continue using the old builder function. + return self; + } -function MixedTypeAnnotation() { - this.word("mixed"); -} + // Every buildable type will have its "type" field filled in + // automatically. This includes types that are not subtypes of Node, + // like SourceLocation, but that seems harmless (TODO?). + self.field("type", String, function () { return self.typeName }); -function EmptyTypeAnnotation() { - this.word("empty"); -} + // Override Dp.buildable for this Def instance. + Object.defineProperty(self, "buildable", {value: true}); -function NullableTypeAnnotation(node) { - this.token("?"); - this.print(node.typeAnnotation, node); -} + Object.defineProperty(builders, getBuilderName(self.typeName), { + enumerable: true, -function NumberTypeAnnotation() { - this.word("number"); -} + value: function () { + var args = arguments; + var argc = args.length; + var built = Object.create(nodePrototype); -function StringTypeAnnotation() { - this.word("string"); -} + if (!self.finalized) { + throw new Error( + "attempting to instantiate unfinalized type " + + self.typeName + ); + } -function ThisTypeAnnotation() { - this.word("this"); -} + function add(param, i) { + if (hasOwn.call(built, param)) + return; -function TupleTypeAnnotation(node) { - this.token("["); - this.printList(node.types, node); - this.token("]"); -} + var all = self.allFields; + if (!hasOwn.call(all, param)) { + throw new Error("" + param); + } -function TypeofTypeAnnotation(node) { - this.word("typeof"); - this.space(); - this.print(node.argument, node); -} + var field = all[param]; + var type = field.type; + var value; -function TypeAlias(node) { - this.word("type"); - this.space(); - this.print(node.id, node); - this.print(node.typeParameters, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); - this.semicolon(); -} + if (isNumber.check(i) && i < argc) { + value = args[i]; + } else if (field.defaultFn) { + // Expose the partially-built object to the default + // function as its `this` object. + value = field.defaultFn.call(built); + } else { + var message = "no value or default function given for field " + + JSON.stringify(param) + " of " + self.typeName + "(" + + self.buildParams.map(function (name) { + return all[name]; + }).join(", ") + ")"; + throw new Error(message); + } -function TypeAnnotation(node) { - this.token(":"); - this.space(); - if (node.optional) this.token("?"); - this.print(node.typeAnnotation, node); -} + if (!type.check(value)) { + throw new Error( + shallowStringify(value) + + " does not match field " + field + + " of type " + self.typeName + ); + } -function TypeParameter(node) { - this._variance(node); + // TODO Could attach getters and setters here to enforce + // dynamic type safety. + built[param] = value; + } - this.word(node.name); + self.buildParams.forEach(function (param, i) { + add(param, i); + }); - if (node.bound) { - this.print(node.bound, node); - } + Object.keys(self.allFields).forEach(function (param) { + add(param); // Use the default value. + }); - if (node.default) { - this.space(); - this.token("="); - this.space(); - this.print(node.default, node); - } -} + // Make sure that the "type" field was filled automatically. + if (built.type !== self.typeName) { + throw new Error(""); + } -function TypeParameterInstantiation(node) { - this.token("<"); - this.printList(node.params, node, {}); - this.token(">"); -} + return built; + } + }); -exports.TypeParameterDeclaration = TypeParameterInstantiation; -function ObjectTypeAnnotation(node) { - var _this = this; + return self; // For chaining. + }; - if (node.exact) { - this.token("{|"); - } else { - this.token("{"); - } + function getBuilderName(typeName) { + return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) { + var len = upperCasePrefix.length; + switch (len) { + case 0: return ""; + // If there's only one initial capital letter, just lower-case it. + case 1: return upperCasePrefix.toLowerCase(); + default: + // If there's more than one initial capital letter, lower-case + // all but the last one, so that XMLDefaultDeclaration (for + // example) becomes xmlDefaultDeclaration. + return upperCasePrefix.slice( + 0, len - 1).toLowerCase() + + upperCasePrefix.charAt(len - 1); + } + }); + } + exports.getBuilderName = getBuilderName; - var props = node.properties.concat(node.callProperties, node.indexers); + function getStatementBuilderName(typeName) { + typeName = getBuilderName(typeName); + return typeName.replace(/(Expression)?$/, "Statement"); + } + exports.getStatementBuilderName = getStatementBuilderName; - if (props.length) { - this.space(); + // The reason fields are specified using .field(...) instead of an object + // literal syntax is somewhat subtle: the object literal syntax would + // support only one key and one value, but with .field(...) we can pass + // any number of arguments to specify the field. + Dp.field = function (name, type, defaultFn, hidden) { + if (this.finalized) { + console.error("Ignoring attempt to redefine field " + + JSON.stringify(name) + " of finalized type " + + JSON.stringify(this.typeName)); + return this; + } + this.ownFields[name] = new Field(name, type, defaultFn, hidden); + return this; // For chaining. + }; - this.printJoin(props, node, { - addNewlines: function addNewlines(leading) { - if (leading && !props[0]) return 1; - }, + var namedTypes = {}; + exports.namedTypes = namedTypes; - indent: true, - statement: true, - iterator: function iterator() { - if (props.length !== 1) { - if (_this.format.flowCommaSeparator) { - _this.token(","); - } else { - _this.semicolon(); - } - _this.space(); + // Like Object.keys, but aware of what fields each AST type should have. + function getFieldNames(object) { + var d = Def.fromValue(object); + if (d) { + return d.fieldNames.slice(0); } - } - }); - this.space(); - } + if ("type" in object) { + throw new Error( + "did not recognize object of type " + + JSON.stringify(object.type) + ); + } - if (node.exact) { - this.token("|}"); - } else { - this.token("}"); - } -} + return Object.keys(object); + } + exports.getFieldNames = getFieldNames; -function ObjectTypeCallProperty(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this.print(node.value, node); -} + // Get the value of an object property, taking object.type and default + // functions into account. + function getFieldValue(object, fieldName) { + var d = Def.fromValue(object); + if (d) { + var field = d.allFields[fieldName]; + if (field) { + return field.getValue(object); + } + } -function ObjectTypeIndexer(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.token("["); - this.print(node.id, node); - this.token(":"); - this.space(); - this.print(node.key, node); - this.token("]"); - this.token(":"); - this.space(); - this.print(node.value, node); -} + return object && object[fieldName]; + } + exports.getFieldValue = getFieldValue; -function ObjectTypeProperty(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.print(node.key, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.value, node); -} + // Iterate over all defined fields of an object, including those missing + // or undefined, passing each field name and effective value (as returned + // by getFieldValue) to the callback. If the object has no corresponding + // Def, the callback will never be called. + exports.eachField = function (object, callback, context) { + getFieldNames(object).forEach(function (name) { + callback.call(this, name, getFieldValue(object, name)); + }, context); + }; -function ObjectTypeSpreadProperty(node) { - this.token("..."); - this.print(node.argument, node); -} + // Similar to eachField, except that iteration stops as soon as the + // callback returns a truthy value. Like Array.prototype.some, the final + // result is either true or false to indicates whether the callback + // returned true for any element or not. + exports.someField = function (object, callback, context) { + return getFieldNames(object).some(function (name) { + return callback.call(this, name, getFieldValue(object, name)); + }, context); + }; -function QualifiedTypeIdentifier(node) { - this.print(node.qualification, node); - this.token("."); - this.print(node.id, node); -} + // This property will be overridden as true by individual Def instances + // when they are finalized. + Object.defineProperty(Dp, "finalized", {value: false}); -function orSeparator() { - this.space(); - this.token("|"); - this.space(); -} + Dp.finalize = function () { + var self = this; -function UnionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: orSeparator }); -} + // It's not an error to finalize a type more than once, but only the + // first call to .finalize does anything. + if (!self.finalized) { + var allFields = self.allFields; + var allSupertypes = self.allSupertypes; -function TypeCastExpression(node) { - this.token("("); - this.print(node.expression, node); - this.print(node.typeAnnotation, node); - this.token(")"); -} + self.baseNames.forEach(function (name) { + var def = defCache[name]; + if (def instanceof Def) { + def.finalize(); + extend(allFields, def.allFields); + extend(allSupertypes, def.allSupertypes); + } else { + var message = "unknown supertype name " + + JSON.stringify(name) + + " for subtype " + + JSON.stringify(self.typeName); + throw new Error(message); + } + }); -function VoidTypeAnnotation() { - this.word("void"); -} -},{"./types":64}],59:[function(require,module,exports){ -"use strict"; + // TODO Warn if fields are overridden with incompatible types. + extend(allFields, self.ownFields); + allSupertypes[self.typeName] = self; -exports.__esModule = true; + self.fieldNames.length = 0; + for (var fieldName in allFields) { + if (hasOwn.call(allFields, fieldName) && + !allFields[fieldName].hidden) { + self.fieldNames.push(fieldName); + } + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + // Types are exported only once they have been finalized. + Object.defineProperty(namedTypes, self.typeName, { + enumerable: true, + value: self.type + }); -var _getIterator3 = _interopRequireDefault(_getIterator2); + Object.defineProperty(self, "finalized", {value: true}); -exports.JSXAttribute = JSXAttribute; -exports.JSXIdentifier = JSXIdentifier; -exports.JSXNamespacedName = JSXNamespacedName; -exports.JSXMemberExpression = JSXMemberExpression; -exports.JSXSpreadAttribute = JSXSpreadAttribute; -exports.JSXExpressionContainer = JSXExpressionContainer; -exports.JSXSpreadChild = JSXSpreadChild; -exports.JSXText = JSXText; -exports.JSXElement = JSXElement; -exports.JSXOpeningElement = JSXOpeningElement; -exports.JSXClosingElement = JSXClosingElement; -exports.JSXEmptyExpression = JSXEmptyExpression; + // A linearization of the inheritance hierarchy. + populateSupertypeList(self.typeName, self.supertypeList); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (self.buildable && self.supertypeList.lastIndexOf("Expression") >= 0) { + wrapExpressionBuilderWithStatement(self.typeName); + } + } + }; -function JSXAttribute(node) { - this.print(node.name, node); - if (node.value) { - this.token("="); - this.print(node.value, node); - } -} + // Adds an additional builder for Expression subtypes + // that wraps the built Expression in an ExpressionStatements. + function wrapExpressionBuilderWithStatement(typeName) { + var wrapperName = getStatementBuilderName(typeName); -function JSXIdentifier(node) { - this.word(node.name); -} + // skip if the builder already exists + if (builders[wrapperName]) return; -function JSXNamespacedName(node) { - this.print(node.namespace, node); - this.token(":"); - this.print(node.name, node); -} + // the builder function to wrap with builders.ExpressionStatement + var wrapped = builders[getBuilderName(typeName)]; -function JSXMemberExpression(node) { - this.print(node.object, node); - this.token("."); - this.print(node.property, node); -} + // skip if there is nothing to wrap + if (!wrapped) return; -function JSXSpreadAttribute(node) { - this.token("{"); - this.token("..."); - this.print(node.argument, node); - this.token("}"); -} + builders[wrapperName] = function () { + return builders.expressionStatement(wrapped.apply(builders, arguments)); + }; + } -function JSXExpressionContainer(node) { - this.token("{"); - this.print(node.expression, node); - this.token("}"); -} + function populateSupertypeList(typeName, list) { + list.length = 0; + list.push(typeName); -function JSXSpreadChild(node) { - this.token("{"); - this.token("..."); - this.print(node.expression, node); - this.token("}"); -} + var lastSeen = Object.create(null); -function JSXText(node) { - this.token(node.value); -} + for (var pos = 0; pos < list.length; ++pos) { + typeName = list[pos]; + var d = defCache[typeName]; + if (d.finalized !== true) { + throw new Error(""); + } -function JSXElement(node) { - var open = node.openingElement; - this.print(open, node); - if (open.selfClosing) return; + // If we saw typeName earlier in the breadth-first traversal, + // delete the last-seen occurrence. + if (hasOwn.call(lastSeen, typeName)) { + delete list[lastSeen[typeName]]; + } - this.indent(); - for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + // Record the new index of the last-seen occurrence of typeName. + lastSeen[typeName] = pos; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + // Enqueue the base names of this type. + list.push.apply(list, d.baseNames); + } + + // Compaction loop to remove array holes. + for (var to = 0, from = to, len = list.length; from < len; ++from) { + if (hasOwn.call(list, from)) { + list[to++] = list[from]; + } + } + + list.length = to; } - var child = _ref; + function extend(into, from) { + Object.keys(from).forEach(function (name) { + into[name] = from[name]; + }); - this.print(child, node); - } - this.dedent(); + return into; + }; - this.print(node.closingElement, node); -} + exports.finalize = function () { + Object.keys(defCache).forEach(function (name) { + defCache[name].finalize(); + }); + }; -function spaceSeparator() { - this.space(); -} + return exports; +}; -function JSXOpeningElement(node) { - this.token("<"); - this.print(node.name, node); - if (node.attributes.length > 0) { - this.space(); - this.printJoin(node.attributes, node, { separator: spaceSeparator }); - } - if (node.selfClosing) { - this.space(); - this.token("/>"); - } else { - this.token(">"); - } -} +},{}],60:[function(require,module,exports){ +module.exports = require('./fork')([ + // This core module of AST types captures ES5 as it is parsed today by + // git://github.com/ariya/esprima.git#master. + require("./def/core"), -function JSXClosingElement(node) { - this.token(""); -} + // Feel free to add to or remove from this list of extension modules to + // configure the precise type hierarchy that you need. + require("./def/es6"), + require("./def/es7"), + require("./def/mozilla"), + require("./def/e4x"), + require("./def/jsx"), + require("./def/flow"), + require("./def/esprima"), + require("./def/babel"), + require("./def/babel6") +]); -function JSXEmptyExpression() {} -},{"babel-runtime/core-js/get-iterator":89}],60:[function(require,module,exports){ +},{"./def/babel":42,"./def/babel6":43,"./def/core":44,"./def/e4x":45,"./def/es6":46,"./def/es7":47,"./def/esprima":48,"./def/flow":49,"./def/jsx":50,"./def/mozilla":51,"./fork":52}],61:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.FunctionDeclaration = undefined; -exports._params = _params; -exports._method = _method; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; -var _babelTypes = require("babel-types"); +exports.default = function (rawLines, lineNumber, colNumber) { + var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; -var t = _interopRequireWildcard(_babelTypes); + colNumber = Math.max(colNumber, 0); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor; + var chalk = _chalk2.default; + if (opts.forceColor) { + chalk = new _chalk2.default.constructor({ enabled: true }); + } + var maybeHighlight = function maybeHighlight(chalkFn, string) { + return highlighted ? chalkFn(string) : string; + }; + var defs = getDefs(chalk); + if (highlighted) rawLines = highlight(defs, rawLines); -function _params(node) { - var _this = this; + var linesAbove = opts.linesAbove || 2; + var linesBelow = opts.linesBelow || 3; - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node, { - iterator: function iterator(node) { - if (node.optional) _this.token("?"); - _this.print(node.typeAnnotation, node); - } - }); - this.token(")"); + var lines = rawLines.split(NEWLINE); + var start = Math.max(lineNumber - (linesAbove + 1), 0); + var end = Math.min(lines.length, lineNumber + linesBelow); - if (node.returnType) { - this.print(node.returnType, node); + if (!lineNumber && !colNumber) { + start = 0; + end = lines.length; } -} -function _method(node) { - var kind = node.kind; - var key = node.key; + var numberMaxWidth = String(end).length; - if (kind === "method" || kind === "init") { - if (node.generator) { - this.token("*"); + var frame = lines.slice(start, end).map(function (line, index) { + var number = start + 1 + index; + var paddedNumber = (" " + number).slice(-numberMaxWidth); + var gutter = " " + paddedNumber + " | "; + if (number === lineNumber) { + var markerLine = ""; + if (colNumber) { + var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); + } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return " " + maybeHighlight(defs.gutter, gutter) + line; } - } - - if (kind === "get" || kind === "set") { - this.word(kind); - this.space(); - } - - if (node.async) { - this.word("async"); - this.space(); - } + }).join("\n"); - if (node.computed) { - this.token("["); - this.print(key, node); - this.token("]"); + if (highlighted) { + return chalk.reset(frame); } else { - this.print(key, node); + return frame; } +}; - this._params(node); - this.space(); - this.print(node.body, node); -} +var _jsTokens = require("js-tokens"); -function FunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - this.word("function"); - if (node.generator) this.token("*"); +var _jsTokens2 = _interopRequireDefault(_jsTokens); - if (node.id) { - this.space(); - this.print(node.id, node); - } else { - this.space(); - } +var _esutils = require("esutils"); - this._params(node); - this.space(); - this.print(node.body, node); -} +var _esutils2 = _interopRequireDefault(_esutils); -exports.FunctionDeclaration = FunctionExpression; -function ArrowFunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } +var _chalk = require("chalk"); - var firstParam = node.params[0]; +var _chalk2 = _interopRequireDefault(_chalk); - if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { - this.print(firstParam, node); - } else { - this._params(node); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - this.space(); - this.token("=>"); - this.space(); +function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, - this.print(node.body, node); + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold, + gutter: chalk.grey, + marker: chalk.red.bold + }; } -function hasTypes(node, param) { - return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; -} -},{"babel-types":145}],61:[function(require,module,exports){ -"use strict"; +var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; -exports.__esModule = true; -exports.ImportSpecifier = ImportSpecifier; -exports.ImportDefaultSpecifier = ImportDefaultSpecifier; -exports.ExportDefaultSpecifier = ExportDefaultSpecifier; -exports.ExportSpecifier = ExportSpecifier; -exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; -exports.ExportAllDeclaration = ExportAllDeclaration; -exports.ExportNamedDeclaration = ExportNamedDeclaration; -exports.ExportDefaultDeclaration = ExportDefaultDeclaration; -exports.ImportDeclaration = ImportDeclaration; -exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; +var JSX_TAG = /^[a-z][\w-]*$/i; -var _babelTypes = require("babel-types"); +var BRACKET = /^[()\[\]{}]$/; -var t = _interopRequireWildcard(_babelTypes); +function getTokenType(match) { + var _match$slice = match.slice(-2), + offset = _match$slice[0], + text = _match$slice[1]; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var token = (0, _jsTokens.matchToToken)(match); -function ImportSpecifier(node) { - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); + if (token.type === "name") { + if (_esutils2.default.keyword.isReservedWordES6(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " 1 && arguments[1] !== undefined ? arguments[1] : {}; -function DoWhileStatement(node) { - this.word("do"); - this.space(); - this.print(node.body, node); - this.space(); - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.semicolon(); + opts.filename = filename; + return transform(_fs2.default.readFileSync(filename, "utf8"), opts); } +},{"../../package":89,"../helpers/resolve-plugin":69,"../helpers/resolve-preset":70,"../tools/build-external-helpers":73,"../transformation/file":74,"../transformation/file/options/config":78,"../transformation/file/options/option-manager":80,"../transformation/pipeline":85,"../util":88,"babel-messages":115,"babel-template":146,"babel-traverse":150,"babel-types":183,"fs":1}],64:[function(require,module,exports){ +"use strict"; -function buildLabelStatement(prefix) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; +exports.__esModule = true; +exports.default = getPossiblePluginNames; +function getPossiblePluginNames(pluginName) { + return ["babel-plugin-" + pluginName, pluginName]; +} +module.exports = exports["default"]; +},{}],65:[function(require,module,exports){ +"use strict"; - return function (node) { - this.word(prefix); +exports.__esModule = true; +exports.default = getPossiblePresetNames; +function getPossiblePresetNames(presetName) { + var possibleNames = ["babel-preset-" + presetName, presetName]; - var label = node[key]; - if (label) { - this.space(); + var matches = presetName.match(/^(@[^/]+)\/(.+)$/); + if (matches) { + var orgName = matches[1], + presetPath = matches[2]; - var terminatorState = this.startTerminatorless(); - this.print(label, node); - this.endTerminatorless(terminatorState); - } + possibleNames.push(orgName + "/babel-preset-" + presetPath); + } - this.semicolon(); - }; + return possibleNames; } +module.exports = exports["default"]; +},{}],66:[function(require,module,exports){ +"use strict"; -var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); -var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); -var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); -var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); +exports.__esModule = true; -function LabeledStatement(node) { - this.print(node.label, node); - this.token(":"); - this.space(); - this.print(node.body, node); -} +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -function TryStatement(node) { - this.word("try"); - this.space(); - this.print(node.block, node); - this.space(); +var _getIterator3 = _interopRequireDefault(_getIterator2); - if (node.handlers) { - this.print(node.handlers[0], node); - } else { - this.print(node.handler, node); - } +exports.default = function (dest, src) { + if (!dest || !src) return; - if (node.finalizer) { - this.space(); - this.word("finally"); - this.space(); - this.print(node.finalizer, node); - } -} + return (0, _mergeWith2.default)(dest, src, function (a, b) { + if (b && Array.isArray(a)) { + var newArray = b.slice(0); -function CatchClause(node) { - this.word("catch"); - this.space(); - this.token("("); - this.print(node.param, node); - this.token(")"); - this.space(); - this.print(node.body, node); -} + for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -function SwitchStatement(node) { - this.word("switch"); - this.space(); - this.token("("); - this.print(node.discriminant, node); - this.token(")"); - this.space(); - this.token("{"); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - this.printSequence(node.cases, node, { - indent: true, - addNewlines: function addNewlines(leading, cas) { - if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + var item = _ref; + + if (newArray.indexOf(item) < 0) { + newArray.push(item); + } + } + + return newArray; } }); +}; - this.token("}"); -} +var _mergeWith = require("lodash/mergeWith"); -function SwitchCase(node) { - if (node.test) { - this.word("case"); - this.space(); - this.print(node.test, node); - this.token(":"); - } else { - this.word("default"); - this.token(":"); - } +var _mergeWith2 = _interopRequireDefault(_mergeWith); - if (node.consequent.length) { - this.newline(); - this.printSequence(node.consequent, node, { indent: true }); - } -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function DebuggerStatement() { - this.word("debugger"); - this.semicolon(); -} +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":127,"lodash/mergeWith":529}],67:[function(require,module,exports){ +"use strict"; -function variableDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { - this.space(true); +exports.__esModule = true; + +exports.default = function (ast, comments, tokens) { + if (ast) { + if (ast.type === "Program") { + return t.file(ast, comments || [], tokens || []); + } else if (ast.type === "File") { + return ast; + } } -} -function constDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { - this.space(true); - } -} - -function VariableDeclaration(node, parent) { - this.word(node.kind); - this.space(); - - var hasInits = false; + throw new Error("Not a valid ast?"); +}; - if (!t.isFor(parent)) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _babelTypes = require("babel-types"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var t = _interopRequireWildcard(_babelTypes); - var declar = _ref; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (declar.init) { - hasInits = true; - } - } - } +module.exports = exports["default"]; +},{"babel-types":183}],68:[function(require,module,exports){ +"use strict"; - var separator = void 0; - if (hasInits) { - separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; - } +exports.__esModule = true; +exports.default = resolveFromPossibleNames; - this.printList(node.declarations, node, { separator: separator }); +var _resolve = require("./resolve"); - if (t.isFor(parent)) { - if (parent.left === node || parent.init === node) return; - } +var _resolve2 = _interopRequireDefault(_resolve); - this.semicolon(); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function VariableDeclarator(node) { - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - if (node.init) { - this.space(); - this.token("="); - this.space(); - this.print(node.init, node); - } +function resolveFromPossibleNames(possibleNames, dirname) { + return possibleNames.reduce(function (accum, curr) { + return accum || (0, _resolve2.default)(curr, dirname); + }, null); } -},{"babel-runtime/core-js/get-iterator":89,"babel-types":145}],63:[function(require,module,exports){ +module.exports = exports["default"]; +},{"./resolve":71}],69:[function(require,module,exports){ +(function (process){ "use strict"; exports.__esModule = true; -exports.TaggedTemplateExpression = TaggedTemplateExpression; -exports.TemplateElement = TemplateElement; -exports.TemplateLiteral = TemplateLiteral; -function TaggedTemplateExpression(node) { - this.print(node.tag, node); - this.print(node.quasi, node); -} +exports.default = resolvePlugin; -function TemplateElement(node, parent) { - var isFirst = parent.quasis[0] === node; - var isLast = parent.quasis[parent.quasis.length - 1] === node; +var _resolveFromPossibleNames = require("./resolve-from-possible-names"); - var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); +var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); - this.token(value); -} +var _getPossiblePluginNames = require("./get-possible-plugin-names"); -function TemplateLiteral(node) { - var quasis = node.quasis; +var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames); - for (var i = 0; i < quasis.length; i++) { - this.print(quasis[i], node); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (i + 1 < quasis.length) { - this.print(node.expressions[i], node); - } - } +function resolvePlugin(pluginName) { + var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); + + return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname); } -},{}],64:[function(require,module,exports){ +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"./get-possible-plugin-names":64,"./resolve-from-possible-names":68,"_process":15}],70:[function(require,module,exports){ +(function (process){ "use strict"; exports.__esModule = true; -exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; -exports.Identifier = Identifier; -exports.RestElement = RestElement; -exports.ObjectExpression = ObjectExpression; -exports.ObjectMethod = ObjectMethod; -exports.ObjectProperty = ObjectProperty; -exports.ArrayExpression = ArrayExpression; -exports.RegExpLiteral = RegExpLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.NumericLiteral = NumericLiteral; -exports.StringLiteral = StringLiteral; +exports.default = resolvePreset; -var _babelTypes = require("babel-types"); +var _resolveFromPossibleNames = require("./resolve-from-possible-names"); -var t = _interopRequireWildcard(_babelTypes); +var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); -var _jsesc = require("jsesc"); +var _getPossiblePresetNames = require("./get-possible-preset-names"); -var _jsesc2 = _interopRequireDefault(_jsesc); +var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function Identifier(node) { - if (node.variance) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } - } - - this.word(node.name); -} +function resolvePreset(presetName) { + var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); -function RestElement(node) { - this.token("..."); - this.print(node.argument, node); + return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname); } +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"./get-possible-preset-names":65,"./resolve-from-possible-names":68,"_process":15}],71:[function(require,module,exports){ +(function (process){ +"use strict"; -exports.SpreadElement = RestElement; -exports.SpreadProperty = RestElement; -exports.RestProperty = RestElement; -function ObjectExpression(node) { - var props = node.properties; +exports.__esModule = true; - this.token("{"); - this.printInnerComments(node); +var _typeof2 = require("babel-runtime/helpers/typeof"); - if (props.length) { - this.space(); - this.printList(props, node, { indent: true, statement: true }); - this.space(); - } +var _typeof3 = _interopRequireDefault(_typeof2); - this.token("}"); -} +exports.default = function (loc) { + var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); -exports.ObjectPattern = ObjectExpression; -function ObjectMethod(node) { - this.printJoin(node.decorators, node); - this._method(node); -} + if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; -function ObjectProperty(node) { - this.printJoin(node.decorators, node); + var relativeMod = relativeModules[relative]; - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { - this.print(node.value, node); - return; - } + if (!relativeMod) { + relativeMod = new _module2.default(); - this.print(node.key, node); + var filename = _path2.default.join(relative, ".babelrc"); + relativeMod.id = filename; + relativeMod.filename = filename; - if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { - return; - } + relativeMod.paths = _module2.default._nodeModulePaths(relative); + relativeModules[relative] = relativeMod; } - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ArrayExpression(node) { - var elems = node.elements; - var len = elems.length; - - this.token("["); - this.printInnerComments(node); - - for (var i = 0; i < elems.length; i++) { - var elem = elems[i]; - if (elem) { - if (i > 0) this.space(); - this.print(elem, node); - if (i < len - 1) this.token(","); - } else { - this.token(","); - } + try { + return _module2.default._resolveFilename(loc, relativeMod); + } catch (err) { + return null; } +}; - this.token("]"); -} - -exports.ArrayPattern = ArrayExpression; -function RegExpLiteral(node) { - this.word("/" + node.pattern + "/" + node.flags); -} +var _module = require("module"); -function BooleanLiteral(node) { - this.word(node.value ? "true" : "false"); -} +var _module2 = _interopRequireDefault(_module); -function NullLiteral() { - this.word("null"); -} +var _path = require("path"); -function NumericLiteral(node) { - var raw = this.getPossibleRaw(node); - var value = node.value + ""; - if (raw == null) { - this.number(value); - } else if (this.format.minified) { - this.number(raw.length < value.length ? raw : value); - } else { - this.number(raw); - } -} +var _path2 = _interopRequireDefault(_path); -function StringLiteral(node, parent) { - var raw = this.getPossibleRaw(node); - if (!this.format.minified && raw != null) { - this.token(raw); - return; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var opts = { - quotes: t.isJSX(parent) ? "double" : this.format.quotes, - wrap: true - }; - if (this.format.jsonCompatibleStrings) { - opts.json = true; - } - var val = (0, _jsesc2.default)(node.value, opts); +var relativeModules = {}; - return this.token(val); -} -},{"babel-types":145,"jsesc":287}],65:[function(require,module,exports){ +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"_process":15,"babel-runtime/helpers/typeof":145,"module":1,"path":13}],72:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.CodeGenerator = undefined; + +var _map = require("babel-runtime/core-js/map"); + +var _map2 = _interopRequireDefault(_map); var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); @@ -10016,4470 +12008,5019 @@ var _inherits2 = require("babel-runtime/helpers/inherits"); var _inherits3 = _interopRequireDefault(_inherits2); -exports.default = function (ast, opts, code) { - var gen = new Generator(ast, opts, code); - return gen.generate(); -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _detectIndent = require("detect-indent"); +var Store = function (_Map) { + (0, _inherits3.default)(Store, _Map); -var _detectIndent2 = _interopRequireDefault(_detectIndent); + function Store() { + (0, _classCallCheck3.default)(this, Store); -var _sourceMap = require("./source-map"); + var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); -var _sourceMap2 = _interopRequireDefault(_sourceMap); + _this.dynamicData = {}; + return _this; + } -var _babelMessages = require("babel-messages"); + Store.prototype.setDynamic = function setDynamic(key, fn) { + this.dynamicData[key] = fn; + }; -var messages = _interopRequireWildcard(_babelMessages); + Store.prototype.get = function get(key) { + if (this.has(key)) { + return _Map.prototype.get.call(this, key); + } else { + if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { + var val = this.dynamicData[key](); + this.set(key, val); + return val; + } + } + }; -var _printer = require("./printer"); + return Store; +}(_map2.default); -var _printer2 = _interopRequireDefault(_printer); +exports.default = Store; +module.exports = exports["default"]; +},{"babel-runtime/core-js/map":129,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144}],73:[function(require,module,exports){ +"use strict"; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +exports.__esModule = true; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.default = function (whitelist) { + var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; -var Generator = function (_Printer) { - (0, _inherits3.default)(Generator, _Printer); + var namespace = t.identifier("babelHelpers"); - function Generator(ast) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var code = arguments[2]; - (0, _classCallCheck3.default)(this, Generator); + var builder = function builder(body) { + return buildHelpers(body, namespace, whitelist); + }; - var tokens = ast.tokens || []; - var format = normalizeOptions(code, opts, tokens); - var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; + var tree = void 0; - var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); + var build = { + global: buildGlobal, + umd: buildUmd, + var: buildVar + }[outputType]; - _this.ast = ast; - return _this; + if (build) { + tree = build(namespace, builder); + } else { + throw new Error(messages.get("unsupportedOutputType", outputType)); } - Generator.prototype.generate = function generate() { - return _Printer.prototype.generate.call(this, this.ast); - }; + return (0, _babelGenerator2.default)(tree).code; +}; - return Generator; -}(_printer2.default); +var _babelHelpers = require("babel-helpers"); -function normalizeOptions(code, opts, tokens) { - var style = " "; - if (code && typeof code === "string") { - var indent = (0, _detectIndent2.default)(code).indent; - if (indent && indent !== " ") style = indent; - } +var helpers = _interopRequireWildcard(_babelHelpers); - var format = { - auxiliaryCommentBefore: opts.auxiliaryCommentBefore, - auxiliaryCommentAfter: opts.auxiliaryCommentAfter, - shouldPrintComment: opts.shouldPrintComment, - retainLines: opts.retainLines, - retainFunctionParens: opts.retainFunctionParens, - comments: opts.comments == null || opts.comments, - compact: opts.compact, - minified: opts.minified, - concise: opts.concise, - quotes: opts.quotes || findCommonStringDelimiter(code, tokens), - jsonCompatibleStrings: opts.jsonCompatibleStrings, - indent: { - adjustMultilineComment: true, - style: style, - base: 0 - }, - flowCommaSeparator: opts.flowCommaSeparator - }; +var _babelGenerator = require("babel-generator"); - if (format.minified) { - format.compact = true; +var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - format.shouldPrintComment = format.shouldPrintComment || function () { - return format.comments; - }; - } else { - format.shouldPrintComment = format.shouldPrintComment || function (value) { - return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; - }; - } +var _babelMessages = require("babel-messages"); - if (format.compact === "auto") { - format.compact = code.length > 500000; +var messages = _interopRequireWildcard(_babelMessages); - if (format.compact) { - console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "500KB")); - } - } +var _babelTemplate = require("babel-template"); - if (format.compact) { - format.indent.adjustMultilineComment = false; - } +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - return format; -} +var _babelTypes = require("babel-types"); -function findCommonStringDelimiter(code, tokens) { - var DEFAULT_STRING_DELIMITER = "double"; - if (!code) { - return DEFAULT_STRING_DELIMITER; - } +var t = _interopRequireWildcard(_babelTypes); - var occurrences = { - single: 0, - double: 0 - }; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var checked = 0; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token.type.label !== "string") continue; +var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n"); - var raw = code.slice(token.start, token.end); - if (raw[0] === "'") { - occurrences.single++; - } else { - occurrences.double++; - } +function buildGlobal(namespace, builder) { + var body = []; + var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); + var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); - checked++; - if (checked >= 3) break; - } - if (occurrences.single > occurrences.double) { - return "single"; - } else { - return "double"; - } + body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))])); + + builder(body); + + return tree; } -var CodeGenerator = exports.CodeGenerator = function () { - function CodeGenerator(ast, opts, code) { - (0, _classCallCheck3.default)(this, CodeGenerator); +function buildUmd(namespace, builder) { + var body = []; + body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))])); - this._generator = new Generator(ast, opts, code); - } + builder(body); - CodeGenerator.prototype.generate = function generate() { - return this._generator.generate(); - }; + return t.program([buildUmdWrapper({ + FACTORY_PARAMETERS: t.identifier("global"), + BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])), + COMMON_ARGUMENTS: t.identifier("exports"), + AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: t.identifier("this") + })]); +} - return CodeGenerator; -}(); -},{"./printer":69,"./source-map":70,"babel-messages":79,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106,"detect-indent":274}],66:[function(require,module,exports){ +function buildVar(namespace, builder) { + var body = []; + body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))])); + builder(body); + body.push(t.expressionStatement(namespace)); + return t.program(body); +} + +function buildHelpers(body, namespace, whitelist) { + helpers.list.forEach(function (name) { + if (whitelist && whitelist.indexOf(name) < 0) return; + + var key = t.identifier(name); + body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)))); + }); +} +module.exports = exports["default"]; +},{"babel-generator":101,"babel-helpers":114,"babel-messages":115,"babel-template":146,"babel-types":183}],74:[function(require,module,exports){ +(function (process){ "use strict"; exports.__esModule = true; +exports.File = undefined; var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); -var _keys = require("babel-runtime/core-js/object/keys"); +var _create = require("babel-runtime/core-js/object/create"); -var _keys2 = _interopRequireDefault(_keys); +var _create2 = _interopRequireDefault(_create); -exports.needsWhitespace = needsWhitespace; -exports.needsWhitespaceBefore = needsWhitespaceBefore; -exports.needsWhitespaceAfter = needsWhitespaceAfter; -exports.needsParens = needsParens; +var _assign = require("babel-runtime/core-js/object/assign"); -var _whitespace = require("./whitespace"); +var _assign2 = _interopRequireDefault(_assign); -var _whitespace2 = _interopRequireDefault(_whitespace); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _parentheses = require("./parentheses"); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -var parens = _interopRequireWildcard(_parentheses); +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); -var _babelTypes = require("babel-types"); +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -var t = _interopRequireWildcard(_babelTypes); +var _inherits2 = require("babel-runtime/helpers/inherits"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _inherits3 = _interopRequireDefault(_inherits2); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _babelHelpers = require("babel-helpers"); -function expandAliases(obj) { - var newObj = {}; +var _babelHelpers2 = _interopRequireDefault(_babelHelpers); - function add(type, func) { - var fn = newObj[type]; - newObj[type] = fn ? function (node, parent, stack) { - var result = fn(node, parent, stack); +var _metadata = require("./metadata"); - return result == null ? func(node, parent, stack) : result; - } : func; - } +var metadataVisitor = _interopRequireWildcard(_metadata); - for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _convertSourceMap = require("convert-source-map"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); - var type = _ref; +var _optionManager = require("./options/option-manager"); +var _optionManager2 = _interopRequireDefault(_optionManager); - var aliases = t.FLIPPED_ALIAS_KEYS[type]; - if (aliases) { - for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +var _pluginPass = require("../plugin-pass"); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +var _pluginPass2 = _interopRequireDefault(_pluginPass); - var alias = _ref2; +var _babelTraverse = require("babel-traverse"); - add(alias, obj[type]); - } - } else { - add(type, obj[type]); - } - } +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - return newObj; -} +var _sourceMap = require("source-map"); -var expandedParens = expandAliases(parens); -var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); -var expandedWhitespaceList = expandAliases(_whitespace2.default.list); +var _sourceMap2 = _interopRequireDefault(_sourceMap); -function find(obj, node, parent, printStack) { - var fn = obj[node.type]; - return fn ? fn(node, parent, printStack) : null; -} +var _babelGenerator = require("babel-generator"); -function isOrHasCallExpression(node) { - if (t.isCallExpression(node)) { - return true; - } +var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - if (t.isMemberExpression(node)) { - return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); - } else { - return false; - } -} +var _babelCodeFrame = require("babel-code-frame"); -function needsWhitespace(node, parent, type) { - if (!node) return 0; +var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); - if (t.isExpressionStatement(node)) { - node = node.expression; - } +var _defaults = require("lodash/defaults"); - var linesInfo = find(expandedWhitespaceNodes, node, parent); +var _defaults2 = _interopRequireDefault(_defaults); - if (!linesInfo) { - var items = find(expandedWhitespaceList, node, parent); - if (items) { - for (var i = 0; i < items.length; i++) { - linesInfo = needsWhitespace(items[i], node, type); - if (linesInfo) break; - } - } - } +var _logger = require("./logger"); - return linesInfo && linesInfo[type] || 0; -} +var _logger2 = _interopRequireDefault(_logger); -function needsWhitespaceBefore(node, parent) { - return needsWhitespace(node, parent, "before"); -} +var _store = require("../../store"); -function needsWhitespaceAfter(node, parent) { - return needsWhitespace(node, parent, "after"); -} +var _store2 = _interopRequireDefault(_store); -function needsParens(node, parent, printStack) { - if (!parent) return false; +var _babylon = require("babylon"); - if (t.isNewExpression(parent) && parent.callee === node) { - if (isOrHasCallExpression(node)) return true; - } +var _util = require("../../util"); - return find(expandedParens, node, parent, printStack); -} -},{"./parentheses":67,"./whitespace":68,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/object/keys":96,"babel-types":145}],67:[function(require,module,exports){ -"use strict"; +var util = _interopRequireWildcard(_util); -exports.__esModule = true; -exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; -exports.NullableTypeAnnotation = NullableTypeAnnotation; -exports.UpdateExpression = UpdateExpression; -exports.ObjectExpression = ObjectExpression; -exports.DoExpression = DoExpression; -exports.Binary = Binary; -exports.BinaryExpression = BinaryExpression; -exports.SequenceExpression = SequenceExpression; -exports.YieldExpression = YieldExpression; -exports.ClassExpression = ClassExpression; -exports.UnaryLike = UnaryLike; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.AssignmentExpression = AssignmentExpression; +var _path = require("path"); + +var _path2 = _interopRequireDefault(_path); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _resolve = require("../../helpers/resolve"); -var PRECEDENCE = { - "||": 0, - "&&": 1, - "|": 2, - "^": 3, - "&": 4, - "==": 5, - "===": 5, - "!=": 5, - "!==": 5, - "<": 6, - ">": 6, - "<=": 6, - ">=": 6, - in: 6, - instanceof: 6, - ">>": 7, - "<<": 7, - ">>>": 7, - "+": 8, - "-": 8, - "*": 9, - "/": 9, - "%": 9, - "**": 10 -}; +var _resolve2 = _interopRequireDefault(_resolve); -function NullableTypeAnnotation(node, parent) { - return t.isArrayTypeAnnotation(parent); -} +var _blockHoist = require("../internal-plugins/block-hoist"); -exports.FunctionTypeAnnotation = NullableTypeAnnotation; -function UpdateExpression(node, parent) { - return t.isMemberExpression(parent) && parent.object === node; -} +var _blockHoist2 = _interopRequireDefault(_blockHoist); -function ObjectExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerArrow: true }); -} +var _shadowFunctions = require("../internal-plugins/shadow-functions"); -function DoExpression(node, parent, printStack) { - return isFirstInStatement(printStack); -} +var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); -function Binary(node, parent) { - if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isUnaryLike(parent) || t.isMemberExpression(parent) && parent.object === node || t.isAwaitExpression(parent)) { - return true; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (t.isBinary(parent)) { - var parentOp = parent.operator; - var parentPos = PRECEDENCE[parentOp]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var nodeOp = node.operator; - var nodePos = PRECEDENCE[nodeOp]; +var shebangRegex = /^#!.*/; - if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { - return true; +var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; + +var errorVisitor = { + enter: function enter(path, state) { + var loc = path.node.loc; + if (loc) { + state.loc = loc; + path.stop(); } } +}; - return false; -} +var File = function (_Store) { + (0, _inherits3.default)(File, _Store); -function BinaryExpression(node, parent) { - return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); -} + function File() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var pipeline = arguments[1]; + (0, _classCallCheck3.default)(this, File); -function SequenceExpression(node, parent) { + var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { - return false; - } + _this.pipeline = pipeline; - return true; -} + _this.log = new _logger2.default(_this, opts.filename || "unknown"); + _this.opts = _this.initOptions(opts); -function YieldExpression(node, parent) { - return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) && node === parent.test; -} + _this.parserOpts = { + sourceType: _this.opts.sourceType, + sourceFileName: _this.opts.filename, + plugins: [] + }; -exports.AwaitExpression = YieldExpression; -function ClassExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} + _this.pluginVisitors = []; + _this.pluginPasses = []; -function UnaryLike(node, parent) { - return t.isMemberExpression(parent, { object: node }) || t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node }); -} + _this.buildPluginsForOptions(_this.opts); -function FunctionExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} + if (_this.opts.passPerPreset) { + _this.perPresetOpts = []; + _this.opts.presets.forEach(function (presetOpts) { + var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts); + _this.perPresetOpts.push(perPresetOpts); + _this.buildPluginsForOptions(perPresetOpts); + }); + } -function ArrowFunctionExpression(node, parent) { - if (t.isExportDeclaration(parent) || t.isBinaryExpression(parent) || t.isLogicalExpression(parent) || t.isUnaryExpression(parent) || t.isTaggedTemplateExpression(parent)) { - return true; - } + _this.metadata = { + usedHelpers: [], + marked: [], + modules: { + imports: [], + exports: { + exported: [], + specifiers: [] + } + } + }; - return UnaryLike(node, parent); -} + _this.dynamicImportTypes = {}; + _this.dynamicImportIds = {}; + _this.dynamicImports = []; + _this.declarations = {}; + _this.usedHelpers = {}; -function ConditionalExpression(node, parent) { - if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { test: node }) || t.isAwaitExpression(parent)) { - return true; - } + _this.path = null; + _this.ast = {}; - return UnaryLike(node, parent); -} + _this.code = ""; + _this.shebang = ""; -function AssignmentExpression(node) { - if (t.isObjectPattern(node.left)) { - return true; - } else { - return ConditionalExpression.apply(undefined, arguments); + _this.hub = new _babelTraverse.Hub(_this); + return _this; } -} -function isFirstInStatement(printStack) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$considerArrow = _ref.considerArrow, - considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow, - _ref$considerDefaultE = _ref.considerDefaultExports, - considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; + File.prototype.getMetadata = function getMetadata() { + var has = false; + for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - var i = printStack.length - 1; - var node = printStack[i]; - i--; - var parent = printStack[i]; - while (i > 0) { - if (t.isExpressionStatement(parent, { expression: node }) || t.isTaggedTemplateExpression(parent) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { - return true; - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) { - node = parent; - i--; - parent = printStack[i]; - } else { - return false; + var node = _ref; + + if (t.isModuleDeclaration(node)) { + has = true; + break; + } } - } + if (has) { + this.path.traverse(metadataVisitor, this); + } + }; - return false; -} -},{"babel-types":145}],68:[function(require,module,exports){ -"use strict"; + File.prototype.initOptions = function initOptions(opts) { + opts = new _optionManager2.default(this.log, this.pipeline).init(opts); -var _map = require("lodash/map"); + if (opts.inputSourceMap) { + opts.sourceMaps = true; + } -var _map2 = _interopRequireDefault(_map); + if (opts.moduleId) { + opts.moduleIds = true; + } -var _babelTypes = require("babel-types"); + opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename)); -var t = _interopRequireWildcard(_babelTypes); + opts.ignore = util.arrayify(opts.ignore, util.regexify); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + (0, _defaults2.default)(opts, { + moduleRoot: opts.sourceRoot + }); -function crawl(node) { - var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (0, _defaults2.default)(opts, { + sourceRoot: opts.moduleRoot + }); - if (t.isMemberExpression(node)) { - crawl(node.object, state); - if (node.computed) crawl(node.property, state); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - crawl(node.left, state); - crawl(node.right, state); - } else if (t.isCallExpression(node)) { - state.hasCall = true; - crawl(node.callee, state); - } else if (t.isFunction(node)) { - state.hasFunction = true; - } else if (t.isIdentifier(node)) { - state.hasHelper = state.hasHelper || isHelper(node.callee); - } + (0, _defaults2.default)(opts, { + filenameRelative: opts.filename + }); - return state; -} + var basenameRelative = _path2.default.basename(opts.filenameRelative); -function isHelper(node) { - if (t.isMemberExpression(node)) { - return isHelper(node.object) || isHelper(node.property); - } else if (t.isIdentifier(node)) { - return node.name === "require" || node.name[0] === "_"; - } else if (t.isCallExpression(node)) { - return isHelper(node.callee); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); - } else { - return false; - } -} + (0, _defaults2.default)(opts, { + sourceFileName: basenameRelative, + sourceMapTarget: basenameRelative + }); -function isType(node) { - return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); -} + return opts; + }; -exports.nodes = { - AssignmentExpression: function AssignmentExpression(node) { - var state = crawl(node.right); - if (state.hasCall && state.hasHelper || state.hasFunction) { - return { - before: state.hasFunction, - after: true - }; - } - }, - SwitchCase: function SwitchCase(node, parent) { - return { - before: node.consequent.length || parent.cases[0] === node - }; - }, - LogicalExpression: function LogicalExpression(node) { - if (t.isFunction(node.left) || t.isFunction(node.right)) { - return { - after: true - }; - } - }, - Literal: function Literal(node) { - if (node.value === "use strict") { - return { - after: true - }; - } - }, - CallExpression: function CallExpression(node) { - if (t.isFunction(node.callee) || isHelper(node)) { - return { - before: true, - after: true - }; + File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) { + if (!Array.isArray(opts.plugins)) { + return; } - }, - VariableDeclaration: function VariableDeclaration(node) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - var enabled = isHelper(declar.id) && !isType(declar.init); - if (!enabled) { - var state = crawl(declar.init); - enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + var plugins = opts.plugins.concat(INTERNAL_PLUGINS); + var currentPluginVisitors = []; + var currentPluginPasses = []; + + for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } - if (enabled) { - return { - before: true, - after: true - }; + var ref = _ref2; + var plugin = ref[0], + pluginOpts = ref[1]; + + + currentPluginVisitors.push(plugin.visitor); + currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts)); + + if (plugin.manipulateOptions) { + plugin.manipulateOptions(opts, this.parserOpts, this); } } - }, - IfStatement: function IfStatement(node) { - if (t.isBlockStatement(node.consequent)) { - return { - before: true, - after: true - }; + + this.pluginVisitors.push(currentPluginVisitors); + this.pluginPasses.push(currentPluginPasses); + }; + + File.prototype.getModuleName = function getModuleName() { + var opts = this.opts; + if (!opts.moduleIds) { + return null; } - } -}; -exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { - if (parent.properties[0] === node) { - return { - before: true - }; - } -}; + if (opts.moduleId != null && !opts.getModuleId) { + return opts.moduleId; + } -exports.list = { - VariableDeclaration: function VariableDeclaration(node) { - return (0, _map2.default)(node.declarations, "init"); - }, - ArrayExpression: function ArrayExpression(node) { - return node.elements; - }, - ObjectExpression: function ObjectExpression(node) { - return node.properties; - } -}; - -[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { - var type = _ref[0], - amounts = _ref[1]; - - if (typeof amounts === "boolean") { - amounts = { after: amounts, before: amounts }; - } - [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { - exports.nodes[type] = function () { - return amounts; - }; - }); -}); -},{"babel-types":145,"lodash/map":489}],69:[function(require,module,exports){ -"use strict"; + var filenameRelative = opts.filenameRelative; + var moduleName = ""; -exports.__esModule = true; + if (opts.moduleRoot != null) { + moduleName = opts.moduleRoot + "/"; + } -var _assign = require("babel-runtime/core-js/object/assign"); + if (!opts.filenameRelative) { + return moduleName + opts.filename.replace(/^\//, ""); + } -var _assign2 = _interopRequireDefault(_assign); + if (opts.sourceRoot != null) { + var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); + filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); + } -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); -var _getIterator3 = _interopRequireDefault(_getIterator2); + moduleName += filenameRelative; -var _stringify = require("babel-runtime/core-js/json/stringify"); + moduleName = moduleName.replace(/\\/g, "/"); -var _stringify2 = _interopRequireDefault(_stringify); + if (opts.getModuleId) { + return opts.getModuleId(moduleName) || moduleName; + } else { + return moduleName; + } + }; -var _weakSet = require("babel-runtime/core-js/weak-set"); + File.prototype.resolveModuleSource = function resolveModuleSource(source) { + var resolveModuleSource = this.opts.resolveModuleSource; + if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); + return source; + }; -var _weakSet2 = _interopRequireDefault(_weakSet); + File.prototype.addImport = function addImport(source, imported) { + var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var alias = source + ":" + imported; + var id = this.dynamicImportIds[alias]; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + if (!id) { + source = this.resolveModuleSource(source); + id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); -var _find = require("lodash/find"); + var specifiers = []; -var _find2 = _interopRequireDefault(_find); + if (imported === "*") { + specifiers.push(t.importNamespaceSpecifier(id)); + } else if (imported === "default") { + specifiers.push(t.importDefaultSpecifier(id)); + } else { + specifiers.push(t.importSpecifier(id, t.identifier(imported))); + } -var _findLast = require("lodash/findLast"); + var declar = t.importDeclaration(specifiers, t.stringLiteral(source)); + declar._blockHoist = 3; -var _findLast2 = _interopRequireDefault(_findLast); + this.path.unshiftContainer("body", declar); + } -var _isInteger = require("lodash/isInteger"); + return id; + }; -var _isInteger2 = _interopRequireDefault(_isInteger); + File.prototype.addHelper = function addHelper(name) { + var declar = this.declarations[name]; + if (declar) return declar; -var _repeat = require("lodash/repeat"); + if (!this.usedHelpers[name]) { + this.metadata.usedHelpers.push(name); + this.usedHelpers[name] = true; + } -var _repeat2 = _interopRequireDefault(_repeat); + var generator = this.get("helperGenerator"); + var runtime = this.get("helpersNamespace"); + if (generator) { + var res = generator(name); + if (res) return res; + } else if (runtime) { + return t.memberExpression(runtime, t.identifier(name)); + } -var _buffer = require("./buffer"); + var ref = (0, _babelHelpers2.default)(name); + var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); -var _buffer2 = _interopRequireDefault(_buffer); + if (t.isFunctionExpression(ref) && !ref.id) { + ref.body._compact = true; + ref._generated = true; + ref.id = uid; + ref.type = "FunctionDeclaration"; + this.path.unshiftContainer("body", ref); + } else { + ref._compact = true; + this.scope.push({ + id: uid, + init: ref, + unique: true + }); + } -var _node = require("./node"); + return uid; + }; -var n = _interopRequireWildcard(_node); + File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { + var stringIds = raw.elements.map(function (string) { + return string.value; + }); + var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); -var _whitespace = require("./whitespace"); + var declar = this.declarations[name]; + if (declar) return declar; -var _whitespace2 = _interopRequireDefault(_whitespace); + var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); -var _babelTypes = require("babel-types"); + var helperId = this.addHelper(helperName); + var init = t.callExpression(helperId, [strings, raw]); + init._compact = true; + this.scope.push({ + id: uid, + init: init, + _blockHoist: 1.9 }); + return uid; + }; -var t = _interopRequireWildcard(_babelTypes); + File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) { + var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var loc = node && (node.loc || node._loc); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var err = new Error(msg); -var SCIENTIFIC_NOTATION = /e/i; -var ZERO_DECIMAL_INTEGER = /\.0+$/; -var NON_DECIMAL_LITERAL = /^0[box]/; + if (loc) { + err.loc = loc.start; + } else { + (0, _babelTraverse2.default)(node, errorVisitor, this.scope, err); -var Printer = function () { - function Printer(format, map, tokens) { - (0, _classCallCheck3.default)(this, Printer); - this.inForStatementInitCounter = 0; - this._printStack = []; - this._indent = 0; - this._insideAux = false; - this._printedCommentStarts = {}; - this._parenPushNewlineState = null; - this._printAuxAfterOnNextUserNode = false; - this._printedComments = new _weakSet2.default(); - this._endsWithInteger = false; - this._endsWithWord = false; + err.message += " (This is an error on an internal node. Probably an internal error"; - this.format = format || {}; - this._buf = new _buffer2.default(map); - this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; - } + if (err.loc) { + err.message += ". Location has been estimated."; + } - Printer.prototype.generate = function generate(ast) { - this.print(ast); - this._maybeAddAuxComment(); + err.message += ")"; + } - return this._buf.get(); + return err; }; - Printer.prototype.indent = function indent() { - if (this.format.compact || this.format.concise) return; + File.prototype.mergeSourceMap = function mergeSourceMap(map) { + var inputMap = this.opts.inputSourceMap; - this._indent++; - }; + if (inputMap) { + var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap); + var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map); - Printer.prototype.dedent = function dedent() { - if (this.format.compact || this.format.concise) return; + var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({ + file: inputMapConsumer.file, + sourceRoot: inputMapConsumer.sourceRoot + }); - this._indent--; - }; + var source = outputMapConsumer.sources[0]; - Printer.prototype.semicolon = function semicolon() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + inputMapConsumer.eachMapping(function (mapping) { + var generatedPosition = outputMapConsumer.generatedPositionFor({ + line: mapping.generatedLine, + column: mapping.generatedColumn, + source: source + }); + if (generatedPosition.column != null) { + mergedGenerator.addMapping({ + source: mapping.source, - this._maybeAddAuxComment(); - this._append(";", !force); - }; + original: mapping.source == null ? null : { + line: mapping.originalLine, + column: mapping.originalColumn + }, - Printer.prototype.rightBrace = function rightBrace() { - if (this.format.minified) { - this._buf.removeLastSemicolon(); + generated: generatedPosition + }); + } + }); + + var mergedMap = mergedGenerator.toJSON(); + inputMap.mappings = mergedMap.mappings; + return inputMap; + } else { + return map; } - this.token("}"); }; - Printer.prototype.space = function space() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + File.prototype.parse = function parse(code) { + var parseCode = _babylon.parse; + var parserOpts = this.opts.parserOpts; - if (this.format.compact) return; + if (parserOpts) { + parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); - if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { - this._space(); + if (parserOpts.parser) { + if (typeof parserOpts.parser === "string") { + var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); + var parser = (0, _resolve2.default)(parserOpts.parser, dirname); + if (parser) { + parseCode = require(parser).parse; + } else { + throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname)); + } + } else { + parseCode = parserOpts.parser; + } + + parserOpts.parser = { + parse: function parse(source) { + return (0, _babylon.parse)(source, parserOpts); + } + }; + } } - }; - Printer.prototype.word = function word(str) { - if (this._endsWithWord) this._space(); + this.log.debug("Parse start"); + var ast = parseCode(code, parserOpts || this.parserOpts); + this.log.debug("Parse stop"); + return ast; + }; - this._maybeAddAuxComment(); - this._append(str); + File.prototype._addAst = function _addAst(ast) { + this.path = _babelTraverse.NodePath.get({ + hub: this.hub, + parentPath: null, + parent: ast, + container: ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + this.ast = ast; + this.getMetadata(); + }; - this._endsWithWord = true; + File.prototype.addAst = function addAst(ast) { + this.log.debug("Start set AST"); + this._addAst(ast); + this.log.debug("End set AST"); }; - Printer.prototype.number = function number(str) { - this.word(str); + File.prototype.transform = function transform() { + for (var i = 0; i < this.pluginPasses.length; i++) { + var pluginPasses = this.pluginPasses[i]; + this.call("pre", pluginPasses); + this.log.debug("Start transform traverse"); - this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; - }; + var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); + (0, _babelTraverse2.default)(this.ast, visitor, this.scope); - Printer.prototype.token = function token(str) { - if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { - this._space(); + this.log.debug("End transform traverse"); + this.call("post", pluginPasses); } - this._maybeAddAuxComment(); - this._append(str); + return this.generate(); }; - Printer.prototype.newline = function newline(i) { - if (this.format.retainLines || this.format.compact) return; + File.prototype.wrap = function wrap(code, callback) { + code = code + ""; - if (this.format.concise) { - this.space(); - return; - } + try { + if (this.shouldIgnore()) { + return this.makeResult({ code: code, ignored: true }); + } else { + return callback(); + } + } catch (err) { + if (err._babel) { + throw err; + } else { + err._babel = true; + } - if (this.endsWith("\n\n")) return; + var message = err.message = this.opts.filename + ": " + err.message; - if (typeof i !== "number") i = 1; + var loc = err.loc; + if (loc) { + err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); + message += "\n" + err.codeFrame; + } - i = Math.min(2, i); - if (this.endsWith("{\n") || this.endsWith(":\n")) i--; - if (i <= 0) return; + if (process.browser) { + err.message = message; + } - for (var j = 0; j < i; j++) { - this._newline(); + if (err.stack) { + var newStack = err.stack.replace(err.message, message); + err.stack = newStack; + } + + throw err; } }; - Printer.prototype.endsWith = function endsWith(str) { - return this._buf.endsWith(str); + File.prototype.addCode = function addCode(code) { + code = (code || "") + ""; + code = this.parseInputSourceMap(code); + this.code = code; }; - Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { - this._buf.removeTrailingNewline(); + File.prototype.parseCode = function parseCode() { + this.parseShebang(); + var ast = this.parse(this.code); + this.addAst(ast); }; - Printer.prototype.source = function source(prop, loc) { - this._catchUp(prop, loc); - - this._buf.source(prop, loc); + File.prototype.shouldIgnore = function shouldIgnore() { + var opts = this.opts; + return util.shouldIgnore(opts.filename, opts.ignore, opts.only); }; - Printer.prototype.withSource = function withSource(prop, loc, cb) { - this._catchUp(prop, loc); + File.prototype.call = function call(key, pluginPasses) { + for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - this._buf.withSource(prop, loc, cb); - }; + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } - Printer.prototype._space = function _space() { - this._append(" ", true); - }; + var pass = _ref3; - Printer.prototype._newline = function _newline() { - this._append("\n", true); + var plugin = pass.plugin; + var fn = plugin[key]; + if (fn) fn.call(pass, this); + } }; - Printer.prototype._append = function _append(str) { - var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - this._maybeAddParen(str); - this._maybeIndent(str); + File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { + var opts = this.opts; - if (queue) this._buf.queue(str);else this._buf.append(str); + if (opts.inputSourceMap !== false) { + var inputMap = _convertSourceMap2.default.fromSource(code); + if (inputMap) { + opts.inputSourceMap = inputMap.toObject(); + code = _convertSourceMap2.default.removeComments(code); + } + } - this._endsWithWord = false; - this._endsWithInteger = false; + return code; }; - Printer.prototype._maybeIndent = function _maybeIndent(str) { - if (this._indent && this.endsWith("\n") && str[0] !== "\n") { - this._buf.queue(this._getIndent()); + File.prototype.parseShebang = function parseShebang() { + var shebangMatch = shebangRegex.exec(this.code); + if (shebangMatch) { + this.shebang = shebangMatch[0]; + this.code = this.code.replace(shebangRegex, ""); } }; - Printer.prototype._maybeAddParen = function _maybeAddParen(str) { - var parenPushNewlineState = this._parenPushNewlineState; - if (!parenPushNewlineState) return; - this._parenPushNewlineState = null; + File.prototype.makeResult = function makeResult(_ref4) { + var code = _ref4.code, + map = _ref4.map, + ast = _ref4.ast, + ignored = _ref4.ignored; - var i = void 0; - for (i = 0; i < str.length && str[i] === " "; i++) { - continue; - }if (i === str.length) return; + var result = { + metadata: null, + options: this.opts, + ignored: !!ignored, + code: null, + ast: null, + map: map || null + }; - var cha = str[i]; - if (cha === "\n" || cha === "/") { - this.token("("); - this.indent(); - parenPushNewlineState.printed = true; + if (this.opts.code) { + result.code = code; } - }; - - Printer.prototype._catchUp = function _catchUp(prop, loc) { - if (!this.format.retainLines) return; - var pos = loc ? loc[prop] : null; - if (pos && pos.line !== null) { - var count = pos.line - this._buf.getCurrentLine(); - - for (var i = 0; i < count; i++) { - this._newline(); - } + if (this.opts.ast) { + result.ast = ast; } - }; - Printer.prototype._getIndent = function _getIndent() { - return (0, _repeat2.default)(this.format.indent.style, this._indent); - }; + if (this.opts.metadata) { + result.metadata = this.metadata; + } - Printer.prototype.startTerminatorless = function startTerminatorless() { - return this._parenPushNewlineState = { - printed: false - }; + return result; }; - Printer.prototype.endTerminatorless = function endTerminatorless(state) { - if (state.printed) { - this.dedent(); - this.newline(); - this.token(")"); - } - }; + File.prototype.generate = function generate() { + var opts = this.opts; + var ast = this.ast; - Printer.prototype.print = function print(node, parent) { - var _this = this; + var result = { ast: ast }; + if (!opts.code) return this.makeResult(result); - if (!node) return; + var gen = _babelGenerator2.default; + if (opts.generatorOpts.generator) { + gen = opts.generatorOpts.generator; - var oldConcise = this.format.concise; - if (node._compact) { - this.format.concise = true; + if (typeof gen === "string") { + var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); + var generator = (0, _resolve2.default)(gen, dirname); + if (generator) { + gen = require(generator).print; + } else { + throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname)); + } + } } - var printMethod = this[node.type]; - if (!printMethod) { - throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); - } + this.log.debug("Generation start"); - this._printStack.push(node); + var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); + result.code = _result.code; + result.map = _result.map; - var oldInAux = this._insideAux; - this._insideAux = !node.loc; - this._maybeAddAuxComment(this._insideAux && !oldInAux); + this.log.debug("Generation end"); - var needsParens = n.needsParens(node, parent, this._printStack); - if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { - needsParens = true; + if (this.shebang) { + result.code = this.shebang + "\n" + result.code; } - if (needsParens) this.token("("); - - this._printLeadingComments(node, parent); - var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; - this.withSource("start", loc, function () { - _this[node.type](node, parent); - }); - - this._printTrailingComments(node, parent); - - if (needsParens) this.token(")"); + if (result.map) { + result.map = this.mergeSourceMap(result.map); + } - this._printStack.pop(); + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment(); + } - this.format.concise = oldConcise; - this._insideAux = oldInAux; - }; + if (opts.sourceMaps === "inline") { + result.map = null; + } - Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { - if (enteredPositionlessNode) this._printAuxBeforeComment(); - if (!this._insideAux) this._printAuxAfterComment(); + return this.makeResult(result); }; - Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { - if (this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = true; + return File; +}(_store2.default); - var comment = this.format.auxiliaryCommentBefore; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; +exports.default = File; +exports.File = File; +}).call(this,require('_process')) +},{"../../helpers/resolve":71,"../../store":72,"../../util":88,"../internal-plugins/block-hoist":83,"../internal-plugins/shadow-functions":84,"../plugin-pass":86,"./logger":75,"./metadata":76,"./options/option-manager":80,"_process":15,"babel-code-frame":61,"babel-generator":101,"babel-helpers":114,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/object/assign":131,"babel-runtime/core-js/object/create":132,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144,"babel-traverse":150,"babel-types":183,"babylon":187,"convert-source-map":192,"lodash/defaults":497,"path":13,"source-map":572}],75:[function(require,module,exports){ +"use strict"; - Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { - if (!this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = false; +exports.__esModule = true; - var comment = this.format.auxiliaryCommentAfter; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { - var extra = node.extra; - if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { - return extra.raw; - } - }; +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - Printer.prototype.printJoin = function printJoin(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +var _node = require("debug/node"); - if (!nodes || !nodes.length) return; +var _node2 = _interopRequireDefault(_node); - if (opts.indent) this.indent(); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var newlineOpts = { - addNewlines: opts.addNewlines - }; +var verboseDebug = (0, _node2.default)("babel:verbose"); +var generalDebug = (0, _node2.default)("babel"); - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; +var seenDeprecatedMessages = []; - if (opts.statement) this._printNewline(true, node, parent, newlineOpts); +var Logger = function () { + function Logger(file, filename) { + (0, _classCallCheck3.default)(this, Logger); - this.print(node, parent); + this.filename = filename; + this.file = file; + } - if (opts.iterator) { - opts.iterator(node, i); - } + Logger.prototype._buildMessage = function _buildMessage(msg) { + var parts = "[BABEL] " + this.filename; + if (msg) parts += ": " + msg; + return parts; + }; - if (opts.separator && i < nodes.length - 1) { - opts.separator.call(this); - } + Logger.prototype.warn = function warn(msg) { + console.warn(this._buildMessage(msg)); + }; - if (opts.statement) this._printNewline(false, node, parent, newlineOpts); - } + Logger.prototype.error = function error(msg) { + var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; - if (opts.indent) this.dedent(); + throw new Constructor(this._buildMessage(msg)); }; - Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { - var indent = !!node.leadingComments; - if (indent) this.indent(); - this.print(node, parent); - if (indent) this.dedent(); - }; + Logger.prototype.deprecate = function deprecate(msg) { + if (this.file.opts && this.file.opts.suppressDeprecationMessages) return; - Printer.prototype.printBlock = function printBlock(parent) { - var node = parent.body; + msg = this._buildMessage(msg); - if (!t.isEmptyStatement(node)) { - this.space(); - } + if (seenDeprecatedMessages.indexOf(msg) >= 0) return; - this.print(node, parent); - }; + seenDeprecatedMessages.push(msg); - Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) { - this._printComments(this._getComments(false, node, parent)); + console.error(msg); }; - Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { - this._printComments(this._getComments(true, node, parent)); + Logger.prototype.verbose = function verbose(msg) { + if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg)); }; - Printer.prototype.printInnerComments = function printInnerComments(node) { - var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (!node.innerComments) return; - if (indent) this.indent(); - this._printComments(node.innerComments); - if (indent) this.dedent(); + Logger.prototype.debug = function debug(msg) { + if (generalDebug.enabled) generalDebug(this._buildMessage(msg)); }; - Printer.prototype.printSequence = function printSequence(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - opts.statement = true; - return this.printJoin(nodes, parent, opts); + Logger.prototype.deopt = function deopt(node, msg) { + this.debug(msg); }; - Printer.prototype.printList = function printList(items, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return Logger; +}(); - if (opts.separator == null) { - opts.separator = commaSeparator; - } +exports.default = Logger; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":141,"debug/node":308}],76:[function(require,module,exports){ +"use strict"; - return this.printJoin(items, parent, opts); - }; +exports.__esModule = true; +exports.ImportDeclaration = exports.ModuleDeclaration = undefined; - Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { - var _this2 = this; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - if (this.format.retainLines || this.format.compact) return; +var _getIterator3 = _interopRequireDefault(_getIterator2); - if (this.format.concise) { - this.space(); - return; - } +exports.ExportDeclaration = ExportDeclaration; +exports.Scope = Scope; - var lines = 0; +var _babelTypes = require("babel-types"); - if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { - if (leading) { - var _comments = node.leadingComments; - var _comment = _comments && (0, _find2.default)(_comments, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); +var t = _interopRequireWildcard(_babelTypes); - lines = this._whitespace.getNewlinesBefore(_comment || node); - } else { - var _comments2 = node.trailingComments; - var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - lines = this._whitespace.getNewlinesAfter(_comment2 || node); - } - } else { - if (!leading) lines++; - if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var needs = n.needsWhitespaceAfter; - if (leading) needs = n.needsWhitespaceBefore; - if (needs(node, parent)) lines++; +var ModuleDeclaration = exports.ModuleDeclaration = { + enter: function enter(path, file) { + var node = path.node; - if (!this._buf.hasContent()) lines = 0; + if (node.source) { + node.source.value = file.resolveModuleSource(node.source.value); } + } +}; - this.newline(lines); - }; - - Printer.prototype._getComments = function _getComments(leading, node) { - return node && (leading ? node.leadingComments : node.trailingComments) || []; - }; - - Printer.prototype._printComment = function _printComment(comment) { - var _this3 = this; +var ImportDeclaration = exports.ImportDeclaration = { + exit: function exit(path, file) { + var node = path.node; - if (!this.format.shouldPrintComment(comment.value)) return; - if (comment.ignore) return; + var specifiers = []; + var imported = []; + file.metadata.modules.imports.push({ + source: node.source.value, + imported: imported, + specifiers: specifiers + }); - if (this._printedComments.has(comment)) return; - this._printedComments.add(comment); + for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (comment.start != null) { - if (this._printedCommentStarts[comment.start]) return; - this._printedCommentStarts[comment.start] = true; - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); + var specifier = _ref; - if (!this.endsWith("[") && !this.endsWith("{")) this.space(); + var local = specifier.node.local.name; - var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; + if (specifier.isImportDefaultSpecifier()) { + imported.push("default"); + specifiers.push({ + kind: "named", + imported: "default", + local: local + }); + } - if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { - var offset = comment.loc && comment.loc.start.column; - if (offset) { - var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); - val = val.replace(newlineRegex, "\n"); + if (specifier.isImportSpecifier()) { + var importedName = specifier.node.imported.name; + imported.push(importedName); + specifiers.push({ + kind: "named", + imported: importedName, + local: local + }); } - var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); - val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); + if (specifier.isImportNamespaceSpecifier()) { + imported.push("*"); + specifiers.push({ + kind: "namespace", + local: local + }); + } } + } +}; - this.withSource("start", comment.loc, function () { - _this3._append(val); - }); +function ExportDeclaration(path, file) { + var node = path.node; - this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); - }; - Printer.prototype._printComments = function _printComments(comments) { - if (!comments || !comments.length) return; + var source = node.source ? node.source.value : null; + var exports = file.metadata.modules.exports; - for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var declar = path.get("declaration"); + if (declar.isStatement()) { + var bindings = declar.getBindingIdentifiers(); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; + for (var name in bindings) { + exports.exported.push(name); + exports.specifiers.push({ + kind: "local", + local: name, + exported: path.isExportDefaultDeclaration() ? "default" : name + }); + } + } + + if (path.isExportNamedDeclaration() && node.specifiers) { + for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } - var _comment3 = _ref; + var specifier = _ref2; - this._printComment(_comment3); - } - }; + var exported = specifier.exported.name; + exports.exported.push(exported); - return Printer; -}(); + if (t.isExportDefaultSpecifier(specifier)) { + exports.specifiers.push({ + kind: "external", + local: exported, + exported: exported, + source: source + }); + } -exports.default = Printer; + if (t.isExportNamespaceSpecifier(specifier)) { + exports.specifiers.push({ + kind: "external-namespace", + exported: exported, + source: source + }); + } + var local = specifier.local; + if (!local) continue; -function commaSeparator() { - this.token(","); - this.space(); + if (source) { + exports.specifiers.push({ + kind: "external", + local: local.name, + exported: exported, + source: source + }); + } + + if (!source) { + exports.specifiers.push({ + kind: "local", + local: local.name, + exported: exported + }); + } + } + } + + if (path.isExportAllDeclaration()) { + exports.specifiers.push({ + kind: "external-all", + source: source + }); + } } -var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; -for (var _i2 = 0; _i2 < _arr.length; _i2++) { - var generator = _arr[_i2]; - (0, _assign2.default)(Printer.prototype, generator); +function Scope(path) { + path.skip(); } -module.exports = exports["default"]; -},{"./buffer":54,"./generators/base":55,"./generators/classes":56,"./generators/expressions":57,"./generators/flow":58,"./generators/jsx":59,"./generators/methods":60,"./generators/modules":61,"./generators/statements":62,"./generators/template-literals":63,"./generators/types":64,"./node":66,"./whitespace":71,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/json/stringify":90,"babel-runtime/core-js/object/assign":93,"babel-runtime/core-js/weak-set":102,"babel-runtime/helpers/classCallCheck":103,"babel-types":145,"lodash/find":463,"lodash/findLast":465,"lodash/isInteger":478,"lodash/repeat":494}],70:[function(require,module,exports){ +},{"babel-runtime/core-js/get-iterator":127,"babel-types":183}],77:[function(require,module,exports){ +(function (process){ "use strict"; exports.__esModule = true; -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _typeof2 = require("babel-runtime/helpers/typeof"); +var _assign = require("babel-runtime/core-js/object/assign"); -var _typeof3 = _interopRequireDefault(_typeof2); +var _assign2 = _interopRequireDefault(_assign); var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -var _sourceMap = require("source-map"); +exports.default = buildConfigChain; -var _sourceMap2 = _interopRequireDefault(_sourceMap); +var _resolve = require("../../../helpers/resolve"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _resolve2 = _interopRequireDefault(_resolve); -var SourceMap = function () { - function SourceMap(opts, code) { - (0, _classCallCheck3.default)(this, SourceMap); +var _json = require("json5"); - this._cachedMap = null; - this._code = code; - this._opts = opts; - this._rawMappings = []; - } +var _json2 = _interopRequireDefault(_json); - SourceMap.prototype.get = function get() { - if (!this._cachedMap) { - var map = this._cachedMap = new _sourceMap2.default.SourceMapGenerator({ - file: this._opts.sourceMapTarget, - sourceRoot: this._opts.sourceRoot - }); +var _pathIsAbsolute = require("path-is-absolute"); - var code = this._code; - if (typeof code === "string") { - map.setSourceContent(this._opts.sourceFileName, code); - } else if ((typeof code === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { - (0, _keys2.default)(code).forEach(function (sourceFileName) { - map.setSourceContent(sourceFileName, code[sourceFileName]); - }); - } +var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); - this._rawMappings.forEach(map.addMapping, map); - } +var _path = require("path"); - return this._cachedMap.toJSON(); - }; +var _path2 = _interopRequireDefault(_path); - SourceMap.prototype.getRawMappings = function getRawMappings() { - return this._rawMappings.slice(); - }; +var _fs = require("fs"); - SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { - if (this._lastGenLine !== generatedLine && line === null) return; +var _fs2 = _interopRequireDefault(_fs); - if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { - return; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - this._cachedMap = null; - this._lastGenLine = generatedLine; - this._lastSourceLine = line; - this._lastSourceColumn = column; +var existsCache = {}; +var jsonCache = {}; - this._rawMappings.push({ - name: identifierName || undefined, - generated: { - line: generatedLine, - column: generatedColumn - }, - source: line == null ? undefined : filename || this._opts.sourceFileName, - original: line == null ? undefined : { - line: line, - column: column - } - }); - }; +var BABELIGNORE_FILENAME = ".babelignore"; +var BABELRC_FILENAME = ".babelrc"; +var PACKAGE_FILENAME = "package.json"; - return SourceMap; -}(); +function exists(filename) { + var cached = existsCache[filename]; + if (cached == null) { + return existsCache[filename] = _fs2.default.existsSync(filename); + } else { + return cached; + } +} -exports.default = SourceMap; -module.exports = exports["default"]; -},{"babel-runtime/core-js/object/keys":96,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/typeof":107,"source-map":534}],71:[function(require,module,exports){ -"use strict"; +function buildConfigChain() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var log = arguments[1]; -exports.__esModule = true; + var filename = opts.filename; + var builder = new ConfigChainBuilder(log); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + if (opts.babelrc !== false) { + builder.findConfigs(filename); + } -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + builder.mergeConfig({ + options: opts, + alias: "base", + dirname: filename && _path2.default.dirname(filename) + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return builder.configs; +} -var Whitespace = function () { - function Whitespace(tokens) { - (0, _classCallCheck3.default)(this, Whitespace); +var ConfigChainBuilder = function () { + function ConfigChainBuilder(log) { + (0, _classCallCheck3.default)(this, ConfigChainBuilder); - this.tokens = tokens; - this.used = {}; + this.resolvedConfigs = []; + this.configs = []; + this.log = log; } - Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; + ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { + if (!loc) return; - var index = this._findToken(function (token) { - return token.start - node.start; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.start === tokens[index - 1].start) { - --index; - }startToken = tokens[index - 1]; - endToken = tokens[index]; + if (!(0, _pathIsAbsolute2.default)(loc)) { + loc = _path2.default.join(process.cwd(), loc); } - return this._getNewlinesBetween(startToken, endToken); + var foundConfig = false; + var foundIgnore = false; + + while (loc !== (loc = _path2.default.dirname(loc))) { + if (!foundConfig) { + var configLoc = _path2.default.join(loc, BABELRC_FILENAME); + if (exists(configLoc)) { + this.addConfig(configLoc); + foundConfig = true; + } + + var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME); + if (!foundConfig && exists(pkgLoc)) { + foundConfig = this.addConfig(pkgLoc, "babel", JSON); + } + } + + if (!foundIgnore) { + var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME); + if (exists(ignoreLoc)) { + this.addIgnoreConfig(ignoreLoc); + foundIgnore = true; + } + } + + if (foundIgnore && foundConfig) return; + } }; - Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; + ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) { + var file = _fs2.default.readFileSync(loc, "utf8"); + var lines = file.split("\n"); - var index = this._findToken(function (token) { - return token.end - node.end; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.end === tokens[index - 1].end) { - --index; - }startToken = tokens[index]; - endToken = tokens[index + 1]; - if (endToken.type.label === ",") endToken = tokens[index + 2]; + lines = lines.map(function (line) { + return line.replace(/#(.*?)$/, "").trim(); + }).filter(function (line) { + return !!line; + }); + + if (lines.length) { + this.mergeConfig({ + options: { ignore: lines }, + alias: loc, + dirname: _path2.default.dirname(loc) + }); } + }; - if (endToken && endToken.type.label === "eof") { - return 1; - } else { - return this._getNewlinesBetween(startToken, endToken); + ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { + var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default; + + if (this.resolvedConfigs.indexOf(loc) >= 0) { + return false; + } + + this.resolvedConfigs.push(loc); + + var content = _fs2.default.readFileSync(loc, "utf8"); + var options = void 0; + + try { + options = jsonCache[content] = jsonCache[content] || json.parse(content); + if (key) options = options[key]; + } catch (err) { + err.message = loc + ": Error while parsing JSON - " + err.message; + throw err; } + + this.mergeConfig({ + options: options, + alias: loc, + dirname: _path2.default.dirname(loc) + }); + + return !!options; }; - Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) { - if (!endToken || !endToken.loc) return 0; + ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { + var options = _ref.options, + alias = _ref.alias, + loc = _ref.loc, + dirname = _ref.dirname; - var start = startToken ? startToken.loc.end.line : 1; - var end = endToken.loc.start.line; - var lines = 0; + if (!options) { + return false; + } - for (var line = start; line < end; line++) { - if (typeof this.used[line] === "undefined") { - this.used[line] = true; - lines++; + options = (0, _assign2.default)({}, options); + + dirname = dirname || process.cwd(); + loc = loc || alias; + + if (options.extends) { + var extendsLoc = (0, _resolve2.default)(options.extends, dirname); + if (extendsLoc) { + this.addConfig(extendsLoc); + } else { + if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); } + delete options.extends; } - return lines; - }; + this.configs.push({ + options: options, + alias: alias, + loc: loc, + dirname: dirname + }); - Whitespace.prototype._findToken = function _findToken(test, start, end) { - if (start >= end) return -1; - var middle = start + end >>> 1; - var match = test(this.tokens[middle]); - if (match < 0) { - return this._findToken(test, middle + 1, end); - } else if (match > 0) { - return this._findToken(test, start, middle); - } else if (match === 0) { - return middle; + var envOpts = void 0; + var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; + if (options.env) { + envOpts = options.env[envKey]; + delete options.env; } - return -1; + + this.mergeConfig({ + options: envOpts, + alias: alias + ".env." + envKey, + dirname: dirname + }); }; - return Whitespace; + return ConfigChainBuilder; }(); -exports.default = Whitespace; module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":103}],72:[function(require,module,exports){ +}).call(this,require('_process')) +},{"../../../helpers/resolve":71,"_process":15,"babel-runtime/core-js/object/assign":131,"babel-runtime/helpers/classCallCheck":141,"fs":1,"json5":326,"path":13,"path-is-absolute":547}],78:[function(require,module,exports){ "use strict"; -exports.__esModule = true; +module.exports = { + filename: { + type: "filename", + description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", + default: "unknown", + shorthand: "f" + }, -var _keys = require("babel-runtime/core-js/object/keys"); + filenameRelative: { + hidden: true, + type: "string" + }, -var _keys2 = _interopRequireDefault(_keys); + inputSourceMap: { + hidden: true + }, -exports.push = push; -exports.hasComputed = hasComputed; -exports.toComputedObjectFromClass = toComputedObjectFromClass; -exports.toClassObject = toClassObject; -exports.toDefineObject = toDefineObject; + env: { + hidden: true, + default: {} + }, -var _babelHelperFunctionName = require("babel-helper-function-name"); + mode: { + description: "", + hidden: true + }, -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + retainLines: { + type: "boolean", + default: false, + description: "retain line numbers - will result in really ugly code" + }, -var _has = require("lodash/has"); + highlightCode: { + description: "enable/disable ANSI syntax highlighting of code frames (on by default)", + type: "boolean", + default: true + }, -var _has2 = _interopRequireDefault(_has); + suppressDeprecationMessages: { + type: "boolean", + default: false, + hidden: true + }, -var _babelTypes = require("babel-types"); + presets: { + type: "list", + description: "", + default: [] + }, -var t = _interopRequireWildcard(_babelTypes); + plugins: { + type: "list", + default: [], + description: "" + }, -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + ignore: { + type: "list", + description: "list of glob paths to **not** compile", + default: [] + }, -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + only: { + type: "list", + description: "list of glob paths to **only** compile" + }, -function toKind(node) { - if (t.isClassMethod(node) || t.isObjectMethod(node)) { - if (node.kind === "get" || node.kind === "set") { - return node.kind; - } - } + code: { + hidden: true, + default: true, + type: "boolean" + }, - return "value"; -} + metadata: { + hidden: true, + default: true, + type: "boolean" + }, -function push(mutatorMap, node, kind, file, scope) { - var alias = t.toKeyAlias(node); + ast: { + hidden: true, + default: true, + type: "boolean" + }, - var map = {}; - if ((0, _has2.default)(mutatorMap, alias)) map = mutatorMap[alias]; - mutatorMap[alias] = map; + extends: { + type: "string", + hidden: true + }, - map._inherits = map._inherits || []; - map._inherits.push(node); + comments: { + type: "boolean", + default: true, + description: "write comments to generated output (true by default)" + }, - map._key = node.key; + shouldPrintComment: { + hidden: true, + description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" + }, - if (node.computed) { - map._computed = true; - } + wrapPluginVisitorMethod: { + hidden: true, + description: "optional callback to wrap all visitor methods" + }, - if (node.decorators) { - var decorators = map.decorators = map.decorators || t.arrayExpression([]); - decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) { - return dec.expression; - }).reverse()); - } + compact: { + type: "booleanString", + default: "auto", + description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" + }, - if (map.value || map.initializer) { - throw file.buildCodeFrameError(node, "Key conflict with sibling node"); - } + minified: { + type: "boolean", + default: false, + description: "save as much bytes when printing [true|false]" + }, - var key = void 0, - value = void 0; + sourceMap: { + alias: "sourceMaps", + hidden: true + }, - if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { - key = t.toComputedKey(node, node.key); - } + sourceMaps: { + type: "booleanString", + description: "[true|false|inline]", + default: false, + shorthand: "s" + }, - if (t.isObjectProperty(node) || t.isClassProperty(node)) { - value = node.value; - } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { - value = t.functionExpression(null, node.params, node.body, node.generator, node.async); - value.returnType = node.returnType; - } + sourceMapTarget: { + type: "string", + description: "set `file` on returned source map" + }, - var inheritedKind = toKind(node); - if (!kind || inheritedKind !== "value") { - kind = inheritedKind; - } + sourceFileName: { + type: "string", + description: "set `sources[0]` on returned source map" + }, - if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { - value = (0, _babelHelperFunctionName2.default)({ id: key, node: value, scope: scope }); - } + sourceRoot: { + type: "filename", + description: "the root from which all sources are relative" + }, - if (value) { - t.inheritsComments(value, node); - map[kind] = value; - } + babelrc: { + description: "Whether or not to look up .babelrc and .babelignore files", + type: "boolean", + default: true + }, - return map; -} + sourceType: { + description: "", + default: "module" + }, -function hasComputed(mutatorMap) { - for (var key in mutatorMap) { - if (mutatorMap[key]._computed) { - return true; - } - } - return false; -} + auxiliaryCommentBefore: { + type: "string", + description: "print a comment before any injected non-user code" + }, -function toComputedObjectFromClass(obj) { - var objExpr = t.arrayExpression([]); + auxiliaryCommentAfter: { + type: "string", + description: "print a comment after any injected non-user code" + }, - for (var i = 0; i < obj.properties.length; i++) { - var prop = obj.properties[i]; - var val = prop.value; - val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); - objExpr.elements.push(val); + resolveModuleSource: { + hidden: true + }, + + getModuleId: { + hidden: true + }, + + moduleRoot: { + type: "filename", + description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" + }, + + moduleIds: { + type: "boolean", + default: false, + shorthand: "M", + description: "insert an explicit id for modules" + }, + + moduleId: { + description: "specify a custom name for module ids", + type: "string" + }, + + passPerPreset: { + description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.", + type: "boolean", + default: false, + hidden: true + }, + + parserOpts: { + description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", + default: false + }, + + generatorOpts: { + description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", + default: false } +}; +},{}],79:[function(require,module,exports){ +"use strict"; - return objExpr; -} +exports.__esModule = true; +exports.config = undefined; +exports.normaliseOptions = normaliseOptions; -function toClassObject(mutatorMap) { - var objExpr = t.objectExpression([]); +var _parsers = require("./parsers"); - (0, _keys2.default)(mutatorMap).forEach(function (mutatorMapKey) { - var map = mutatorMap[mutatorMapKey]; - var mapNode = t.objectExpression([]); +var parsers = _interopRequireWildcard(_parsers); - var propNode = t.objectProperty(map._key, mapNode, map._computed); +var _config = require("./config"); - (0, _keys2.default)(map).forEach(function (key) { - var node = map[key]; - if (key[0] === "_") return; +var _config2 = _interopRequireDefault(_config); - var inheritNode = node; - if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var prop = t.objectProperty(t.identifier(key), node); - t.inheritsComments(prop, inheritNode); - t.removeComments(inheritNode); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - mapNode.properties.push(prop); - }); +exports.config = _config2.default; +function normaliseOptions() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - objExpr.properties.push(propNode); - }); + for (var key in options) { + var val = options[key]; + if (val == null) continue; - return objExpr; -} + var opt = _config2.default[key]; + if (opt && opt.alias) opt = _config2.default[opt.alias]; + if (!opt) continue; -function toDefineObject(mutatorMap) { - (0, _keys2.default)(mutatorMap).forEach(function (key) { - var map = mutatorMap[key]; - if (map.value) map.writable = t.booleanLiteral(true); - map.configurable = t.booleanLiteral(true); - map.enumerable = t.booleanLiteral(true); - }); + var parser = parsers[opt.type]; + if (parser) val = parser(val); - return toClassObject(mutatorMap); + options[key] = val; + } + + return options; } -},{"babel-helper-function-name":73,"babel-runtime/core-js/object/keys":96,"babel-types":145,"lodash/has":468}],73:[function(require,module,exports){ +},{"./config":78,"./parsers":81}],80:[function(require,module,exports){ +(function (process){ "use strict"; exports.__esModule = true; -exports.default = function (_ref) { - var node = _ref.node, - parent = _ref.parent, - scope = _ref.scope, - id = _ref.id; +var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties"); - if (node.id) return; +var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); - if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t.isLiteral(parent.key))) { - id = parent.key; - } else if (t.isVariableDeclarator(parent)) { - id = parent.id; +var _stringify = require("babel-runtime/core-js/json/stringify"); - if (t.isIdentifier(id)) { - var binding = scope.parent.getBinding(id.name); - if (binding && binding.constant && scope.getBinding(id.name) === binding) { - node.id = id; - node.id[t.NOT_LOCAL_BINDING] = true; - return; - } - } - } else if (t.isAssignmentExpression(parent)) { - id = parent.left; - } else if (!id) { - return; - } - - var name = void 0; - if (id && t.isLiteral(id)) { - name = id.value; - } else if (id && t.isIdentifier(id)) { - name = id.name; - } else { - return; - } - - name = t.toBindingIdentifierName(name); - id = t.identifier(name); - - id[t.NOT_LOCAL_BINDING] = true; - - var state = visit(node, name, scope); - return wrap(state, node, id, scope) || node; -}; +var _stringify2 = _interopRequireDefault(_stringify); -var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); +var _assign = require("babel-runtime/core-js/object/assign"); -var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); +var _assign2 = _interopRequireDefault(_assign); -var _babelTemplate = require("babel-template"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +var _getIterator3 = _interopRequireDefault(_getIterator2); -var _babelTypes = require("babel-types"); +var _typeof2 = require("babel-runtime/helpers/typeof"); -var t = _interopRequireWildcard(_babelTypes); +var _typeof3 = _interopRequireDefault(_typeof2); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -var buildPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); +var _node = require("../../../api/node"); -var buildGeneratorPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); +var context = _interopRequireWildcard(_node); -var visitor = { - "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { - if (path.node.name !== state.name) return; +var _plugin2 = require("../../plugin"); - var localDeclar = path.scope.getBindingIdentifier(state.name); - if (localDeclar !== state.outerDeclar) return; +var _plugin3 = _interopRequireDefault(_plugin2); - state.selfReference = true; - path.stop(); - } -}; +var _babelMessages = require("babel-messages"); -function wrap(state, method, id, scope) { - if (state.selfReference) { - if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { - scope.rename(id.name); - } else { - if (!t.isFunction(method)) return; +var messages = _interopRequireWildcard(_babelMessages); - var build = buildPropertyMethodAssignmentWrapper; - if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; - var _template = build({ - FUNCTION: method, - FUNCTION_ID: id, - FUNCTION_KEY: scope.generateUidIdentifier(id.name) - }).expression; - _template.callee._skipModulesRemap = true; +var _index = require("./index"); - var params = _template.callee.body.body[0].params; - for (var i = 0, len = (0, _babelHelperGetFunctionArity2.default)(method); i < len; i++) { - params.push(scope.generateUidIdentifier("x")); - } +var _resolvePlugin = require("../../../helpers/resolve-plugin"); - return _template; - } - } +var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin); - method.id = id; - scope.getProgramParent().references[id.name] = true; -} +var _resolvePreset = require("../../../helpers/resolve-preset"); -function visit(node, name, scope) { - var state = { - selfAssignment: false, - selfReference: false, - outerDeclar: scope.getBindingIdentifier(name), - references: [], - name: name - }; +var _resolvePreset2 = _interopRequireDefault(_resolvePreset); - var binding = scope.getOwnBinding(name); +var _cloneDeepWith = require("lodash/cloneDeepWith"); - if (binding) { - if (binding.kind === "param") { - state.selfReference = true; - } else {} - } else if (state.outerDeclar || scope.hasGlobal(name)) { - scope.traverse(node, visitor, state); - } +var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); - return state; -} +var _clone = require("lodash/clone"); -module.exports = exports["default"]; -},{"babel-helper-get-function-arity":74,"babel-template":108,"babel-types":145}],74:[function(require,module,exports){ -"use strict"; +var _clone2 = _interopRequireDefault(_clone); -exports.__esModule = true; +var _merge = require("../../../helpers/merge"); -exports.default = function (node) { - var params = node.params; - for (var i = 0; i < params.length; i++) { - var param = params[i]; - if (t.isAssignmentPattern(param) || t.isRestElement(param)) { - return i; - } - } - return params.length; -}; +var _merge2 = _interopRequireDefault(_merge); -var _babelTypes = require("babel-types"); +var _config2 = require("./config"); -var t = _interopRequireWildcard(_babelTypes); +var _config3 = _interopRequireDefault(_config2); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _removed = require("./removed"); -module.exports = exports["default"]; -},{"babel-types":145}],75:[function(require,module,exports){ -"use strict"; +var _removed2 = _interopRequireDefault(_removed); -exports.__esModule = true; +var _buildConfigChain = require("./build-config-chain"); -exports.default = function (callee, thisNode, args) { - if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { - return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); - } else { - return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode].concat(args)); - } -}; +var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); -var _babelTypes = require("babel-types"); +var _path = require("path"); -var t = _interopRequireWildcard(_babelTypes); +var _path2 = _interopRequireDefault(_path); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -module.exports = exports["default"]; -},{"babel-types":145}],76:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); +var OptionManager = function () { + function OptionManager(log) { + (0, _classCallCheck3.default)(this, OptionManager); -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + this.resolvedConfigs = []; + this.options = OptionManager.createBareOptions(); + this.log = log; + } -var _babelMessages = require("babel-messages"); + OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { + for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -var messages = _interopRequireWildcard(_babelMessages); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } -var _babelTypes = require("babel-types"); + var cache = _ref; -var t = _interopRequireWildcard(_babelTypes); + if (cache.container === fn) return cache.plugin; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var obj = void 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (typeof fn === "function") { + obj = fn(context); + } else { + obj = fn; + } -var HARDCORE_THIS_REF = (0, _symbol2.default)(); + if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") { + var _plugin = new _plugin3.default(obj, alias); + OptionManager.memoisedPlugins.push({ + container: fn, + plugin: _plugin + }); + return _plugin; + } else { + throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); + } + }; -function isIllegalBareSuper(node, parent) { - if (!t.isSuper(node)) return false; - if (t.isMemberExpression(parent, { computed: false })) return false; - if (t.isCallExpression(parent, { callee: node })) return false; - return true; -} + OptionManager.createBareOptions = function createBareOptions() { + var opts = {}; -function isMemberExpressionSuper(node) { - return t.isMemberExpression(node) && t.isSuper(node.object); -} + for (var _key in _config3.default) { + var opt = _config3.default[_key]; + opts[_key] = (0, _clone2.default)(opt.default); + } -function getPrototypeOfExpression(objectRef, isStatic) { - var targetRef = isStatic ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); + return opts; + }; - return t.logicalExpression("||", t.memberExpression(targetRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [targetRef])); -} + OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { + plugin = plugin.__esModule ? plugin.default : plugin; -var visitor = { - Function: function Function(path) { - if (!path.inShadow("this")) { - path.skip(); - } - }, - ReturnStatement: function ReturnStatement(path, state) { - if (!path.inShadow("this")) { - state.returns.push(path); - } - }, - ThisExpression: function ThisExpression(path, state) { - if (!path.node[HARDCORE_THIS_REF]) { - state.thises.push(path); + if (!(plugin instanceof _plugin3.default)) { + if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { + plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); + } else { + throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); + } } - }, - enter: function enter(path, state) { - var callback = state.specHandle; - if (state.isLoose) callback = state.looseHandle; - - var isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); - var result = callback.call(state, path); + plugin.init(loc, i); - if (result) { - state.hasSuper = true; - } + return plugin; + }; - if (isBareSuper) { - state.bareSupers.push(path); - } + OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { + return plugins.map(function (val, i) { + var plugin = void 0, + options = void 0; - if (result === true) { - path.requeue(); - } + if (!val) { + throw new TypeError("Falsy value found in plugins"); + } - if (result !== true && result) { - if (Array.isArray(result)) { - path.replaceWithMultiple(result); + if (Array.isArray(val)) { + plugin = val[0]; + options = val[1]; } else { - path.replaceWith(result); + plugin = val; } - } - } -}; -var ReplaceSupers = function () { - function ReplaceSupers(opts) { - var inClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - (0, _classCallCheck3.default)(this, ReplaceSupers); - - this.forceSuperMemoisation = opts.forceSuperMemoisation; - this.methodPath = opts.methodPath; - this.methodNode = opts.methodNode; - this.superRef = opts.superRef; - this.isStatic = opts.isStatic; - this.hasSuper = false; - this.inClass = inClass; - this.isLoose = opts.isLoose; - this.scope = this.methodPath.scope; - this.file = opts.file; - this.opts = opts; + var alias = typeof plugin === "string" ? plugin : loc + "$" + i; - this.bareSupers = []; - this.returns = []; - this.thises = []; - } + if (typeof plugin === "string") { + var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname); + if (pluginLoc) { + plugin = require(pluginLoc); + } else { + throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname)); + } + } - ReplaceSupers.prototype.getObjectRef = function getObjectRef() { - return this.opts.objectRef || this.opts.getObjectRef(); - }; + plugin = OptionManager.normalisePlugin(plugin, loc, i, alias); - ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed) { - return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), value, t.thisExpression()]); + return [plugin, options]; + }); }; - ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed) { - return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), t.thisExpression()]); - }; + OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) { + var _this = this; - ReplaceSupers.prototype.replace = function replace() { - this.methodPath.traverse(visitor, this); - }; + var rawOpts = _ref2.options, + extendingOpts = _ref2.extending, + alias = _ref2.alias, + loc = _ref2.loc, + dirname = _ref2.dirname; - ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) { - var methodNode = this.methodNode; - var superRef = this.superRef || t.identifier("Function"); + alias = alias || "foreign"; + if (!rawOpts) return; - if (parent.property === id) { - return; - } else if (t.isCallExpression(parent, { callee: id })) { - return; - } else if (t.isMemberExpression(parent) && !methodNode.static) { - return t.memberExpression(superRef, t.identifier("prototype")); - } else { - return superRef; + if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { + this.log.error("Invalid options type for " + alias, TypeError); } - }; - ReplaceSupers.prototype.looseHandle = function looseHandle(path) { - var node = path.node; - if (path.isSuper()) { - return this.getLooseSuperProperty(node, path.parent); - } else if (path.isCallExpression()) { - var callee = node.callee; - if (!t.isMemberExpression(callee)) return; - if (!t.isSuper(callee.object)) return; + var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) { + if (val instanceof _plugin3.default) { + return val; + } + }); - t.appendToMemberExpression(callee, t.identifier("call")); - node.arguments.unshift(t.thisExpression()); - return true; - } - }; + dirname = dirname || process.cwd(); + loc = loc || alias; - ReplaceSupers.prototype.specHandleAssignmentExpression = function specHandleAssignmentExpression(ref, path, node) { - if (node.operator === "=") { - return this.setSuperProperty(node.left.property, node.right, node.left.computed); - } else { - ref = ref || path.scope.generateUidIdentifier("ref"); - return [t.variableDeclaration("var", [t.variableDeclarator(ref, node.left)]), t.expressionStatement(t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right)))]; - } - }; + for (var _key2 in opts) { + var option = _config3.default[_key2]; - ReplaceSupers.prototype.specHandle = function specHandle(path) { - var property = void 0; - var computed = void 0; - var args = void 0; + if (!option && this.log) { + if (_removed2.default[_key2]) { + this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError); + } else { + var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; + var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; - var parent = path.parent; - var node = path.node; - if (isIllegalBareSuper(node, parent)) { - throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); + this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError); + } + } } - if (t.isCallExpression(node)) { - var callee = node.callee; - if (t.isSuper(callee)) { - return; - } else if (isMemberExpressionSuper(callee)) { - property = callee.property; - computed = callee.computed; - args = node.arguments; - } - } else if (t.isMemberExpression(node) && t.isSuper(node.object)) { - property = node.property; - computed = node.computed; - } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { - var binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); - if (node.prefix) { - return this.specHandleAssignmentExpression(null, path, binary); + (0, _index.normaliseOptions)(opts); + + if (opts.plugins) { + opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); + } + + if (opts.presets) { + if (opts.passPerPreset) { + opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) { + _this.mergeOptions({ + options: preset, + extending: preset, + alias: presetLoc, + loc: presetLoc, + dirname: dirname + }); + }); } else { - var ref = path.scope.generateUidIdentifier("ref"); - return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); + this.mergePresets(opts.presets, dirname); + delete opts.presets; } - } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { - return this.specHandleAssignmentExpression(null, path, node); } - if (!property) return; - - var superProperty = this.getSuperProperty(property, computed); - - if (args) { - return this.optimiseCall(superProperty, args); + if (rawOpts === extendingOpts) { + (0, _assign2.default)(extendingOpts, opts); } else { - return superProperty; + (0, _merge2.default)(extendingOpts || this.options, opts); } }; - ReplaceSupers.prototype.optimiseCall = function optimiseCall(callee, args) { - var thisNode = t.thisExpression(); - thisNode[HARDCORE_THIS_REF] = true; - return (0, _babelHelperOptimiseCallExpression2.default)(callee, thisNode, args); + OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { + var _this2 = this; + + this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { + _this2.mergeOptions({ + options: presetOpts, + alias: presetLoc, + loc: presetLoc, + dirname: _path2.default.dirname(presetLoc || "") + }); + }); }; - return ReplaceSupers; -}(); + OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { + return presets.map(function (val) { + var options = void 0; + if (Array.isArray(val)) { + if (val.length > 2) { + throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); + } -exports.default = ReplaceSupers; -module.exports = exports["default"]; -},{"babel-helper-optimise-call-expression":75,"babel-messages":79,"babel-runtime/core-js/symbol":98,"babel-runtime/helpers/classCallCheck":103,"babel-types":145}],77:[function(require,module,exports){ -"use strict"; + var _val = val; + val = _val[0]; + options = _val[1]; + } -exports.__esModule = true; + var presetLoc = void 0; + try { + if (typeof val === "string") { + presetLoc = (0, _resolvePreset2.default)(val, dirname); -var _babelTemplate = require("babel-template"); + if (!presetLoc) { + throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); + } -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + val = require(presetLoc); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) { + if (val.default) { + val = val.default; + } else { + var _val2 = val, + __esModule = _val2.__esModule, + rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]); -var helpers = {}; -exports.default = helpers; + val = rest; + } + } + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; -helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); + if (typeof val !== "function" && options !== undefined) { + throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); + } -helpers.jsx = (0, _babelTemplate2.default)("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n"); + if (typeof val === "function") val = val(context, options, { dirname: dirname }); -helpers.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { + throw new Error("Unsupported preset format: " + val + "."); + } -helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); + onResolve && onResolve(val, presetLoc); + } catch (e) { + if (presetLoc) { + e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; + } + throw e; + } + return val; + }); + }; -helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); + OptionManager.prototype.normaliseOptions = function normaliseOptions() { + var opts = this.options; -helpers.asyncToGenerator = (0, _babelTemplate2.default)("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); + for (var _key3 in _config3.default) { + var option = _config3.default[_key3]; + var val = opts[_key3]; -helpers.classCallCheck = (0, _babelTemplate2.default)("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n"); + if (!val && option.optional) continue; -helpers.createClass = (0, _babelTemplate2.default)("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n"); + if (option.alias) { + opts[option.alias] = opts[option.alias] || val; + } else { + opts[_key3] = val; + } + } + }; -helpers.defineEnumerableProperties = (0, _babelTemplate2.default)("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n"); + OptionManager.prototype.init = function init() { + var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; -helpers.defaults = (0, _babelTemplate2.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"); + for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; -helpers.defineProperty = (0, _babelTemplate2.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"); + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } -helpers.extends = (0, _babelTemplate2.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"); + var _config = _ref3; -helpers.get = (0, _babelTemplate2.default)("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n"); + this.mergeOptions(_config); + } -helpers.inherits = (0, _babelTemplate2.default)("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n"); + this.normaliseOptions(opts); -helpers.instanceof = (0, _babelTemplate2.default)("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n"); + return this.options; + }; -helpers.interopRequireDefault = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); + return OptionManager; +}(); -helpers.interopRequireWildcard = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"); +exports.default = OptionManager; -helpers.newArrowCheck = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); -helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); +OptionManager.memoisedPlugins = []; +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"../../../api/node":63,"../../../helpers/merge":66,"../../../helpers/resolve-plugin":69,"../../../helpers/resolve-preset":70,"../../plugin":87,"./build-config-chain":77,"./config":78,"./index":79,"./removed":82,"_process":15,"babel-messages":115,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/json/stringify":128,"babel-runtime/core-js/object/assign":131,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/objectWithoutProperties":143,"babel-runtime/helpers/typeof":145,"lodash/clone":493,"lodash/cloneDeepWith":495,"path":13}],81:[function(require,module,exports){ +"use strict"; -helpers.objectWithoutProperties = (0, _babelTemplate2.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"); +exports.__esModule = true; +exports.filename = undefined; +exports.boolean = boolean; +exports.booleanString = booleanString; +exports.list = list; -helpers.possibleConstructorReturn = (0, _babelTemplate2.default)("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n"); +var _slash = require("slash"); -helpers.selfGlobal = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); +var _slash2 = _interopRequireDefault(_slash); -helpers.set = (0, _babelTemplate2.default)("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n"); +var _util = require("../../../util"); -helpers.slicedToArray = (0, _babelTemplate2.default)("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n"); +var util = _interopRequireWildcard(_util); -helpers.slicedToArrayLoose = (0, _babelTemplate2.default)("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n"); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -helpers.taggedTemplateLiteral = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); +var filename = exports.filename = _slash2.default; -helpers.temporalRef = (0, _babelTemplate2.default)("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n"); +function boolean(val) { + return !!val; +} -helpers.temporalUndefined = (0, _babelTemplate2.default)("\n ({})\n"); +function booleanString(val) { + return util.booleanify(val); +} -helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); +function list(val) { + return util.list(val); +} +},{"../../../util":88,"slash":561}],82:[function(require,module,exports){ +"use strict"; -helpers.toConsumableArray = (0, _babelTemplate2.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"); -module.exports = exports["default"]; -},{"babel-template":108}],78:[function(require,module,exports){ +module.exports = { + "auxiliaryComment": { + "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" + }, + "blacklist": { + "message": "Put the specific transforms you want in the `plugins` option" + }, + "breakConfig": { + "message": "This is not a necessary option in Babel 6" + }, + "experimental": { + "message": "Put the specific transforms you want in the `plugins` option" + }, + "externalHelpers": { + "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" + }, + "extra": { + "message": "" + }, + "jsxPragma": { + "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" + }, + + "loose": { + "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." + }, + "metadataUsedHelpers": { + "message": "Not required anymore as this is enabled by default" + }, + "modules": { + "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules" + }, + "nonStandard": { + "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" + }, + "optional": { + "message": "Put the specific transforms you want in the `plugins` option" + }, + "sourceMapName": { + "message": "Use the `sourceMapTarget` option" + }, + "stage": { + "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" + }, + "whitelist": { + "message": "Put the specific transforms you want in the `plugins` option" + } +}; +},{}],83:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.list = undefined; - -var _keys = require("babel-runtime/core-js/object/keys"); -var _keys2 = _interopRequireDefault(_keys); +var _plugin = require("../plugin"); -exports.get = get; +var _plugin2 = _interopRequireDefault(_plugin); -var _helpers = require("./helpers"); +var _sortBy = require("lodash/sortBy"); -var _helpers2 = _interopRequireDefault(_helpers); +var _sortBy2 = _interopRequireDefault(_sortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function get(name) { - var fn = _helpers2.default[name]; - if (!fn) throw new ReferenceError("Unknown helper " + name); +exports.default = new _plugin2.default({ - return fn().expression; -} + name: "internal.blockHoist", -var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { - return name.replace(/^_/, ""); -}).filter(function (name) { - return name !== "__esModule"; -}); + visitor: { + Block: { + exit: function exit(_ref) { + var node = _ref.node; -exports.default = get; -},{"./helpers":77,"babel-runtime/core-js/object/keys":96}],79:[function(require,module,exports){ + var hasChange = false; + for (var i = 0; i < node.body.length; i++) { + var bodyNode = node.body[i]; + if (bodyNode && bodyNode._blockHoist != null) { + hasChange = true; + break; + } + } + if (!hasChange) return; + + node.body = (0, _sortBy2.default)(node.body, function (bodyNode) { + var priority = bodyNode && bodyNode._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; + + return -1 * priority; + }); + } + } + } +}); +module.exports = exports["default"]; +},{"../plugin":87,"lodash/sortBy":533}],84:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.MESSAGES = undefined; -var _stringify = require("babel-runtime/core-js/json/stringify"); +var _symbol = require("babel-runtime/core-js/symbol"); -var _stringify2 = _interopRequireDefault(_stringify); +var _symbol2 = _interopRequireDefault(_symbol); -exports.get = get; -exports.parseArgs = parseArgs; +var _plugin = require("../plugin"); -var _util = require("util"); +var _plugin2 = _interopRequireDefault(_plugin); -var util = _interopRequireWildcard(_util); +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var MESSAGES = exports.MESSAGES = { - tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", - classesIllegalBareSuper: "Illegal use of bare super", - classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", - scopeDuplicateDeclaration: "Duplicate declaration $1", - settersNoRest: "Setters aren't allowed to have a rest", - noAssignmentsInForHead: "No assignments allowed in for-in/of head", - expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", - invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", - readOnly: "$1 is read-only", - unknownForHead: "Unknown node type $1 in ForStatement", - didYouMean: "Did you mean $1?", - codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", - missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", - unsupportedOutputType: "Unsupported output type $1", - illegalMethodName: "Illegal method name $1", - lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", +var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); - modulesIllegalExportName: "Illegal export $1", - modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", +var superVisitor = { + CallExpression: function CallExpression(path) { + if (!path.get("callee").isSuper()) return; - undeclaredVariable: "Reference to undeclared variable $1", - undeclaredVariableType: "Referencing a type alias outside of a type annotation", - undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", + var node = path.node; - traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.", - traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", - traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", - traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", + if (node[SUPER_THIS_BOUND]) return; + node[SUPER_THIS_BOUND] = true; - pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", - pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", - pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", - pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" + path.replaceWith(t.assignmentExpression("=", this.id, node)); + } }; -function get(key) { - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } +exports.default = new _plugin2.default({ + name: "internal.shadowFunctions", - var msg = MESSAGES[key]; - if (!msg) throw new ReferenceError("Unknown message " + (0, _stringify2.default)(key)); + visitor: { + ThisExpression: function ThisExpression(path) { + remap(path, "this"); + }, + ReferencedIdentifier: function ReferencedIdentifier(path) { + if (path.node.name === "arguments") { + remap(path, "arguments"); + } + } + } +}); - args = parseArgs(args); - return msg.replace(/\$(\d+)/g, function (str, i) { - return args[i - 1]; - }); +function shouldShadow(path, shadowPath) { + if (path.is("_forceShadow")) { + return true; + } else { + return shadowPath; + } } -function parseArgs(args) { - return args.map(function (val) { - if (val != null && val.inspect) { - return val.inspect(); - } else { - try { - return (0, _stringify2.default)(val) || val + ""; - } catch (e) { - return util.inspect(val); - } - } - }); -} -},{"babel-runtime/core-js/json/stringify":90,"util":821}],80:[function(require,module,exports){ -"use strict"; +function remap(path, key) { + var shadowPath = path.inShadow(key); + if (!shouldShadow(path, shadowPath)) return; -exports.__esModule = true; + var shadowFunction = path.node._shadowedFunctionLiteral; -exports.default = function () { - return { - manipulateOptions: function manipulateOptions(opts, parserOpts) { - parserOpts.plugins.push("asyncFunctions"); + var currentFunction = void 0; + var passedShadowFunction = false; + + var fnPath = path.find(function (innerPath) { + if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { + return true; + } + if (path === innerPath) return false; + if (innerPath.isProgram() || innerPath.isFunction()) { + currentFunction = currentFunction || innerPath; } - }; -}; -module.exports = exports["default"]; -},{}],81:[function(require,module,exports){ -"use strict"; + if (innerPath.isProgram()) { + passedShadowFunction = true; -exports.__esModule = true; + return true; + } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { + if (shadowFunction) { + if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; + } else { + if (!innerPath.is("shadow")) return true; + } -exports.default = function () { - return { - manipulateOptions: function manipulateOptions(opts, parserOpts) { - parserOpts.plugins.push("asyncGenerators"); + passedShadowFunction = true; + return false; } - }; -}; -module.exports = exports["default"]; -},{}],82:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; + return false; + }); -exports.default = function (_ref) { - var t = _ref.types; + if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { + fnPath = path.findParent(function (p) { + return p.isProgram() || p.isFunction(); + }); + } - return { - visitor: { - ArrowFunctionExpression: function ArrowFunctionExpression(path, state) { - if (state.opts.spec) { - var node = path.node; + if (fnPath === currentFunction) return; - if (node.shadow) return; + if (!passedShadowFunction) return; - node.shadow = { this: false }; - node.type = "FunctionExpression"; + var cached = fnPath.getData(key); + if (cached) return path.replaceWith(cached); - var boundThis = t.thisExpression(); - boundThis._forceShadow = path; + var id = path.scope.generateUidIdentifier(key); - path.ensureBlock(); - path.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [t.thisExpression(), boundThis]))); + fnPath.setData(key, id); - path.replaceWith(t.callExpression(t.memberExpression(node, t.identifier("bind")), [t.thisExpression()])); - } else { - path.arrowFunctionToShadowed(); - } - } - } - }; -}; + var classPath = fnPath.findParent(function (p) { + return p.isClass(); + }); + var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); -module.exports = exports["default"]; -},{}],83:[function(require,module,exports){ -"use strict"; + if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { + fnPath.scope.push({ id: id }); -exports.__esModule = true; + fnPath.traverse(superVisitor, { id: id }); + } else { + var init = key === "this" ? t.thisExpression() : t.identifier(key); -var _symbol = require("babel-runtime/core-js/symbol"); + if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction; -var _symbol2 = _interopRequireDefault(_symbol); + fnPath.scope.push({ id: id, init: init }); + } -var _create = require("babel-runtime/core-js/object/create"); + return path.replaceWith(id); +} +module.exports = exports["default"]; +},{"../plugin":87,"babel-runtime/core-js/symbol":136,"babel-types":183}],85:[function(require,module,exports){ +"use strict"; -var _create2 = _interopRequireDefault(_create); +exports.__esModule = true; var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -exports.default = function () { - return { - visitor: { - VariableDeclaration: function VariableDeclaration(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; +var _normalizeAst = require("../helpers/normalize-ast"); - if (!isBlockScoped(node)) return; - convertBlockScopedToVar(path, null, parent, scope, true); +var _normalizeAst2 = _interopRequireDefault(_normalizeAst); - if (node._tdzThis) { - var nodes = [node]; +var _plugin = require("./plugin"); - for (var i = 0; i < node.declarations.length; i++) { - var decl = node.declarations[i]; - if (decl.init) { - var assign = t.assignmentExpression("=", decl.id, decl.init); - assign._ignoreBlockScopingTDZ = true; - nodes.push(t.expressionStatement(assign)); - } - decl.init = file.addHelper("temporalUndefined"); - } +var _plugin2 = _interopRequireDefault(_plugin); - node._blockHoist = 2; +var _file = require("./file"); - if (path.isCompletionRecord()) { - nodes.push(t.expressionStatement(scope.buildUndefinedNode())); - } +var _file2 = _interopRequireDefault(_file); - path.replaceWithMultiple(nodes); - } - }, - Loop: function Loop(path, file) { - var node = path.node, - parent = path.parent, - scope = path.scope; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - t.ensureBlock(node); - var blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); - var replace = blockScoping.run(); - if (replace) path.replaceWith(replace); - }, - CatchClause: function CatchClause(path, file) { - var parent = path.parent, - scope = path.scope; +var Pipeline = function () { + function Pipeline() { + (0, _classCallCheck3.default)(this, Pipeline); + } - var blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); - blockScoping.run(); - }, - "BlockStatement|SwitchStatement|Program": function BlockStatementSwitchStatementProgram(path, file) { - if (!ignoreBlock(path)) { - var blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); - blockScoping.run(); - } - } - } + Pipeline.prototype.lint = function lint(code) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + opts.code = false; + opts.mode = "lint"; + return this.transform(code, opts); }; -}; -var _babelTraverse = require("babel-traverse"); + Pipeline.prototype.pretransform = function pretransform(code, opts) { + var file = new _file2.default(opts, this); + return file.wrap(code, function () { + file.addCode(code); + file.parseCode(code); + return file; + }); + }; -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + Pipeline.prototype.transform = function transform(code, opts) { + var file = new _file2.default(opts, this); + return file.wrap(code, function () { + file.addCode(code); + file.parseCode(code); + return file.transform(); + }); + }; -var _tdz = require("./tdz"); + Pipeline.prototype.analyse = function analyse(code) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var visitor = arguments[2]; -var _babelTypes = require("babel-types"); + opts.code = false; + if (visitor) { + opts.plugins = opts.plugins || []; + opts.plugins.push(new _plugin2.default({ visitor: visitor })); + } + return this.transform(code, opts).metadata; + }; -var t = _interopRequireWildcard(_babelTypes); + Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) { + ast = (0, _normalizeAst2.default)(ast); -var _values = require("lodash/values"); + var file = new _file2.default(opts, this); + return file.wrap(code, function () { + file.addCode(code); + file.addAst(ast); + return file.transform(); + }); + }; -var _values2 = _interopRequireDefault(_values); + return Pipeline; +}(); -var _extend = require("lodash/extend"); +exports.default = Pipeline; +module.exports = exports["default"]; +},{"../helpers/normalize-ast":67,"./file":74,"./plugin":87,"babel-runtime/helpers/classCallCheck":141}],86:[function(require,module,exports){ +"use strict"; -var _extend2 = _interopRequireDefault(_extend); +exports.__esModule = true; -var _babelTemplate = require("babel-template"); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); -function ignoreBlock(path) { - return t.isLoop(path.parent) || t.isCatchClause(path.parent); -} +var _inherits2 = require("babel-runtime/helpers/inherits"); -var buildRetCheck = (0, _babelTemplate2.default)("\n if (typeof RETURN === \"object\") return RETURN.v;\n"); +var _inherits3 = _interopRequireDefault(_inherits2); -function isBlockScoped(node) { - if (!t.isVariableDeclaration(node)) return false; - if (node[t.BLOCK_SCOPED_SYMBOL]) return true; - if (node.kind !== "let" && node.kind !== "const") return false; - return true; -} +var _store = require("../store"); -function convertBlockScopedToVar(path, node, parent, scope) { - var moveBindingsToParent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; +var _store2 = _interopRequireDefault(_store); - if (!node) { - node = path.node; - } +var _file5 = require("./file"); - if (!t.isFor(parent)) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - declar.init = declar.init || scope.buildUndefinedNode(); - } - } +var _file6 = _interopRequireDefault(_file5); - node[t.BLOCK_SCOPED_SYMBOL] = true; - node.kind = "var"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (moveBindingsToParent) { - var parentScope = scope.getFunctionParent(); - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = scope.getOwnBinding(name); - if (binding) binding.kind = "var"; - scope.moveBindingTo(name, parentScope); - } - } -} +var PluginPass = function (_Store) { + (0, _inherits3.default)(PluginPass, _Store); -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); -} + function PluginPass(file, plugin) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + (0, _classCallCheck3.default)(this, PluginPass); -var letReferenceBlockVisitor = _babelTraverse2.default.visitors.merge([{ - Loop: { - enter: function enter(path, state) { - state.loopDepth++; - }, - exit: function exit(path, state) { - state.loopDepth--; - } - }, - Function: function Function(path, state) { - if (state.loopDepth > 0) { - path.traverse(letReferenceFunctionVisitor, state); - } - return path.skip(); + var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + + _this.plugin = plugin; + _this.key = plugin.key; + _this.file = file; + _this.opts = options; + return _this; } -}, _tdz.visitor]); -var letReferenceFunctionVisitor = _babelTraverse2.default.visitors.merge([{ - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - var ref = state.letReferences[path.node.name]; + PluginPass.prototype.addHelper = function addHelper() { + var _file; - if (!ref) return; + return (_file = this.file).addHelper.apply(_file, arguments); + }; - var localBinding = path.scope.getBindingIdentifier(path.node.name); - if (localBinding && localBinding !== ref) return; + PluginPass.prototype.addImport = function addImport() { + var _file2; - state.closurify = true; - } -}, _tdz.visitor]); + return (_file2 = this.file).addImport.apply(_file2, arguments); + }; -var hoistVarDeclarationsVisitor = { - enter: function enter(path, self) { - var node = path.node, - parent = path.parent; + PluginPass.prototype.getModuleName = function getModuleName() { + var _file3; + return (_file3 = this.file).getModuleName.apply(_file3, arguments); + }; - if (path.isForStatement()) { - if (isVar(node.init, node)) { - var nodes = self.pushDeclar(node.init); - if (nodes.length === 1) { - node.init = nodes[0]; - } else { - node.init = t.sequenceExpression(nodes); - } - } - } else if (path.isFor()) { - if (isVar(node.left, node)) { - self.pushDeclar(node.left); - node.left = node.left.declarations[0].id; - } - } else if (isVar(node, parent)) { - path.replaceWithMultiple(self.pushDeclar(node).map(function (expr) { - return t.expressionStatement(expr); - })); - } else if (path.isFunction()) { - return path.skip(); - } - } -}; + PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { + var _file4; -var loopLabelVisitor = { - LabeledStatement: function LabeledStatement(_ref, state) { - var node = _ref.node; + return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); + }; - state.innerLabels.push(node.label.name); - } -}; + return PluginPass; +}(_store2.default); -var continuationVisitor = { - enter: function enter(path, state) { - if (path.isAssignmentExpression() || path.isUpdateExpression()) { - var bindings = path.getBindingIdentifiers(); - for (var name in bindings) { - if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; - state.reassignments[name] = true; - } - } - } -}; +exports.default = PluginPass; +module.exports = exports["default"]; +},{"../store":72,"./file":74,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144}],87:[function(require,module,exports){ +"use strict"; -function loopNodeTo(node) { - if (t.isBreakStatement(node)) { - return "break"; - } else if (t.isContinueStatement(node)) { - return "continue"; - } -} +exports.__esModule = true; -var loopVisitor = { - Loop: function Loop(path, state) { - var oldIgnoreLabeless = state.ignoreLabeless; - state.ignoreLabeless = true; - path.traverse(loopVisitor, state); - state.ignoreLabeless = oldIgnoreLabeless; - path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - SwitchCase: function SwitchCase(path, state) { - var oldInSwitchCase = state.inSwitchCase; - state.inSwitchCase = true; - path.traverse(loopVisitor, state); - state.inSwitchCase = oldInSwitchCase; - path.skip(); - }, - "BreakStatement|ContinueStatement|ReturnStatement": function BreakStatementContinueStatementReturnStatement(path, state) { - var node = path.node, - parent = path.parent, - scope = path.scope; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - if (node[this.LOOP_IGNORE]) return; +var _getIterator3 = _interopRequireDefault(_getIterator2); - var replace = void 0; - var loopText = loopNodeTo(node); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - if (loopText) { - if (node.label) { - if (state.innerLabels.indexOf(node.label.name) >= 0) { - return; - } +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - loopText = loopText + "|" + node.label.name; - } else { - if (state.ignoreLabeless) return; +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - if (state.inSwitchCase) return; +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; - } +var _inherits2 = require("babel-runtime/helpers/inherits"); - state.hasBreakContinue = true; - state.map[loopText] = node; - replace = t.stringLiteral(loopText); - } +var _inherits3 = _interopRequireDefault(_inherits2); - if (path.isReturnStatement()) { - state.hasReturn = true; - replace = t.objectExpression([t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode())]); - } +var _optionManager = require("./file/options/option-manager"); - if (replace) { - replace = t.returnStatement(replace); - replace[this.LOOP_IGNORE] = true; - path.skip(); - path.replaceWith(t.inherits(replace, node)); - } - } -}; +var _optionManager2 = _interopRequireDefault(_optionManager); -var BlockScoping = function () { - function BlockScoping(loopPath, blockPath, parent, scope, file) { - (0, _classCallCheck3.default)(this, BlockScoping); +var _babelMessages = require("babel-messages"); - this.parent = parent; - this.scope = scope; - this.file = file; +var messages = _interopRequireWildcard(_babelMessages); - this.blockPath = blockPath; - this.block = blockPath.node; +var _store = require("../store"); - this.outsideLetReferences = (0, _create2.default)(null); - this.hasLetReferences = false; - this.letReferences = (0, _create2.default)(null); - this.body = []; +var _store2 = _interopRequireDefault(_store); - if (loopPath) { - this.loopParent = loopPath.parent; - this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; - this.loopPath = loopPath; - this.loop = loopPath.node; - } - } +var _babelTraverse = require("babel-traverse"); - BlockScoping.prototype.run = function run() { - var block = this.block; - if (block._letDone) return; - block._letDone = true; +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - var needsClosure = this.getLetReferences(); +var _assign = require("lodash/assign"); - if (t.isFunction(this.parent) || t.isProgram(this.block)) { - this.updateScopeInfo(); - return; - } +var _assign2 = _interopRequireDefault(_assign); - if (!this.hasLetReferences) return; +var _clone = require("lodash/clone"); - if (needsClosure) { - this.wrapClosure(); - } else { - this.remap(); - } +var _clone2 = _interopRequireDefault(_clone); - this.updateScopeInfo(needsClosure); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { - return t.labeledStatement(this.loopLabel, this.loop); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; + +var Plugin = function (_Store) { + (0, _inherits3.default)(Plugin, _Store); + + function Plugin(plugin, key) { + (0, _classCallCheck3.default)(this, Plugin); + + var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + + _this.initialized = false; + _this.raw = (0, _assign2.default)({}, plugin); + _this.key = _this.take("name") || key; + + _this.manipulateOptions = _this.take("manipulateOptions"); + _this.post = _this.take("post"); + _this.pre = _this.take("pre"); + _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); + return _this; + } + + Plugin.prototype.take = function take(key) { + var val = this.raw[key]; + delete this.raw[key]; + return val; }; - BlockScoping.prototype.updateScopeInfo = function updateScopeInfo(wrappedInClosure) { - var scope = this.scope; - var parentScope = scope.getFunctionParent(); - var letRefs = this.letReferences; + Plugin.prototype.chain = function chain(target, key) { + if (!target[key]) return this[key]; + if (!this[key]) return target[key]; - for (var key in letRefs) { - var ref = letRefs[key]; - var binding = scope.getBinding(ref.name); - if (!binding) continue; - if (binding.kind === "let" || binding.kind === "const") { - binding.kind = "var"; + var fns = [target[key], this[key]]; - if (wrappedInClosure) { - scope.removeBinding(ref.name); + return function () { + var val = void 0; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; } else { - scope.moveBindingTo(ref.name, parentScope); + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var fn = _ref; + + if (fn) { + var ret = fn.apply(this, args); + if (ret != null) val = ret; } } - } + return val; + }; }; - BlockScoping.prototype.remap = function remap() { - var letRefs = this.letReferences; - var scope = this.scope; - - for (var key in letRefs) { - var ref = letRefs[key]; + Plugin.prototype.maybeInherit = function maybeInherit(loc) { + var inherits = this.take("inherits"); + if (!inherits) return; - if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { - if (scope.hasOwnBinding(key)) scope.rename(ref.name); + inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits"); - if (this.blockPath.scope.hasOwnBinding(key)) this.blockPath.scope.rename(ref.name); - } - } + this.manipulateOptions = this.chain(inherits, "manipulateOptions"); + this.post = this.chain(inherits, "post"); + this.pre = this.chain(inherits, "pre"); + this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]); }; - BlockScoping.prototype.wrapClosure = function wrapClosure() { - if (this.file.opts.throwIfClosureRequired) { - throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired)."); - } - var block = this.block; + Plugin.prototype.init = function init(loc, i) { + if (this.initialized) return; + this.initialized = true; - var outsideRefs = this.outsideLetReferences; + this.maybeInherit(loc); - if (this.loop) { - for (var name in outsideRefs) { - var id = outsideRefs[name]; + for (var key in this.raw) { + throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); + } + }; - if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { - delete outsideRefs[id.name]; - delete this.letReferences[id.name]; + Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) { + for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - this.scope.rename(id.name); + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } - this.letReferences[id.name] = id; - outsideRefs[id.name] = id; - } + var key = _ref2; + + if (visitor[key]) { + throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes."); } } - this.has = this.checkLoop(); + _babelTraverse2.default.explode(visitor); + return visitor; + }; - this.hoistVarDeclarations(); + return Plugin; +}(_store2.default); - var params = (0, _values2.default)(outsideRefs); - var args = (0, _values2.default)(outsideRefs); +exports.default = Plugin; +module.exports = exports["default"]; +},{"../store":72,"./file/options/option-manager":80,"babel-messages":115,"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144,"babel-traverse":150,"lodash/assign":490,"lodash/clone":493}],88:[function(require,module,exports){ +"use strict"; - var isSwitch = this.blockPath.isSwitchStatement(); +exports.__esModule = true; +exports.inspect = exports.inherits = undefined; - var fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); - fn.shadow = true; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - this.addContinuations(fn); +var _getIterator3 = _interopRequireDefault(_getIterator2); - var ref = fn; +var _util = require("util"); - if (this.loop) { - ref = this.scope.generateUidIdentifier("loop"); - this.loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(ref, fn)])); - } +Object.defineProperty(exports, "inherits", { + enumerable: true, + get: function get() { + return _util.inherits; + } +}); +Object.defineProperty(exports, "inspect", { + enumerable: true, + get: function get() { + return _util.inspect; + } +}); +exports.canCompile = canCompile; +exports.list = list; +exports.regexify = regexify; +exports.arrayify = arrayify; +exports.booleanify = booleanify; +exports.shouldIgnore = shouldIgnore; - var call = t.callExpression(ref, args); - var ret = this.scope.generateUidIdentifier("ret"); +var _escapeRegExp = require("lodash/escapeRegExp"); - var hasYield = _babelTraverse2.default.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); - if (hasYield) { - fn.generator = true; - call = t.yieldExpression(call, true); - } +var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); - var hasAsync = _babelTraverse2.default.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); - if (hasAsync) { - fn.async = true; - call = t.awaitExpression(call); - } +var _startsWith = require("lodash/startsWith"); - this.buildClosure(ret, call); +var _startsWith2 = _interopRequireDefault(_startsWith); - if (isSwitch) this.blockPath.replaceWithMultiple(this.body);else block.body = this.body; - }; +var _minimatch = require("minimatch"); - BlockScoping.prototype.buildClosure = function buildClosure(ret, call) { - var has = this.has; - if (has.hasReturn || has.hasBreakContinue) { - this.buildHas(ret, call); - } else { - this.body.push(t.expressionStatement(call)); - } - }; +var _minimatch2 = _interopRequireDefault(_minimatch); - BlockScoping.prototype.addContinuations = function addContinuations(fn) { - var state = { - reassignments: {}, - outsideReferences: this.outsideLetReferences - }; +var _includes = require("lodash/includes"); - this.scope.traverse(fn, continuationVisitor, state); +var _includes2 = _interopRequireDefault(_includes); - for (var i = 0; i < fn.params.length; i++) { - var param = fn.params[i]; - if (!state.reassignments[param.name]) continue; +var _isRegExp = require("lodash/isRegExp"); - var newParam = this.scope.generateUidIdentifier(param.name); - fn.params[i] = newParam; +var _isRegExp2 = _interopRequireDefault(_isRegExp); - this.scope.rename(param.name, newParam.name, fn); +var _path = require("path"); - fn.body.body.push(t.expressionStatement(t.assignmentExpression("=", param, newParam))); - } - }; +var _path2 = _interopRequireDefault(_path); - BlockScoping.prototype.getLetReferences = function getLetReferences() { - var _this = this; +var _slash = require("slash"); - var block = this.block; +var _slash2 = _interopRequireDefault(_slash); - var declarators = []; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (this.loop) { - var init = this.loop.left || this.loop.init; - if (isBlockScoped(init)) { - declarators.push(init); - (0, _extend2.default)(this.outsideLetReferences, t.getBindingIdentifiers(init)); - } - } - - var addDeclarationsFromChild = function addDeclarationsFromChild(path, node) { - node = node || path.node; - if (t.isClassDeclaration(node) || t.isFunctionDeclaration(node) || isBlockScoped(node)) { - if (isBlockScoped(node)) { - convertBlockScopedToVar(path, node, block, _this.scope); - } - declarators = declarators.concat(node.declarations || node); - } - if (t.isLabeledStatement(node)) { - addDeclarationsFromChild(path.get("body"), node.body); - } - }; - - if (block.body) { - for (var i = 0; i < block.body.length; i++) { - var declarPath = this.blockPath.get("body")[i]; - addDeclarationsFromChild(declarPath); - } - } - - if (block.cases) { - for (var _i = 0; _i < block.cases.length; _i++) { - var consequents = block.cases[_i].consequent; - - for (var j = 0; j < consequents.length; j++) { - var _declarPath = this.blockPath.get("cases")[_i]; - var declar = consequents[j]; - addDeclarationsFromChild(_declarPath, declar); - } - } - } +function canCompile(filename, altExts) { + var exts = altExts || canCompile.EXTENSIONS; + var ext = _path2.default.extname(filename); + return (0, _includes2.default)(exts, ext); +} - for (var _i2 = 0; _i2 < declarators.length; _i2++) { - var _declar = declarators[_i2]; +canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; - var keys = t.getBindingIdentifiers(_declar, false, true); - (0, _extend2.default)(this.letReferences, keys); - this.hasLetReferences = true; - } +function list(val) { + if (!val) { + return []; + } else if (Array.isArray(val)) { + return val; + } else if (typeof val === "string") { + return val.split(","); + } else { + return [val]; + } +} - if (!this.hasLetReferences) return; +function regexify(val) { + if (!val) { + return new RegExp(/.^/); + } - var state = { - letReferences: this.letReferences, - closurify: false, - file: this.file, - loopDepth: 0 - }; + if (Array.isArray(val)) { + val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); + } - var loopOrFunctionParent = this.blockPath.find(function (path) { - return path.isLoop() || path.isFunction(); - }); - if (loopOrFunctionParent && loopOrFunctionParent.isLoop()) { - state.loopDepth++; - } + if (typeof val === "string") { + val = (0, _slash2.default)(val); - this.blockPath.traverse(letReferenceBlockVisitor, state); + if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); + if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); - return state.closurify; - }; + var regex = _minimatch2.default.makeRe(val, { nocase: true }); + return new RegExp(regex.source.slice(1, -1), "i"); + } - BlockScoping.prototype.checkLoop = function checkLoop() { - var state = { - hasBreakContinue: false, - ignoreLabeless: false, - inSwitchCase: false, - innerLabels: [], - hasReturn: false, - isLoop: !!this.loop, - map: {}, - LOOP_IGNORE: (0, _symbol2.default)() - }; + if ((0, _isRegExp2.default)(val)) { + return val; + } - this.blockPath.traverse(loopLabelVisitor, state); - this.blockPath.traverse(loopVisitor, state); + throw new TypeError("illegal type for regexify"); +} - return state; - }; +function arrayify(val, mapFn) { + if (!val) return []; + if (typeof val === "boolean") return arrayify([val], mapFn); + if (typeof val === "string") return arrayify(list(val), mapFn); - BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { - this.blockPath.traverse(hoistVarDeclarationsVisitor, this); - }; + if (Array.isArray(val)) { + if (mapFn) val = val.map(mapFn); + return val; + } - BlockScoping.prototype.pushDeclar = function pushDeclar(node) { - var declars = []; - var names = t.getBindingIdentifiers(node); - for (var name in names) { - declars.push(t.variableDeclarator(names[name])); - } + return [val]; +} - this.body.push(t.variableDeclaration(node.kind, declars)); +function booleanify(val) { + if (val === "true" || val == 1) { + return true; + } - var replace = []; + if (val === "false" || val == 0 || !val) { + return false; + } - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - if (!declar.init) continue; + return val; +} - var expr = t.assignmentExpression("=", declar.id, declar.init); - replace.push(t.inherits(expr, declar)); - } +function shouldIgnore(filename) { + var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var only = arguments[2]; - return replace; - }; + filename = filename.replace(/\\/g, "/"); - BlockScoping.prototype.buildHas = function buildHas(ret, call) { - var body = this.body; + if (only) { + for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - var retCheck = void 0; - var has = this.has; - var cases = []; + var pattern = _ref; - if (has.hasReturn) { - retCheck = buildRetCheck({ - RETURN: ret - }); + if (_shouldIgnore(pattern, filename)) return false; } + return true; + } else if (ignore.length) { + for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - if (has.hasBreakContinue) { - for (var key in has.map) { - cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); - } - - if (has.hasReturn) { - cases.push(t.switchCase(null, [retCheck])); + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } - if (cases.length === 1) { - var single = cases[0]; - body.push(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0])); - } else { - if (this.loop) { - for (var i = 0; i < cases.length; i++) { - var caseConsequent = cases[i].consequent[0]; - if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { - caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); - } - } - } + var _pattern = _ref2; - body.push(t.switchStatement(ret, cases)); - } - } else { - if (has.hasReturn) { - body.push(retCheck); - } + if (_shouldIgnore(_pattern, filename)) return true; } - }; + } - return BlockScoping; -}(); + return false; +} -module.exports = exports["default"]; -},{"./tdz":84,"babel-runtime/core-js/object/create":94,"babel-runtime/core-js/symbol":98,"babel-runtime/helpers/classCallCheck":103,"babel-template":108,"babel-traverse":112,"babel-types":145,"lodash/extend":462,"lodash/values":505}],84:[function(require,module,exports){ +function _shouldIgnore(pattern, filename) { + if (typeof pattern === "function") { + return pattern(filename); + } else { + return pattern.test(filename); + } +} +},{"babel-runtime/core-js/get-iterator":127,"lodash/escapeRegExp":499,"lodash/includes":509,"lodash/isRegExp":521,"lodash/startsWith":534,"minimatch":544,"path":13,"slash":561,"util":36}],89:[function(require,module,exports){ +module.exports={ + "_from": "babel-core@^6.18.2", + "_id": "babel-core@6.25.0", + "_inBundle": false, + "_integrity": "sha1-fdQrBGPHQunVKW3rPsZ6kyLa1yk=", + "_location": "/babel-core", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "babel-core@^6.18.2", + "name": "babel-core", + "escapedName": "babel-core", + "rawSpec": "^6.18.2", + "saveSpec": null, + "fetchSpec": "^6.18.2" + }, + "_requiredBy": [ + "/", + "/babel-cli", + "/babel-register", + "/rollup-plugin-babel" + ], + "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.25.0.tgz", + "_shasum": "7dd42b0463c742e9d5296deb3ec67a9322dad729", + "_spec": "babel-core@^6.18.2", + "_where": "/Users/mateuszburzynski/Desktop/regenerator", + "author": { + "name": "Sebastian McKenzie", + "email": "sebmck@gmail.com" + }, + "bundleDependencies": false, + "dependencies": { + "babel-code-frame": "^6.22.0", + "babel-generator": "^6.25.0", + "babel-helpers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-register": "^6.24.1", + "babel-runtime": "^6.22.0", + "babel-template": "^6.25.0", + "babel-traverse": "^6.25.0", + "babel-types": "^6.25.0", + "babylon": "^6.17.2", + "convert-source-map": "^1.1.0", + "debug": "^2.1.1", + "json5": "^0.5.0", + "lodash": "^4.2.0", + "minimatch": "^3.0.2", + "path-is-absolute": "^1.0.0", + "private": "^0.1.6", + "slash": "^1.0.0", + "source-map": "^0.5.0" + }, + "deprecated": false, + "description": "Babel compiler core.", + "devDependencies": { + "babel-helper-fixtures": "^6.22.0", + "babel-helper-transform-fixture-test-runner": "^6.24.1", + "babel-polyfill": "^6.23.0" + }, + "homepage": "https://babeljs.io/", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ], + "license": "MIT", + "name": "babel-core", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel/tree/master/packages/babel-core" + }, + "scripts": { + "bench": "make bench", + "test": "make test" + }, + "version": "6.25.0" +} + +},{}],90:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.visitor = undefined; - -var _babelTypes = require("babel-types"); -var t = _interopRequireWildcard(_babelTypes); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -function getTDZStatus(refPath, bindingPath) { - var executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); +var _trimRight = require("trim-right"); - if (executionStatus === "before") { - return "inside"; - } else if (executionStatus === "after") { - return "outside"; - } else { - return "maybe"; - } -} +var _trimRight2 = _interopRequireDefault(_trimRight); -function buildTDZAssert(node, file) { - return t.callExpression(file.addHelper("temporalRef"), [node, t.stringLiteral(node.name), file.addHelper("temporalUndefined")]); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function isReference(node, scope, state) { - var declared = state.letReferences[node.name]; - if (!declared) return false; +var SPACES_RE = /^[ \t]+$/; - return scope.getBindingIdentifier(node.name) === declared; -} +var Buffer = function () { + function Buffer(map) { + (0, _classCallCheck3.default)(this, Buffer); + this._map = null; + this._buf = []; + this._last = ""; + this._queue = []; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: null, + line: null, + column: null, + filename: null + }; -var visitor = exports.visitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (!this.file.opts.tdz) return; + this._map = map; + } - var node = path.node, - parent = path.parent, - scope = path.scope; + Buffer.prototype.get = function get() { + this._flush(); + var map = this._map; + var result = { + code: (0, _trimRight2.default)(this._buf.join("")), + map: null, + rawMappings: map && map.getRawMappings() + }; - if (path.parentPath.isFor({ left: node })) return; - if (!isReference(node, scope, state)) return; + if (map) { + Object.defineProperty(result, "map", { + configurable: true, + enumerable: true, + get: function get() { + return this.map = map.get(); + }, + set: function set(value) { + Object.defineProperty(this, "map", { value: value, writable: true }); + } + }); + } - var bindingPath = scope.getBinding(node.name).path; + return result; + }; - var status = getTDZStatus(path, bindingPath); - if (status === "inside") return; + Buffer.prototype.append = function append(str) { + this._flush(); + var _sourcePosition = this._sourcePosition, + line = _sourcePosition.line, + column = _sourcePosition.column, + filename = _sourcePosition.filename, + identifierName = _sourcePosition.identifierName; - if (status === "maybe") { - var assert = buildTDZAssert(node, state.file); + this._append(str, line, column, identifierName, filename); + }; - bindingPath.parent._tdzThis = true; + Buffer.prototype.queue = function queue(str) { + if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { + this._queue.shift(); + }var _sourcePosition2 = this._sourcePosition, + line = _sourcePosition2.line, + column = _sourcePosition2.column, + filename = _sourcePosition2.filename, + identifierName = _sourcePosition2.identifierName; - path.skip(); + this._queue.unshift([str, line, column, identifierName, filename]); + }; - if (path.parentPath.isUpdateExpression()) { - if (parent._ignoreBlockScopingTDZ) return; - path.parentPath.replaceWith(t.sequenceExpression([assert, parent])); - } else { - path.replaceWith(assert); - } - } else if (status === "outside") { - path.replaceWith(t.throwStatement(t.inherits(t.newExpression(t.identifier("ReferenceError"), [t.stringLiteral(node.name + " is not defined - temporal dead zone")]), node))); + Buffer.prototype._flush = function _flush() { + var item = void 0; + while (item = this._queue.pop()) { + this._append.apply(this, item); } - }, - + }; - AssignmentExpression: { - exit: function exit(path, state) { - if (!this.file.opts.tdz) return; + Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { + if (this._map && str[0] !== "\n") { + this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); + } - var node = path.node; + this._buf.push(str); + this._last = str[str.length - 1]; - if (node._ignoreBlockScopingTDZ) return; + for (var i = 0; i < str.length; i++) { + if (str[i] === "\n") { + this._position.line++; + this._position.column = 0; + } else { + this._position.column++; + } + } + }; - var nodes = []; - var ids = path.getBindingIdentifiers(); + Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { + if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); + }; - for (var name in ids) { - var id = ids[name]; + Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { + if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); + }; - if (isReference(id, path.scope, state)) { - nodes.push(buildTDZAssert(id, state.file)); - } + Buffer.prototype.endsWith = function endsWith(suffix) { + if (suffix.length === 1) { + var last = void 0; + if (this._queue.length > 0) { + var str = this._queue[0][0]; + last = str[str.length - 1]; + } else { + last = this._last; } - if (nodes.length) { - node._ignoreBlockScopingTDZ = true; - nodes.push(node); - path.replaceWithMultiple(nodes.map(t.expressionStatement)); - } + return last === suffix; } - } -}; -},{"babel-types":145}],85:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -var _symbol = require("babel-runtime/core-js/symbol"); + var end = this._last + this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); + if (suffix.length <= end.length) { + return end.slice(-suffix.length) === suffix; + } -var _symbol2 = _interopRequireDefault(_symbol); + return false; + }; -exports.default = function (_ref) { - var t = _ref.types; + Buffer.prototype.hasContent = function hasContent() { + return this._queue.length > 0 || !!this._last; + }; - var VISITED = (0, _symbol2.default)(); + Buffer.prototype.source = function source(prop, loc) { + if (prop && !loc) return; - return { - visitor: { - ExportDefaultDeclaration: function ExportDefaultDeclaration(path) { - if (!path.get("declaration").isClassDeclaration()) return; + var pos = loc ? loc[prop] : null; - var node = path.node; + this._sourcePosition.identifierName = loc && loc.identifierName || null; + this._sourcePosition.line = pos ? pos.line : null; + this._sourcePosition.column = pos ? pos.column : null; + this._sourcePosition.filename = loc && loc.filename || null; + }; - var ref = node.declaration.id || path.scope.generateUidIdentifier("class"); - node.declaration.id = ref; - - path.replaceWith(node.declaration); - path.insertAfter(t.exportDefaultDeclaration(ref)); - }, - ClassDeclaration: function ClassDeclaration(path) { - var node = path.node; + Buffer.prototype.withSource = function withSource(prop, loc, cb) { + if (!this._map) return cb(); + var originalLine = this._sourcePosition.line; + var originalColumn = this._sourcePosition.column; + var originalFilename = this._sourcePosition.filename; + var originalIdentifierName = this._sourcePosition.identifierName; - var ref = node.id || path.scope.generateUidIdentifier("class"); + this.source(prop, loc); - path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(ref, t.toExpression(node))])); - }, - ClassExpression: function ClassExpression(path, state) { - var node = path.node; + cb(); - if (node[VISITED]) return; + this._sourcePosition.line = originalLine; + this._sourcePosition.column = originalColumn; + this._sourcePosition.filename = originalFilename; + this._sourcePosition.identifierName = originalIdentifierName; + }; - var inferred = (0, _babelHelperFunctionName2.default)(path); - if (inferred && inferred !== node) return path.replaceWith(inferred); + Buffer.prototype.getCurrentColumn = function getCurrentColumn() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); + var lastIndex = extra.lastIndexOf("\n"); - node[VISITED] = true; + return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; + }; - var Constructor = _vanilla2.default; - if (state.opts.loose) Constructor = _loose2.default; + Buffer.prototype.getCurrentLine = function getCurrentLine() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); - path.replaceWith(new Constructor(path, state.file).run()); - } + var count = 0; + for (var i = 0; i < extra.length; i++) { + if (extra[i] === "\n") count++; } + + return this._position.line + count; }; -}; -var _loose = require("./loose"); + return Buffer; +}(); -var _loose2 = _interopRequireDefault(_loose); +exports.default = Buffer; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":141,"trim-right":577}],91:[function(require,module,exports){ +"use strict"; -var _vanilla = require("./vanilla"); +exports.__esModule = true; +exports.File = File; +exports.Program = Program; +exports.BlockStatement = BlockStatement; +exports.Noop = Noop; +exports.Directive = Directive; -var _vanilla2 = _interopRequireDefault(_vanilla); +var _types = require("./types"); -var _babelHelperFunctionName = require("babel-helper-function-name"); +Object.defineProperty(exports, "DirectiveLiteral", { + enumerable: true, + get: function get() { + return _types.StringLiteral; + } +}); +function File(node) { + this.print(node.program, node); +} -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); +function Program(node) { + this.printInnerComments(node, false); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.printSequence(node.directives, node); + if (node.directives && node.directives.length) this.newline(); -module.exports = exports["default"]; -},{"./loose":86,"./vanilla":87,"babel-helper-function-name":73,"babel-runtime/core-js/symbol":98}],86:[function(require,module,exports){ -"use strict"; + this.printSequence(node.body, node); +} -exports.__esModule = true; +function BlockStatement(node) { + this.token("{"); + this.printInnerComments(node); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var hasDirectives = node.directives && node.directives.length; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + if (node.body.length || hasDirectives) { + this.newline(); -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + this.printSequence(node.directives, node, { indent: true }); + if (hasDirectives) this.newline(); -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + this.printSequence(node.body, node, { indent: true }); + this.removeTrailingNewline(); -var _inherits2 = require("babel-runtime/helpers/inherits"); + this.source("end", node.loc); -var _inherits3 = _interopRequireDefault(_inherits2); + if (!this.endsWith("\n")) this.newline(); -var _babelHelperFunctionName = require("babel-helper-function-name"); + this.rightBrace(); + } else { + this.source("end", node.loc); + this.token("}"); + } +} -var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); +function Noop() {} -var _vanilla = require("./vanilla"); +function Directive(node) { + this.print(node.value, node); + this.semicolon(); +} +},{"./types":100}],92:[function(require,module,exports){ +"use strict"; -var _vanilla2 = _interopRequireDefault(_vanilla); +exports.__esModule = true; +exports.ClassDeclaration = ClassDeclaration; +exports.ClassBody = ClassBody; +exports.ClassProperty = ClassProperty; +exports.ClassMethod = ClassMethod; +function ClassDeclaration(node) { + this.printJoin(node.decorators, node); + this.word("class"); -var _babelTypes = require("babel-types"); + if (node.id) { + this.space(); + this.print(node.id, node); + } -var t = _interopRequireWildcard(_babelTypes); + this.print(node.typeParameters, node); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } -var LooseClassTransformer = function (_VanillaTransformer) { - (0, _inherits3.default)(LooseClassTransformer, _VanillaTransformer); + this.space(); + this.print(node.body, node); +} - function LooseClassTransformer() { - (0, _classCallCheck3.default)(this, LooseClassTransformer); +exports.ClassExpression = ClassDeclaration; +function ClassBody(node) { + this.token("{"); + this.printInnerComments(node); + if (node.body.length === 0) { + this.token("}"); + } else { + this.newline(); - var _this = (0, _possibleConstructorReturn3.default)(this, _VanillaTransformer.apply(this, arguments)); + this.indent(); + this.printSequence(node.body, node); + this.dedent(); - _this.isLoose = true; - return _this; + if (!this.endsWith("\n")) this.newline(); + + this.rightBrace(); } +} - LooseClassTransformer.prototype._processMethod = function _processMethod(node, scope) { - if (!node.decorators) { +function ClassProperty(node) { + this.printJoin(node.decorators, node); - var classRef = this.classRef; - if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); - var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); + if (node.static) { + this.word("static"); + this.space(); + } + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + this._variance(node); + this.print(node.key, node); + } + this.print(node.typeAnnotation, node); + if (node.value) { + this.space(); + this.token("="); + this.space(); + this.print(node.value, node); + } + this.semicolon(); +} - var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); - func.returnType = node.returnType; - var key = t.toComputedKey(node, node.key); - if (t.isStringLiteral(key)) { - func = (0, _babelHelperFunctionName2.default)({ - node: func, - id: key, - scope: scope - }); - } +function ClassMethod(node) { + this.printJoin(node.decorators, node); - var expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); - t.inheritsComments(expr, node); - this.body.push(expr); - return true; - } - }; + if (node.static) { + this.word("static"); + this.space(); + } - return LooseClassTransformer; -}(_vanilla2.default); + if (node.kind === "constructorCall") { + this.word("call"); + this.space(); + } -exports.default = LooseClassTransformer; -module.exports = exports["default"]; -},{"./vanilla":87,"babel-helper-function-name":73,"babel-runtime/helpers/classCallCheck":103,"babel-runtime/helpers/inherits":104,"babel-runtime/helpers/possibleConstructorReturn":106,"babel-types":145}],87:[function(require,module,exports){ + this._method(node); +} +},{}],93:[function(require,module,exports){ "use strict"; exports.__esModule = true; +exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; +exports.UnaryExpression = UnaryExpression; +exports.DoExpression = DoExpression; +exports.ParenthesizedExpression = ParenthesizedExpression; +exports.UpdateExpression = UpdateExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.NewExpression = NewExpression; +exports.SequenceExpression = SequenceExpression; +exports.ThisExpression = ThisExpression; +exports.Super = Super; +exports.Decorator = Decorator; +exports.CallExpression = CallExpression; +exports.Import = Import; +exports.EmptyStatement = EmptyStatement; +exports.ExpressionStatement = ExpressionStatement; +exports.AssignmentPattern = AssignmentPattern; +exports.AssignmentExpression = AssignmentExpression; +exports.BindExpression = BindExpression; +exports.MemberExpression = MemberExpression; +exports.MetaProperty = MetaProperty; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _babelTypes = require("babel-types"); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var t = _interopRequireWildcard(_babelTypes); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +var _node = require("../node"); -var _babelTraverse = require("babel-traverse"); +var n = _interopRequireWildcard(_node); -var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); +function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { + this.word(node.operator); + this.space(); + } else { + this.token(node.operator); + } -var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + this.print(node.argument, node); +} -var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); +function DoExpression(node) { + this.word("do"); + this.space(); + this.print(node.body, node); +} -var _babelHelperDefineMap = require("babel-helper-define-map"); +function ParenthesizedExpression(node) { + this.token("("); + this.print(node.expression, node); + this.token(")"); +} -var defineMap = _interopRequireWildcard(_babelHelperDefineMap); +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); + } else { + this.print(node.argument, node); + this.token(node.operator); + } +} -var _babelTemplate = require("babel-template"); +function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.token("?"); + this.space(); + this.print(node.consequent, node); + this.space(); + this.token(":"); + this.space(); + this.print(node.alternate, node); +} -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); +function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee, node); + if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return; -var _babelTypes = require("babel-types"); + this.token("("); + this.printList(node.arguments, node); + this.token(")"); +} -var t = _interopRequireWildcard(_babelTypes); +function SequenceExpression(node) { + this.printList(node.expressions, node); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function ThisExpression() { + this.word("this"); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function Super() { + this.word("super"); +} -var buildDerivedConstructor = (0, _babelTemplate2.default)("\n (function () {\n super(...arguments);\n })\n"); +function Decorator(node) { + this.token("@"); + this.print(node.expression, node); + this.newline(); +} -var noMethodVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - if (!path.is("shadow")) { - path.skip(); - } - }, - Method: function Method(path) { - path.skip(); - } -}; +function commaSeparatorNewline() { + this.token(","); + this.newline(); -var verifyConstructorVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - Super: function Super(path) { - if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { - throw path.buildCodeFrameError("'super.*' is not allowed before super()"); - } - }, + if (!this.endsWith("\n")) this.space(); +} +function CallExpression(node) { + this.print(node.callee, node); - CallExpression: { - exit: function exit(path) { - if (path.get("callee").isSuper()) { - this.hasBareSuper = true; + this.token("("); - if (!this.isDerived) { - throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); - } - } - } - }, + var isPrettyCall = node._prettyCall; - ThisExpression: function ThisExpression(path) { - if (this.isDerived && !this.hasBareSuper) { - if (!path.inShadow("this")) { - throw path.buildCodeFrameError("'this' is not allowed before super()"); - } - } + var separator = void 0; + if (isPrettyCall) { + separator = commaSeparatorNewline; + this.newline(); + this.indent(); } -}]); -var findThisesVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { - ThisExpression: function ThisExpression(path) { - this.superThises.push(path); + this.printList(node.arguments, node, { separator: separator }); + + if (isPrettyCall) { + this.newline(); + this.dedent(); } -}]); -var ClassTransformer = function () { - function ClassTransformer(path, file) { - (0, _classCallCheck3.default)(this, ClassTransformer); + this.token(")"); +} - this.parent = path.parent; - this.scope = path.scope; - this.node = path.node; - this.path = path; - this.file = file; +function Import() { + this.word("import"); +} - this.clearDescriptors(); +function buildYieldAwait(keyword) { + return function (node) { + this.word(keyword); - this.instancePropBody = []; - this.instancePropRefs = {}; - this.staticPropBody = []; - this.body = []; + if (node.delegate) { + this.token("*"); + } - this.bareSuperAfter = []; - this.bareSupers = []; + if (node.argument) { + this.space(); + var terminatorState = this.startTerminatorless(); + this.print(node.argument, node); + this.endTerminatorless(terminatorState); + } + }; +} - this.pushedConstructor = false; - this.pushedInherits = false; - this.isLoose = false; +var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); +var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); - this.superThises = []; +function EmptyStatement() { + this.semicolon(true); +} - this.classId = this.node.id; +function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); +} - this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class"); +function AssignmentPattern(node) { + this.print(node.left, node); + if (node.left.optional) this.token("?"); + this.print(node.left.typeAnnotation, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); +} - this.superName = this.node.superClass || t.identifier("Function"); - this.isDerived = !!this.node.superClass; - } +function AssignmentExpression(node, parent) { + var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); - ClassTransformer.prototype.run = function run() { - var _this = this; + if (parens) { + this.token("("); + } - var superName = this.superName; - var file = this.file; - var body = this.body; + this.print(node.left, node); - var constructorBody = this.constructorBody = t.blockStatement([]); - this.constructor = this.buildConstructor(); + this.space(); + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } + this.space(); - var closureParams = []; - var closureArgs = []; + this.print(node.right, node); - if (this.isDerived) { - closureArgs.push(superName); + if (parens) { + this.token(")"); + } +} - superName = this.scope.generateUidIdentifierBasedOnNode(superName); - closureParams.push(superName); +function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + this.print(node.callee, node); +} - this.superName = superName; - } +exports.BinaryExpression = AssignmentExpression; +exports.LogicalExpression = AssignmentExpression; +function MemberExpression(node) { + this.print(node.object, node); - this.buildBody(); + if (!node.computed && t.isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } - constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [t.thisExpression(), this.classRef]))); + var computed = node.computed; + if (t.isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } - body = body.concat(this.staticPropBody.map(function (fn) { - return fn(_this.classRef); - })); + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + this.token("."); + this.print(node.property, node); + } +} - if (this.classId) { - if (body.length === 1) return t.toExpression(body[0]); - } +function MetaProperty(node) { + this.print(node.meta, node); + this.token("."); + this.print(node.property, node); +} +},{"../node":102,"babel-types":183}],94:[function(require,module,exports){ +"use strict"; - body.push(t.returnStatement(this.classRef)); +exports.__esModule = true; +exports.AnyTypeAnnotation = AnyTypeAnnotation; +exports.ArrayTypeAnnotation = ArrayTypeAnnotation; +exports.BooleanTypeAnnotation = BooleanTypeAnnotation; +exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; +exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; +exports.DeclareClass = DeclareClass; +exports.DeclareFunction = DeclareFunction; +exports.DeclareInterface = DeclareInterface; +exports.DeclareModule = DeclareModule; +exports.DeclareModuleExports = DeclareModuleExports; +exports.DeclareTypeAlias = DeclareTypeAlias; +exports.DeclareVariable = DeclareVariable; +exports.ExistentialTypeParam = ExistentialTypeParam; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.FunctionTypeParam = FunctionTypeParam; +exports.InterfaceExtends = InterfaceExtends; +exports._interfaceish = _interfaceish; +exports._variance = _variance; +exports.InterfaceDeclaration = InterfaceDeclaration; +exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; +exports.MixedTypeAnnotation = MixedTypeAnnotation; +exports.EmptyTypeAnnotation = EmptyTypeAnnotation; +exports.NullableTypeAnnotation = NullableTypeAnnotation; - var container = t.functionExpression(null, closureParams, t.blockStatement(body)); - container.shadow = true; - return t.callExpression(container, closureArgs); - }; +var _types = require("./types"); - ClassTransformer.prototype.buildConstructor = function buildConstructor() { - var func = t.functionDeclaration(this.classRef, [], this.constructorBody); - t.inherits(func, this.node); - return func; - }; +Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types.NumericLiteral; + } +}); +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types.StringLiteral; + } +}); +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeParameter = TypeParameter; +exports.TypeParameterInstantiation = TypeParameterInstantiation; +exports.ObjectTypeAnnotation = ObjectTypeAnnotation; +exports.ObjectTypeCallProperty = ObjectTypeCallProperty; +exports.ObjectTypeIndexer = ObjectTypeIndexer; +exports.ObjectTypeProperty = ObjectTypeProperty; +exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; +exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; +exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.TypeCastExpression = TypeCastExpression; +exports.VoidTypeAnnotation = VoidTypeAnnotation; +function AnyTypeAnnotation() { + this.word("any"); +} - ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "value"; - var scope = arguments[3]; +function ArrayTypeAnnotation(node) { + this.print(node.elementType, node); + this.token("["); + this.token("]"); +} - var mutatorMap = void 0; - if (node.static) { - this.hasStaticDescriptors = true; - mutatorMap = this.staticMutatorMap; - } else { - this.hasInstanceDescriptors = true; - mutatorMap = this.instanceMutatorMap; - } +function BooleanTypeAnnotation() { + this.word("boolean"); +} - var map = defineMap.push(mutatorMap, node, kind, this.file, scope); +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} - if (enumerable) { - map.enumerable = t.booleanLiteral(true); - } +function NullLiteralTypeAnnotation() { + this.word("null"); +} - return map; - }; +function DeclareClass(node) { + this.word("declare"); + this.space(); + this.word("class"); + this.space(); + this._interfaceish(node); +} - ClassTransformer.prototype.constructorMeMaybe = function constructorMeMaybe() { - var hasConstructor = false; - var paths = this.path.get("body.body"); - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +function DeclareFunction(node) { + this.word("declare"); + this.space(); + this.word("function"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation.typeAnnotation, node); + this.semicolon(); +} - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} - var path = _ref; +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id, node); + this.space(); + this.print(node.body, node); +} - hasConstructor = path.equals("kind", "constructor"); - if (hasConstructor) break; - } - if (hasConstructor) return; +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.token("."); + this.word("exports"); + this.print(node.typeAnnotation, node); +} - var params = void 0, - body = void 0; +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); +} - if (this.isDerived) { - var _constructor = buildDerivedConstructor().expression; - params = _constructor.params; - body = _constructor.body; - } else { - params = []; - body = t.blockStatement([]); - } +function DeclareVariable(node) { + this.word("declare"); + this.space(); + this.word("var"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + this.semicolon(); +} - this.path.get("body").unshiftContainer("body", t.classMethod("constructor", t.identifier("constructor"), params, body)); - }; +function ExistentialTypeParam() { + this.token("*"); +} - ClassTransformer.prototype.buildBody = function buildBody() { - this.constructorMeMaybe(); - this.pushBody(); - this.verifyConstructor(); +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.params, node); - if (this.userConstructor) { - var constructorBody = this.constructorBody; - constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); - t.inherits(this.constructor, this.userConstructor); - t.inherits(constructorBody, this.userConstructor.body); + if (node.rest) { + if (node.params.length) { + this.token(","); + this.space(); } + this.token("..."); + this.print(node.rest, node); + } - this.pushDescriptors(); - }; - - ClassTransformer.prototype.pushBody = function pushBody() { - var classBodyPaths = this.path.get("body.body"); - - for (var _iterator2 = classBodyPaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + this.token(")"); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { + this.token(":"); + } else { + this.space(); + this.token("=>"); + } - var path = _ref2; + this.space(); + this.print(node.returnType, node); +} - var node = path.node; +function FunctionTypeParam(node) { + this.print(node.name, node); + if (node.optional) this.token("?"); + this.token(":"); + this.space(); + this.print(node.typeAnnotation, node); +} - if (path.isClassProperty()) { - throw path.buildCodeFrameError("Missing class properties transform."); - } +function InterfaceExtends(node) { + this.print(node.id, node); + this.print(node.typeParameters, node); +} - if (node.decorators) { - throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); - } +exports.ClassImplements = InterfaceExtends; +exports.GenericTypeAnnotation = InterfaceExtends; +function _interfaceish(node) { + this.print(node.id, node); + this.print(node.typeParameters, node); + if (node.extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + if (node.mixins && node.mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins, node); + } + this.space(); + this.print(node.body, node); +} - if (t.isClassMethod(node)) { - var isConstructor = node.kind === "constructor"; +function _variance(node) { + if (node.variance === "plus") { + this.token("+"); + } else if (node.variance === "minus") { + this.token("-"); + } +} - if (isConstructor) { - path.traverse(verifyConstructorVisitor, this); +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); + this._interfaceish(node); +} - if (!this.hasBareSuper && this.isDerived) { - throw path.buildCodeFrameError("missing super() call in constructor"); - } - } +function andSeparator() { + this.space(); + this.token("&"); + this.space(); +} - var replaceSupers = new _babelHelperReplaceSupers2.default({ - forceSuperMemoisation: isConstructor, - methodPath: path, - methodNode: node, - objectRef: this.classRef, - superRef: this.superName, - isStatic: node.static, - isLoose: this.isLoose, - scope: this.scope, - file: this.file - }, true); +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, node, { separator: andSeparator }); +} - replaceSupers.replace(); +function MixedTypeAnnotation() { + this.word("mixed"); +} - if (isConstructor) { - this.pushConstructor(replaceSupers, node, path); - } else { - this.pushMethod(node, path); - } - } - } - }; +function EmptyTypeAnnotation() { + this.word("empty"); +} - ClassTransformer.prototype.clearDescriptors = function clearDescriptors() { - this.hasInstanceDescriptors = false; - this.hasStaticDescriptors = false; +function NullableTypeAnnotation(node) { + this.token("?"); + this.print(node.typeAnnotation, node); +} - this.instanceMutatorMap = {}; - this.staticMutatorMap = {}; - }; +function NumberTypeAnnotation() { + this.word("number"); +} - ClassTransformer.prototype.pushDescriptors = function pushDescriptors() { - this.pushInherits(); +function StringTypeAnnotation() { + this.word("string"); +} - var body = this.body; +function ThisTypeAnnotation() { + this.word("this"); +} - var instanceProps = void 0; - var staticProps = void 0; +function TupleTypeAnnotation(node) { + this.token("["); + this.printList(node.types, node); + this.token("]"); +} - if (this.hasInstanceDescriptors) { - instanceProps = defineMap.toClassObject(this.instanceMutatorMap); - } +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument, node); +} - if (this.hasStaticDescriptors) { - staticProps = defineMap.toClassObject(this.staticMutatorMap); - } +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); + this.semicolon(); +} - if (instanceProps || staticProps) { - if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); - if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); +function TypeAnnotation(node) { + this.token(":"); + this.space(); + if (node.optional) this.token("?"); + this.print(node.typeAnnotation, node); +} - var nullNode = t.nullLiteral(); +function TypeParameter(node) { + this._variance(node); - var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; + this.word(node.name); - if (instanceProps) args[1] = instanceProps; - if (staticProps) args[2] = staticProps; + if (node.bound) { + this.print(node.bound, node); + } - if (this.instanceInitializersId) { - args[3] = this.instanceInitializersId; - body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); - } + if (node.default) { + this.space(); + this.token("="); + this.space(); + this.print(node.default, node); + } +} - if (this.staticInitializersId) { - args[4] = this.staticInitializersId; - body.unshift(this.buildObjectAssignment(this.staticInitializersId)); - } +function TypeParameterInstantiation(node) { + this.token("<"); + this.printList(node.params, node, {}); + this.token(">"); +} - var lastNonNullIndex = 0; - for (var i = 0; i < args.length; i++) { - if (args[i] !== nullNode) lastNonNullIndex = i; - } - args = args.slice(0, lastNonNullIndex + 1); +exports.TypeParameterDeclaration = TypeParameterInstantiation; +function ObjectTypeAnnotation(node) { + var _this = this; - body.push(t.expressionStatement(t.callExpression(this.file.addHelper("createClass"), args))); - } + if (node.exact) { + this.token("{|"); + } else { + this.token("{"); + } - this.clearDescriptors(); - }; + var props = node.properties.concat(node.callProperties, node.indexers); - ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { - return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); - }; + if (props.length) { + this.space(); - ClassTransformer.prototype.wrapSuperCall = function wrapSuperCall(bareSuper, superRef, thisRef, body) { - var bareSuperNode = bareSuper.node; + this.printJoin(props, node, { + addNewlines: function addNewlines(leading) { + if (leading && !props[0]) return 1; + }, - if (this.isLoose) { - bareSuperNode.arguments.unshift(t.thisExpression()); - if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { - bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); - } else { - bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); + indent: true, + statement: true, + iterator: function iterator() { + if (props.length !== 1) { + if (_this.format.flowCommaSeparator) { + _this.token(","); + } else { + _this.semicolon(); + } + _this.space(); + } } - } else { - bareSuperNode = (0, _babelHelperOptimiseCallExpression2.default)(t.logicalExpression("||", t.memberExpression(this.classRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef])), t.thisExpression(), bareSuperNode.arguments); - } - - var call = t.callExpression(this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode]); - - var bareSuperAfter = this.bareSuperAfter.map(function (fn) { - return fn(thisRef); }); - if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { + this.space(); + } - if (this.superThises.length || bareSuperAfter.length) { - bareSuper.scope.push({ id: thisRef }); - call = t.assignmentExpression("=", thisRef, call); - } + if (node.exact) { + this.token("|}"); + } else { + this.token("}"); + } +} - if (bareSuperAfter.length) { - call = t.toSequenceExpression([call].concat(bareSuperAfter, [thisRef])); - } +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.print(node.value, node); +} - bareSuper.parentPath.replaceWith(t.returnStatement(call)); - } else { - bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(thisRef, call)])].concat(bareSuperAfter, [t.expressionStatement(thisRef)])); - } - }; - - ClassTransformer.prototype.verifyConstructor = function verifyConstructor() { - var _this2 = this; +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this._variance(node); + this.token("["); + this.print(node.id, node); + this.token(":"); + this.space(); + this.print(node.key, node); + this.token("]"); + this.token(":"); + this.space(); + this.print(node.value, node); +} - if (!this.isDerived) return; +function ObjectTypeProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this._variance(node); + this.print(node.key, node); + if (node.optional) this.token("?"); + this.token(":"); + this.space(); + this.print(node.value, node); +} - var path = this.userConstructorPath; - var body = path.get("body"); +function ObjectTypeSpreadProperty(node) { + this.token("..."); + this.print(node.argument, node); +} - path.traverse(findThisesVisitor, this); +function QualifiedTypeIdentifier(node) { + this.print(node.qualification, node); + this.token("."); + this.print(node.id, node); +} - var guaranteedSuperBeforeFinish = !!this.bareSupers.length; +function orSeparator() { + this.space(); + this.token("|"); + this.space(); +} - var superRef = this.superName || t.identifier("Function"); - var thisRef = path.scope.generateUidIdentifier("this"); +function UnionTypeAnnotation(node) { + this.printJoin(node.types, node, { separator: orSeparator }); +} - for (var _iterator3 = this.bareSupers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +function TypeCastExpression(node) { + this.token("("); + this.print(node.expression, node); + this.print(node.typeAnnotation, node); + this.token(")"); +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +function VoidTypeAnnotation() { + this.word("void"); +} +},{"./types":100}],95:[function(require,module,exports){ +"use strict"; - var bareSuper = _ref3; +exports.__esModule = true; - this.wrapSuperCall(bareSuper, superRef, thisRef, body); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - if (guaranteedSuperBeforeFinish) { - bareSuper.find(function (parentPath) { - if (parentPath === path) { - return true; - } +var _getIterator3 = _interopRequireDefault(_getIterator2); - if (parentPath.isLoop() || parentPath.isConditional()) { - guaranteedSuperBeforeFinish = false; - return true; - } - }); - } - } +exports.JSXAttribute = JSXAttribute; +exports.JSXIdentifier = JSXIdentifier; +exports.JSXNamespacedName = JSXNamespacedName; +exports.JSXMemberExpression = JSXMemberExpression; +exports.JSXSpreadAttribute = JSXSpreadAttribute; +exports.JSXExpressionContainer = JSXExpressionContainer; +exports.JSXSpreadChild = JSXSpreadChild; +exports.JSXText = JSXText; +exports.JSXElement = JSXElement; +exports.JSXOpeningElement = JSXOpeningElement; +exports.JSXClosingElement = JSXClosingElement; +exports.JSXEmptyExpression = JSXEmptyExpression; - for (var _iterator4 = this.superThises, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } +function JSXAttribute(node) { + this.print(node.name, node); + if (node.value) { + this.token("="); + this.print(node.value, node); + } +} - var thisPath = _ref4; +function JSXIdentifier(node) { + this.word(node.name); +} - thisPath.replaceWith(thisRef); - } +function JSXNamespacedName(node) { + this.print(node.namespace, node); + this.token(":"); + this.print(node.name, node); +} - var wrapReturn = function wrapReturn(returnArg) { - return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || [])); - }; +function JSXMemberExpression(node) { + this.print(node.object, node); + this.token("."); + this.print(node.property, node); +} - var bodyPaths = body.get("body"); - if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { - body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); - } +function JSXSpreadAttribute(node) { + this.token("{"); + this.token("..."); + this.print(node.argument, node); + this.token("}"); +} - for (var _iterator5 = this.superReturns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; +function JSXExpressionContainer(node) { + this.token("{"); + this.print(node.expression, node); + this.token("}"); +} - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } +function JSXSpreadChild(node) { + this.token("{"); + this.token("..."); + this.print(node.expression, node); + this.token("}"); +} - var returnPath = _ref5; +function JSXText(node) { + this.token(node.value); +} - if (returnPath.node.argument) { - var ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); - returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref)]); - } else { - returnPath.get("argument").replaceWith(wrapReturn()); - } - } - }; +function JSXElement(node) { + var open = node.openingElement; + this.print(open, node); + if (open.selfClosing) return; - ClassTransformer.prototype.pushMethod = function pushMethod(node, path) { - var scope = path ? path.scope : this.scope; + this.indent(); + for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (node.kind === "method") { - if (this._processMethod(node, scope)) return; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } - this.pushToMap(node, false, null, scope); - }; + var child = _ref; - ClassTransformer.prototype._processMethod = function _processMethod() { - return false; - }; + this.print(child, node); + } + this.dedent(); - ClassTransformer.prototype.pushConstructor = function pushConstructor(replaceSupers, method, path) { - this.bareSupers = replaceSupers.bareSupers; - this.superReturns = replaceSupers.returns; + this.print(node.closingElement, node); +} - if (path.scope.hasOwnBinding(this.classRef.name)) { - path.scope.rename(this.classRef.name); - } +function spaceSeparator() { + this.space(); +} - var construct = this.constructor; +function JSXOpeningElement(node) { + this.token("<"); + this.print(node.name, node); + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, node, { separator: spaceSeparator }); + } + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.token(">"); + } +} - this.userConstructorPath = path; - this.userConstructor = method; - this.hasConstructor = true; +function JSXClosingElement(node) { + this.token(""); +} - t.inheritsComments(construct, method); +function JSXEmptyExpression() {} +},{"babel-runtime/core-js/get-iterator":127}],96:[function(require,module,exports){ +"use strict"; - construct._ignoreUserWhitespace = true; - construct.params = method.params; +exports.__esModule = true; +exports.FunctionDeclaration = undefined; +exports._params = _params; +exports._method = _method; +exports.FunctionExpression = FunctionExpression; +exports.ArrowFunctionExpression = ArrowFunctionExpression; - t.inherits(construct.body, method.body); - construct.body.directives = method.body.directives; +var _babelTypes = require("babel-types"); - this._pushConstructor(); - }; +var t = _interopRequireWildcard(_babelTypes); - ClassTransformer.prototype._pushConstructor = function _pushConstructor() { - if (this.pushedConstructor) return; - this.pushedConstructor = true; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { - this.pushDescriptors(); - } +function _params(node) { + var _this = this; - this.body.push(this.constructor); + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.params, node, { + iterator: function iterator(node) { + if (node.optional) _this.token("?"); + _this.print(node.typeAnnotation, node); + } + }); + this.token(")"); - this.pushInherits(); - }; + if (node.returnType) { + this.print(node.returnType, node); + } +} - ClassTransformer.prototype.pushInherits = function pushInherits() { - if (!this.isDerived || this.pushedInherits) return; +function _method(node) { + var kind = node.kind; + var key = node.key; - this.pushedInherits = true; - this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"), [this.classRef, this.superName]))); - }; + if (kind === "method" || kind === "init") { + if (node.generator) { + this.token("*"); + } + } - return ClassTransformer; -}(); + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } -exports.default = ClassTransformer; -module.exports = exports["default"]; -},{"babel-helper-define-map":72,"babel-helper-optimise-call-expression":75,"babel-helper-replace-supers":76,"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/classCallCheck":103,"babel-template":108,"babel-traverse":112,"babel-types":145}],88:[function(require,module,exports){ -"use strict"; + if (node.async) { + this.word("async"); + this.space(); + } -exports.__esModule = true; + if (node.computed) { + this.token("["); + this.print(key, node); + this.token("]"); + } else { + this.print(key, node); + } -exports.default = function (_ref) { - var messages = _ref.messages, - template = _ref.template, - t = _ref.types; + this._params(node); + this.space(); + this.print(node.body, node); +} - var buildForOfArray = template("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "); +function FunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + this.word("function"); + if (node.generator) this.token("*"); - var buildForOfLoose = template("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "); + if (node.id) { + this.space(); + this.print(node.id, node); + } else { + this.space(); + } - var buildForOf = template("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n "); + this._params(node); + this.space(); + this.print(node.body, node); +} +exports.FunctionDeclaration = FunctionExpression; +function ArrowFunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } - function _ForOfStatementArray(path) { - var node = path.node, - scope = path.scope; + var firstParam = node.params[0]; - var nodes = []; - var right = node.right; + if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { + this.print(firstParam, node); + } else { + this._params(node); + } - if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { - var uid = scope.generateUidIdentifier("arr"); - nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)])); - right = uid; - } + this.space(); + this.token("=>"); + this.space(); - var iterationKey = scope.generateUidIdentifier("i"); + this.print(node.body, node); +} - var loop = buildForOfArray({ - BODY: node.body, - KEY: iterationKey, - ARR: right - }); +function hasTypes(node, param) { + return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; +} +},{"babel-types":183}],97:[function(require,module,exports){ +"use strict"; - t.inherits(loop, node); - t.ensureBlock(loop); +exports.__esModule = true; +exports.ImportSpecifier = ImportSpecifier; +exports.ImportDefaultSpecifier = ImportDefaultSpecifier; +exports.ExportDefaultSpecifier = ExportDefaultSpecifier; +exports.ExportSpecifier = ExportSpecifier; +exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; +exports.ExportAllDeclaration = ExportAllDeclaration; +exports.ExportNamedDeclaration = ExportNamedDeclaration; +exports.ExportDefaultDeclaration = ExportDefaultDeclaration; +exports.ImportDeclaration = ImportDeclaration; +exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; - var iterationValue = t.memberExpression(right, iterationKey, true); +var _babelTypes = require("babel-types"); - var left = node.left; - if (t.isVariableDeclaration(left)) { - left.declarations[0].init = iterationValue; - loop.body.body.unshift(left); - } else { - loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue))); - } +var t = _interopRequireWildcard(_babelTypes); - if (path.parentPath.isLabeledStatement()) { - loop = t.labeledStatement(path.parentPath.node.label, loop); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - nodes.push(loop); +function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } - return nodes; + this.print(node.imported, node); + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); } +} - return { - visitor: { - ForOfStatement: function ForOfStatement(path, state) { - if (path.get("right").isArrayExpression()) { - if (path.parentPath.isLabeledStatement()) { - return path.parentPath.replaceWithMultiple(_ForOfStatementArray(path)); - } else { - return path.replaceWithMultiple(_ForOfStatementArray(path)); - } - } +function ImportDefaultSpecifier(node) { + this.print(node.local, node); +} - var callback = spec; - if (state.opts.loose) callback = loose; +function ExportDefaultSpecifier(node) { + this.print(node.exported, node); +} - var node = path.node; +function ExportSpecifier(node) { + this.print(node.local, node); + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } +} - var build = callback(path, state); - var declar = build.declar; - var loop = build.loop; - var block = loop.body; +function ExportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); +} - path.ensureBlock(); +function ExportAllDeclaration(node) { + this.word("export"); + this.space(); + this.token("*"); + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.semicolon(); +} - if (declar) { - block.body.push(declar); - } +function ExportNamedDeclaration() { + this.word("export"); + this.space(); + ExportDeclaration.apply(this, arguments); +} - block.body = block.body.concat(node.body.body); +function ExportDefaultDeclaration() { + this.word("export"); + this.space(); + this.word("default"); + this.space(); + ExportDeclaration.apply(this, arguments); +} - t.inherits(loop, node); - t.inherits(loop.body, node.body); +function ExportDeclaration(node) { + if (node.declaration) { + var declar = node.declaration; + this.print(declar, node); + if (!t.isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } - if (build.replaceParent) { - path.parentPath.replaceWithMultiple(build.node); - path.remove(); - } else { - path.replaceWithMultiple(build.node); + var specifiers = node.specifiers.slice(0); + + var hasSpecial = false; + while (true) { + var first = specifiers[0]; + if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift(), node); + if (specifiers.length) { + this.token(","); + this.space(); } + } else { + break; } } - }; - - function loose(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - var left = node.left; - - var declar = void 0, - id = void 0; - - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - id = left; - } else if (t.isVariableDeclaration(left)) { - id = scope.generateUidIdentifier("ref"); - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]); - } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); - } - - var iteratorKey = scope.generateUidIdentifier("iterator"); - var isArrayKey = scope.generateUidIdentifier("isArray"); - - var loop = buildForOfLoose({ - LOOP_OBJECT: iteratorKey, - IS_ARRAY: isArrayKey, - OBJECT: node.right, - INDEX: scope.generateUidIdentifier("i"), - ID: id - }); - if (!declar) { - loop.body.body.shift(); + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.token("{"); + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); + } + this.token("}"); } - var isLabeledParent = t.isLabeledStatement(parent); - var labeled = void 0; - - if (isLabeledParent) { - labeled = t.labeledStatement(parent.label, loop); + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); } - return { - replaceParent: isLabeledParent, - declar: declar, - node: labeled || loop, - loop: loop - }; + this.semicolon(); } +} - function spec(path, file) { - var node = path.node, - scope = path.scope, - parent = path.parent; - - var left = node.left; - var declar = void 0; +function ImportDeclaration(node) { + this.word("import"); + this.space(); - var stepKey = scope.generateUidIdentifier("step"); - var stepValue = t.memberExpression(stepKey, t.identifier("value")); + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } - if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { - declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); - } else if (t.isVariableDeclaration(left)) { - declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); - } else { - throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + var specifiers = node.specifiers.slice(0); + if (specifiers && specifiers.length) { + while (true) { + var first = specifiers[0]; + if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } } - var iteratorKey = scope.generateUidIdentifier("iterator"); - - var template = buildForOf({ - ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), - ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), - ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), - ITERATOR_KEY: iteratorKey, - STEP_KEY: stepKey, - OBJECT: node.right, - BODY: null - }); - - var isLabeledParent = t.isLabeledStatement(parent); - - var tryBody = template[3].block.body; - var loop = tryBody[0]; - - if (isLabeledParent) { - tryBody[0] = t.labeledStatement(parent.label, loop); + if (specifiers.length) { + this.token("{"); + this.space(); + this.printList(specifiers, node); + this.space(); + this.token("}"); } - return { - replaceParent: isLabeledParent, - declar: declar, - loop: loop, - node: template - }; + this.space(); + this.word("from"); + this.space(); } -}; - -module.exports = exports["default"]; -},{}],89:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; -},{"core-js/library/fn/get-iterator":155}],90:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; -},{"core-js/library/fn/json/stringify":156}],91:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; -},{"core-js/library/fn/map":157}],92:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; -},{"core-js/library/fn/number/max-safe-integer":158}],93:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; -},{"core-js/library/fn/object/assign":159}],94:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; -},{"core-js/library/fn/object/create":160}],95:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; -},{"core-js/library/fn/object/get-own-property-symbols":161}],96:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; -},{"core-js/library/fn/object/keys":162}],97:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; -},{"core-js/library/fn/object/set-prototype-of":163}],98:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; -},{"core-js/library/fn/symbol":165}],99:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; -},{"core-js/library/fn/symbol/for":164}],100:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; -},{"core-js/library/fn/symbol/iterator":166}],101:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; -},{"core-js/library/fn/weak-map":167}],102:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; -},{"core-js/library/fn/weak-set":168}],103:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; + this.print(node.source, node); + this.semicolon(); +} -exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; -},{}],104:[function(require,module,exports){ +function ImportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); +} +},{"babel-types":183}],98:[function(require,module,exports){ "use strict"; exports.__esModule = true; +exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForAwaitStatement = exports.ForOfStatement = exports.ForInStatement = undefined; -var _setPrototypeOf = require("../core-js/object/set-prototype-of"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); +var _getIterator3 = _interopRequireDefault(_getIterator2); -var _create = require("../core-js/object/create"); +exports.WithStatement = WithStatement; +exports.IfStatement = IfStatement; +exports.ForStatement = ForStatement; +exports.WhileStatement = WhileStatement; +exports.DoWhileStatement = DoWhileStatement; +exports.LabeledStatement = LabeledStatement; +exports.TryStatement = TryStatement; +exports.CatchClause = CatchClause; +exports.SwitchStatement = SwitchStatement; +exports.SwitchCase = SwitchCase; +exports.DebuggerStatement = DebuggerStatement; +exports.VariableDeclaration = VariableDeclaration; +exports.VariableDeclarator = VariableDeclarator; -var _create2 = _interopRequireDefault(_create); +var _babelTypes = require("babel-types"); -var _typeof2 = require("../helpers/typeof"); +var t = _interopRequireWildcard(_babelTypes); -var _typeof3 = _interopRequireDefault(_typeof2); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -exports.default = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); - } - - subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; -}; -},{"../core-js/object/create":94,"../core-js/object/set-prototype-of":97,"../helpers/typeof":107}],105:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; +function WithStatement(node) { + this.word("with"); + this.space(); + this.token("("); + this.print(node.object, node); + this.token(")"); + this.printBlock(node); +} -exports.default = function (obj, keys) { - var target = {}; +function IfStatement(node) { + this.word("if"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.space(); - for (var i in obj) { - if (keys.indexOf(i) >= 0) continue; - if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; - target[i] = obj[i]; + var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); + if (needsBlock) { + this.token("{"); + this.newline(); + this.indent(); } - return target; -}; -},{}],106:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("../helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); + this.printAndIndentOnComments(node.consequent, node); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (needsBlock) { + this.dedent(); + this.newline(); + this.token("}"); + } -exports.default = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + if (node.alternate) { + if (this.endsWith("}")) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); } +} - return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; -}; -},{"../helpers/typeof":107}],107:[function(require,module,exports){ -"use strict"; +function getLastStatement(statement) { + if (!t.isStatement(statement.body)) return statement; + return getLastStatement(statement.body); +} -exports.__esModule = true; +function ForStatement(node) { + this.word("for"); + this.space(); + this.token("("); -var _iterator = require("../core-js/symbol/iterator"); + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.token(";"); -var _iterator2 = _interopRequireDefault(_iterator); + if (node.test) { + this.space(); + this.print(node.test, node); + } + this.token(";"); -var _symbol = require("../core-js/symbol"); + if (node.update) { + this.space(); + this.print(node.update, node); + } -var _symbol2 = _interopRequireDefault(_symbol); + this.token(")"); + this.printBlock(node); +} -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; +function WhileStatement(node) { + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.printBlock(node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var buildForXStatement = function buildForXStatement(op) { + return function (node) { + this.word("for"); + this.space(); + if (op === "await") { + this.word("await"); + this.space(); + } + this.token("("); -exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); + this.print(node.left, node); + this.space(); + this.word(op === "await" ? "of" : op); + this.space(); + this.print(node.right, node); + this.token(")"); + this.printBlock(node); + }; }; -},{"../core-js/symbol":98,"../core-js/symbol/iterator":100}],108:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (code, opts) { - var stack = void 0; - try { - throw new Error(); - } catch (error) { - if (error.stack) { - stack = error.stack.split("\n").slice(1).join("\n"); - } - } +var ForInStatement = exports.ForInStatement = buildForXStatement("in"); +var ForOfStatement = exports.ForOfStatement = buildForXStatement("of"); +var ForAwaitStatement = exports.ForAwaitStatement = buildForXStatement("await"); - opts = (0, _assign2.default)({ - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - preserveComments: false - }, opts); +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.semicolon(); +} - var _getAst = function getAst() { - var ast = void 0; +function buildLabelStatement(prefix) { + var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; - try { - ast = babylon.parse(code, opts); + return function (node) { + this.word(prefix); - ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); + var label = node[key]; + if (label) { + this.space(); - _babelTraverse2.default.cheap(ast, function (node) { - node[FROM_TEMPLATE] = true; - }); - } catch (err) { - err.stack = err.stack + "from\n" + stack; - throw err; + var terminatorState = this.startTerminatorless(); + this.print(label, node); + this.endTerminatorless(terminatorState); } - _getAst = function getAst() { - return ast; - }; - - return ast; + this.semicolon(); }; +} - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); +var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); +var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); +var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); - return useTemplate(_getAst(), args); - }; -}; +function LabeledStatement(node) { + this.print(node.label, node); + this.token(":"); + this.space(); + this.print(node.body, node); +} -var _cloneDeep = require("lodash/cloneDeep"); +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); -var _cloneDeep2 = _interopRequireDefault(_cloneDeep); + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } -var _assign = require("lodash/assign"); + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } +} -var _assign2 = _interopRequireDefault(_assign); +function CatchClause(node) { + this.word("catch"); + this.space(); + this.token("("); + this.print(node.param, node); + this.token(")"); + this.space(); + this.print(node.body, node); +} -var _has = require("lodash/has"); +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.token("("); + this.print(node.discriminant, node); + this.token(")"); + this.space(); + this.token("{"); -var _has2 = _interopRequireDefault(_has); + this.printSequence(node.cases, node, { + indent: true, + addNewlines: function addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + }); -var _babelTraverse = require("babel-traverse"); + this.token("}"); +} -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.token(":"); + } else { + this.word("default"); + this.token(":"); + } -var _babylon = require("babylon"); + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { indent: true }); + } +} -var babylon = _interopRequireWildcard(_babylon); +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} -var _babelTypes = require("babel-types"); +function variableDeclarationIdent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { + this.space(true); + } +} -var t = _interopRequireWildcard(_babelTypes); +function constDeclarationIdent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { + this.space(true); + } +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function VariableDeclaration(node, parent) { + this.word(node.kind); + this.space(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var hasInits = false; -var FROM_TEMPLATE = "_fromTemplate"; -var TEMPLATE_SKIP = (0, _symbol2.default)(); + if (!t.isFor(parent)) { + for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -function useTemplate(ast, nodes) { - ast = (0, _cloneDeep2.default)(ast); - var _ast = ast, - program = _ast.program; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + var declar = _ref; - if (nodes.length) { - (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); + if (declar.init) { + hasInits = true; + } + } } - if (program.body.length > 1) { - return program.body; - } else { - return program.body[0]; + var separator = void 0; + if (hasInits) { + separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; } -} - -var templateVisitor = { - noScope: true, - - enter: function enter(path, args) { - var node = path.node; - - if (node[TEMPLATE_SKIP]) return path.skip(); - - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - var replacement = void 0; - if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { - if ((0, _has2.default)(args[0], node.name)) { - replacement = args[0][node.name]; - } else if (node.name[0] === "$") { - var i = +node.name.slice(1); - if (args[i]) replacement = args[i]; - } - } + this.printList(node.declarations, node, { separator: separator }); - if (replacement === null) { - path.remove(); - } + if (t.isFor(parent)) { + if (parent.left === node || parent.init === node) return; + } - if (replacement) { - replacement[TEMPLATE_SKIP] = true; - path.replaceInline(replacement); - } - }, - exit: function exit(_ref) { - var node = _ref.node; + this.semicolon(); +} - if (!node.loc) _babelTraverse2.default.clearNode(node); +function VariableDeclarator(node) { + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + if (node.init) { + this.space(); + this.token("="); + this.space(); + this.print(node.init, node); } -}; -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":98,"babel-traverse":112,"babel-types":145,"babylon":149,"lodash/assign":452,"lodash/cloneDeep":456,"lodash/has":468}],109:[function(require,module,exports){ +} +},{"babel-runtime/core-js/get-iterator":127,"babel-types":183}],99:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.scope = exports.path = undefined; - -var _weakMap = require("babel-runtime/core-js/weak-map"); - -var _weakMap2 = _interopRequireDefault(_weakMap); - -exports.clear = clear; -exports.clearPath = clearPath; -exports.clearScope = clearScope; +exports.TaggedTemplateExpression = TaggedTemplateExpression; +exports.TemplateElement = TemplateElement; +exports.TemplateLiteral = TemplateLiteral; +function TaggedTemplateExpression(node) { + this.print(node.tag, node); + this.print(node.quasi, node); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function TemplateElement(node, parent) { + var isFirst = parent.quasis[0] === node; + var isLast = parent.quasis[parent.quasis.length - 1] === node; -var path = exports.path = new _weakMap2.default(); -var scope = exports.scope = new _weakMap2.default(); + var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); -function clear() { - clearPath(); - clearScope(); + this.token(value); } -function clearPath() { - exports.path = path = new _weakMap2.default(); -} +function TemplateLiteral(node) { + var quasis = node.quasis; -function clearScope() { - exports.scope = scope = new _weakMap2.default(); + for (var i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); + + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } } -},{"babel-runtime/core-js/weak-map":101}],110:[function(require,module,exports){ -(function (process){ +},{}],100:[function(require,module,exports){ "use strict"; exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _path2 = require("./path"); - -var _path3 = _interopRequireDefault(_path2); +exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; +exports.Identifier = Identifier; +exports.RestElement = RestElement; +exports.ObjectExpression = ObjectExpression; +exports.ObjectMethod = ObjectMethod; +exports.ObjectProperty = ObjectProperty; +exports.ArrayExpression = ArrayExpression; +exports.RegExpLiteral = RegExpLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.NullLiteral = NullLiteral; +exports.NumericLiteral = NumericLiteral; +exports.StringLiteral = StringLiteral; var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _jsesc = require("jsesc"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _jsesc2 = _interopRequireDefault(_jsesc); -var testing = process.env.NODE_ENV === "test"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var TraversalContext = function () { - function TraversalContext(scope, opts, state, parentPath) { - (0, _classCallCheck3.default)(this, TraversalContext); - this.queue = null; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - this.parentPath = parentPath; - this.scope = scope; - this.state = state; - this.opts = opts; +function Identifier(node) { + if (node.variance) { + if (node.variance === "plus") { + this.token("+"); + } else if (node.variance === "minus") { + this.token("-"); + } } - TraversalContext.prototype.shouldVisit = function shouldVisit(node) { - var opts = this.opts; - if (opts.enter || opts.exit) return true; - - if (opts[node.type]) return true; + this.word(node.name); +} - var keys = t.VISITOR_KEYS[node.type]; - if (!keys || !keys.length) return false; +function RestElement(node) { + this.token("..."); + this.print(node.argument, node); +} - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +exports.SpreadElement = RestElement; +exports.SpreadProperty = RestElement; +exports.RestProperty = RestElement; +function ObjectExpression(node) { + var props = node.properties; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.token("{"); + this.printInnerComments(node); - var key = _ref; + if (props.length) { + this.space(); + this.printList(props, node, { indent: true, statement: true }); + this.space(); + } - if (node[key]) return true; - } + this.token("}"); +} - return false; - }; +exports.ObjectPattern = ObjectExpression; +function ObjectMethod(node) { + this.printJoin(node.decorators, node); + this._method(node); +} - TraversalContext.prototype.create = function create(node, obj, key, listKey) { - return _path3.default.get({ - parentPath: this.parentPath, - parent: node, - container: obj, - key: key, - listKey: listKey - }); - }; +function ObjectProperty(node) { + this.printJoin(node.decorators, node); - TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { - if (this.trap) { - throw new Error("Infinite cycle detected"); + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { + this.print(node.value, node); + return; } - if (this.queue) { - if (notPriority) { - this.queue.push(path); - } else { - this.priorityQueue.push(path); - } - } - }; + this.print(node.key, node); - TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { - if (container.length === 0) return false; + if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } - var queue = []; + this.token(":"); + this.space(); + this.print(node.value, node); +} - for (var key = 0; key < container.length; key++) { - var node = container[key]; - if (node && this.shouldVisit(node)) { - queue.push(this.create(parent, container, key, listKey)); - } - } +function ArrayExpression(node) { + var elems = node.elements; + var len = elems.length; - return this.visitQueue(queue); - }; + this.token("["); + this.printInnerComments(node); - TraversalContext.prototype.visitSingle = function visitSingle(node, key) { - if (this.shouldVisit(node[key])) { - return this.visitQueue([this.create(node, node, key)]); + for (var i = 0; i < elems.length; i++) { + var elem = elems[i]; + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.token(","); } else { - return false; + this.token(","); } - }; + } - TraversalContext.prototype.visitQueue = function visitQueue(queue) { - this.queue = queue; - this.priorityQueue = []; + this.token("]"); +} - var visited = []; - var stop = false; +exports.ArrayPattern = ArrayExpression; +function RegExpLiteral(node) { + this.word("/" + node.pattern + "/" + node.flags); +} - for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +function NullLiteral() { + this.word("null"); +} - var path = _ref2; +function NumericLiteral(node) { + var raw = this.getPossibleRaw(node); + var value = node.value + ""; + if (raw == null) { + this.number(value); + } else if (this.format.minified) { + this.number(raw.length < value.length ? raw : value); + } else { + this.number(raw); + } +} - path.resync(); +function StringLiteral(node, parent) { + var raw = this.getPossibleRaw(node); + if (!this.format.minified && raw != null) { + this.token(raw); + return; + } - if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { - path.pushContext(this); - } + var opts = { + quotes: t.isJSX(parent) ? "double" : this.format.quotes, + wrap: true + }; + if (this.format.jsonCompatibleStrings) { + opts.json = true; + } + var val = (0, _jsesc2.default)(node.value, opts); - if (path.key === null) continue; + return this.token(val); +} +},{"babel-types":183,"jsesc":325}],101:[function(require,module,exports){ +"use strict"; - if (testing && queue.length >= 10000) { - this.trap = true; - } +exports.__esModule = true; +exports.CodeGenerator = undefined; - if (visited.indexOf(path.node) >= 0) continue; - visited.push(path.node); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - if (path.visit()) { - stop = true; - break; - } +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - if (this.priorityQueue.length) { - stop = this.visitQueue(this.priorityQueue); - this.priorityQueue = []; - this.queue = queue; - if (stop) break; - } - } +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +var _inherits2 = require("babel-runtime/helpers/inherits"); - var _path = _ref3; +var _inherits3 = _interopRequireDefault(_inherits2); - _path.popContext(); - } +exports.default = function (ast, opts, code) { + var gen = new Generator(ast, opts, code); + return gen.generate(); +}; - this.queue = null; +var _detectIndent = require("detect-indent"); - return stop; - }; +var _detectIndent2 = _interopRequireDefault(_detectIndent); - TraversalContext.prototype.visit = function visit(node, key) { - var nodes = node[key]; - if (!nodes) return false; +var _sourceMap = require("./source-map"); - if (Array.isArray(nodes)) { - return this.visitMultiple(nodes, node, key); - } else { - return this.visitSingle(node, key); - } - }; +var _sourceMap2 = _interopRequireDefault(_sourceMap); - return TraversalContext; -}(); +var _babelMessages = require("babel-messages"); -exports.default = TraversalContext; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./path":119,"_process":803,"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/classCallCheck":103,"babel-types":145}],111:[function(require,module,exports){ -"use strict"; +var messages = _interopRequireWildcard(_babelMessages); -exports.__esModule = true; +var _printer = require("./printer"); -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var _printer2 = _interopRequireDefault(_printer); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Hub = function Hub(file, options) { - (0, _classCallCheck3.default)(this, Hub); +var Generator = function (_Printer) { + (0, _inherits3.default)(Generator, _Printer); - this.file = file; - this.options = options; -}; + function Generator(ast) { + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var code = arguments[2]; + (0, _classCallCheck3.default)(this, Generator); -exports.default = Hub; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":103}],112:[function(require,module,exports){ -"use strict"; + var tokens = ast.tokens || []; + var format = normalizeOptions(code, opts, tokens); + var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; -exports.__esModule = true; -exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; + var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + _this.ast = ast; + return _this; + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + Generator.prototype.generate = function generate() { + return _Printer.prototype.generate.call(this, this.ast); + }; -var _path = require("./path"); + return Generator; +}(_printer2.default); -Object.defineProperty(exports, "NodePath", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_path).default; +function normalizeOptions(code, opts, tokens) { + var style = " "; + if (code && typeof code === "string") { + var indent = (0, _detectIndent2.default)(code).indent; + if (indent && indent !== " ") style = indent; } -}); - -var _scope = require("./scope"); -Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_scope).default; - } -}); + var format = { + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + shouldPrintComment: opts.shouldPrintComment, + retainLines: opts.retainLines, + retainFunctionParens: opts.retainFunctionParens, + comments: opts.comments == null || opts.comments, + compact: opts.compact, + minified: opts.minified, + concise: opts.concise, + quotes: opts.quotes || findCommonStringDelimiter(code, tokens), + jsonCompatibleStrings: opts.jsonCompatibleStrings, + indent: { + adjustMultilineComment: true, + style: style, + base: 0 + }, + flowCommaSeparator: opts.flowCommaSeparator + }; -var _hub = require("./hub"); + if (format.minified) { + format.compact = true; -Object.defineProperty(exports, "Hub", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_hub).default; + format.shouldPrintComment = format.shouldPrintComment || function () { + return format.comments; + }; + } else { + format.shouldPrintComment = format.shouldPrintComment || function (value) { + return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; + }; } -}); -exports.default = traverse; -var _context = require("./context"); + if (format.compact === "auto") { + format.compact = code.length > 500000; -var _context2 = _interopRequireDefault(_context); + if (format.compact) { + console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "500KB")); + } + } -var _visitors = require("./visitors"); + if (format.compact) { + format.indent.adjustMultilineComment = false; + } -var visitors = _interopRequireWildcard(_visitors); + return format; +} -var _babelMessages = require("babel-messages"); +function findCommonStringDelimiter(code, tokens) { + var DEFAULT_STRING_DELIMITER = "double"; + if (!code) { + return DEFAULT_STRING_DELIMITER; + } -var messages = _interopRequireWildcard(_babelMessages); + var occurrences = { + single: 0, + double: 0 + }; -var _includes = require("lodash/includes"); + var checked = 0; -var _includes2 = _interopRequireDefault(_includes); + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (token.type.label !== "string") continue; -var _babelTypes = require("babel-types"); + var raw = code.slice(token.start, token.end); + if (raw[0] === "'") { + occurrences.single++; + } else { + occurrences.double++; + } -var t = _interopRequireWildcard(_babelTypes); + checked++; + if (checked >= 3) break; + } + if (occurrences.single > occurrences.double) { + return "single"; + } else { + return "double"; + } +} -var _cache = require("./cache"); +var CodeGenerator = exports.CodeGenerator = function () { + function CodeGenerator(ast, opts, code) { + (0, _classCallCheck3.default)(this, CodeGenerator); -var cache = _interopRequireWildcard(_cache); + this._generator = new Generator(ast, opts, code); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + CodeGenerator.prototype.generate = function generate() { + return this._generator.generate(); + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return CodeGenerator; +}(); +},{"./printer":105,"./source-map":106,"babel-messages":115,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144,"detect-indent":312}],102:[function(require,module,exports){ +"use strict"; -exports.visitors = visitors; -function traverse(parent, opts, scope, state, parentPath) { - if (!parent) return; - if (!opts) opts = {}; +exports.__esModule = true; - if (!opts.noScope && !scope) { - if (parent.type !== "Program" && parent.type !== "File") { - throw new Error(messages.get("traverseNeedsParent", parent.type)); - } - } +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - visitors.explode(opts); +var _getIterator3 = _interopRequireDefault(_getIterator2); - traverse.node(parent, opts, scope, state, parentPath); -} +var _keys = require("babel-runtime/core-js/object/keys"); -traverse.visitors = visitors; -traverse.verify = visitors.verify; -traverse.explode = visitors.explode; +var _keys2 = _interopRequireDefault(_keys); -traverse.NodePath = require("./path"); -traverse.Scope = require("./scope"); -traverse.Hub = require("./hub"); +exports.needsWhitespace = needsWhitespace; +exports.needsWhitespaceBefore = needsWhitespaceBefore; +exports.needsWhitespaceAfter = needsWhitespaceAfter; +exports.needsParens = needsParens; -traverse.cheap = function (node, enter) { - return t.traverseFast(node, enter); -}; +var _whitespace = require("./whitespace"); -traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; +var _whitespace2 = _interopRequireDefault(_whitespace); - var context = new _context2.default(scope, opts, state, parentPath); - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { +var _parentheses = require("./parentheses"); + +var parens = _interopRequireWildcard(_parentheses); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function expandAliases(obj) { + var newObj = {}; + + function add(type, func) { + var fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + var result = fn(node, parent, stack); + + return result == null ? func(node, parent, stack) : result; + } : func; + } + + for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { @@ -14491,1608 +17032,1377 @@ traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { _ref = _i.value; } - var key = _ref; + var type = _ref; - if (skipKeys && skipKeys[key]) continue; - if (context.visit(node, key)) return; - } -}; -traverse.clearNode = function (node, opts) { - t.removeProperties(node, opts); + var aliases = t.FLIPPED_ALIAS_KEYS[type]; + if (aliases) { + for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - cache.path.delete(node); -}; + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } -traverse.removeProperties = function (tree, opts) { - t.traverseFast(tree, traverse.clearNode, opts); - return tree; -}; + var alias = _ref2; -function hasBlacklistedType(path, state) { - if (path.node.type === state.type) { - state.has = true; - path.stop(); + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } } + + return newObj; } -traverse.hasType = function (tree, scope, type, blacklistTypes) { - if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; +var expandedParens = expandAliases(parens); +var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); +var expandedWhitespaceList = expandAliases(_whitespace2.default.list); - if (tree.type === type) return true; +function find(obj, node, parent, printStack) { + var fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; +} - var state = { - has: false, - type: type - }; +function isOrHasCallExpression(node) { + if (t.isCallExpression(node)) { + return true; + } - traverse(tree, { - blacklist: blacklistTypes, - enter: hasBlacklistedType - }, scope, state); + if (t.isMemberExpression(node)) { + return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); + } else { + return false; + } +} - return state.has; -}; +function needsWhitespace(node, parent, type) { + if (!node) return 0; -traverse.clearCache = function () { - cache.clear(); -}; + if (t.isExpressionStatement(node)) { + node = node.expression; + } -traverse.clearCache.clearPath = cache.clearPath; -traverse.clearCache.clearScope = cache.clearScope; + var linesInfo = find(expandedWhitespaceNodes, node, parent); -traverse.copyCache = function (source, destination) { - if (cache.path.has(source)) { - cache.path.set(destination, cache.path.get(source)); + if (!linesInfo) { + var items = find(expandedWhitespaceList, node, parent); + if (items) { + for (var i = 0; i < items.length; i++) { + linesInfo = needsWhitespace(items[i], node, type); + if (linesInfo) break; + } + } } -}; -},{"./cache":109,"./context":110,"./hub":111,"./path":119,"./scope":131,"./visitors":133,"babel-messages":79,"babel-runtime/core-js/get-iterator":89,"babel-types":145,"lodash/includes":471}],113:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; + return linesInfo && linesInfo[type] || 0; +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, "before"); +} -var _getIterator3 = _interopRequireDefault(_getIterator2); +function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, "after"); +} -exports.findParent = findParent; -exports.find = find; -exports.getFunctionParent = getFunctionParent; -exports.getStatementParent = getStatementParent; -exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; -exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; -exports.getAncestry = getAncestry; -exports.isAncestor = isAncestor; -exports.isDescendant = isDescendant; -exports.inType = inType; -exports.inShadow = inShadow; +function needsParens(node, parent, printStack) { + if (!parent) return false; -var _babelTypes = require("babel-types"); + if (t.isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; + } -var t = _interopRequireWildcard(_babelTypes); + return find(expandedParens, node, parent, printStack); +} +},{"./parentheses":103,"./whitespace":104,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/object/keys":134,"babel-types":183}],103:[function(require,module,exports){ +"use strict"; -var _index = require("./index"); +exports.__esModule = true; +exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.UpdateExpression = UpdateExpression; +exports.ObjectExpression = ObjectExpression; +exports.DoExpression = DoExpression; +exports.Binary = Binary; +exports.BinaryExpression = BinaryExpression; +exports.SequenceExpression = SequenceExpression; +exports.YieldExpression = YieldExpression; +exports.ClassExpression = ClassExpression; +exports.UnaryLike = UnaryLike; +exports.FunctionExpression = FunctionExpression; +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.AssignmentExpression = AssignmentExpression; -var _index2 = _interopRequireDefault(_index); +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var PRECEDENCE = { + "||": 0, + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "===": 5, + "!=": 5, + "!==": 5, + "<": 6, + ">": 6, + "<=": 6, + ">=": 6, + in: 6, + instanceof: 6, + ">>": 7, + "<<": 7, + ">>>": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, + "**": 10 +}; -function findParent(callback) { - var path = this; - while (path = path.parentPath) { - if (callback(path)) return path; - } - return null; +function NullableTypeAnnotation(node, parent) { + return t.isArrayTypeAnnotation(parent); } -function find(callback) { - var path = this; - do { - if (callback(path)) return path; - } while (path = path.parentPath); - return null; +exports.FunctionTypeAnnotation = NullableTypeAnnotation; +function UpdateExpression(node, parent) { + return t.isMemberExpression(parent) && parent.object === node; } -function getFunctionParent() { - return this.findParent(function (path) { - return path.isFunction() || path.isProgram(); - }); +function ObjectExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { considerArrow: true }); } -function getStatementParent() { - var path = this; - do { - if (Array.isArray(path.container)) { - return path; - } - } while (path = path.parentPath); +function DoExpression(node, parent, printStack) { + return isFirstInStatement(printStack); } -function getEarliestCommonAncestorFrom(paths) { - return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { - var earliest = void 0; - var keys = t.VISITOR_KEYS[deepest.type]; - - for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var ancestry = _ref; - - var path = ancestry[i + 1]; +function Binary(node, parent) { + if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isUnaryLike(parent) || t.isMemberExpression(parent) && parent.object === node || t.isAwaitExpression(parent)) { + return true; + } - if (!earliest) { - earliest = path; - continue; - } + if (t.isBinary(parent)) { + var parentOp = parent.operator; + var parentPos = PRECEDENCE[parentOp]; - if (path.listKey && earliest.listKey === path.listKey) { - if (path.key < earliest.key) { - earliest = path; - continue; - } - } + var nodeOp = node.operator; + var nodePos = PRECEDENCE[nodeOp]; - var earliestKeyIndex = keys.indexOf(earliest.parentKey); - var currentKeyIndex = keys.indexOf(path.parentKey); - if (earliestKeyIndex > currentKeyIndex) { - earliest = path; - } + if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent) || parentPos > nodePos) { + return true; } + } - return earliest; - }); + return false; } -function getDeepestCommonAncestorFrom(paths, filter) { - var _this = this; +function BinaryExpression(node, parent) { + return node.operator === "in" && (t.isVariableDeclarator(parent) || t.isFor(parent)); +} - if (!paths.length) { - return this; - } +function SequenceExpression(node, parent) { - if (paths.length === 1) { - return paths[0]; + if (t.isForStatement(parent) || t.isThrowStatement(parent) || t.isReturnStatement(parent) || t.isIfStatement(parent) && parent.test === node || t.isWhileStatement(parent) && parent.test === node || t.isForInStatement(parent) && parent.right === node || t.isSwitchStatement(parent) && parent.discriminant === node || t.isExpressionStatement(parent) && parent.expression === node) { + return false; } - var minDepth = Infinity; + return true; +} - var lastCommonIndex = void 0, - lastCommon = void 0; +function YieldExpression(node, parent) { + return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) && node === parent.test; +} - var ancestries = paths.map(function (path) { - var ancestry = []; +exports.AwaitExpression = YieldExpression; +function ClassExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { considerDefaultExports: true }); +} - do { - ancestry.unshift(path); - } while ((path = path.parentPath) && path !== _this); +function UnaryLike(node, parent) { + return t.isMemberExpression(parent, { object: node }) || t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node }); +} - if (ancestry.length < minDepth) { - minDepth = ancestry.length; - } +function FunctionExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { considerDefaultExports: true }); +} - return ancestry; - }); +function ArrowFunctionExpression(node, parent) { + if (t.isExportDeclaration(parent) || t.isBinaryExpression(parent) || t.isLogicalExpression(parent) || t.isUnaryExpression(parent) || t.isTaggedTemplateExpression(parent)) { + return true; + } - var first = ancestries[0]; + return UnaryLike(node, parent); +} - depthLoop: for (var i = 0; i < minDepth; i++) { - var shouldMatch = first[i]; +function ConditionalExpression(node, parent) { + if (t.isUnaryLike(parent) || t.isBinary(parent) || t.isConditionalExpression(parent, { test: node }) || t.isAwaitExpression(parent)) { + return true; + } - for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + return UnaryLike(node, parent); +} - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +function AssignmentExpression(node) { + if (t.isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression.apply(undefined, arguments); + } +} - var ancestry = _ref2; +function isFirstInStatement(printStack) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$considerArrow = _ref.considerArrow, + considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow, + _ref$considerDefaultE = _ref.considerDefaultExports, + considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; - if (ancestry[i] !== shouldMatch) { - break depthLoop; - } + var i = printStack.length - 1; + var node = printStack[i]; + i--; + var parent = printStack[i]; + while (i > 0) { + if (t.isExpressionStatement(parent, { expression: node }) || t.isTaggedTemplateExpression(parent) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { + return true; } - lastCommonIndex = i; - lastCommon = shouldMatch; - } - - if (lastCommon) { - if (filter) { - return filter(lastCommon, lastCommonIndex, ancestries); + if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) { + node = parent; + i--; + parent = printStack[i]; } else { - return lastCommon; + return false; } - } else { - throw new Error("Couldn't find intersection"); } -} -function getAncestry() { - var path = this; - var paths = []; - do { - paths.push(path); - } while (path = path.parentPath); - return paths; + return false; } +},{"babel-types":183}],104:[function(require,module,exports){ +"use strict"; -function isAncestor(maybeDescendant) { - return maybeDescendant.isDescendant(this); -} +var _map = require("lodash/map"); -function isDescendant(maybeAncestor) { - return !!this.findParent(function (parent) { - return parent === maybeAncestor; - }); -} +var _map2 = _interopRequireDefault(_map); -function inType() { - var path = this; - while (path) { - for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +var _babelTypes = require("babel-types"); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +var t = _interopRequireWildcard(_babelTypes); - var type = _ref3; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (path.node.type === type) return true; - } - path = path.parentPath; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return false; -} - -function inShadow(key) { - var parentFn = this.isFunction() ? this : this.findParent(function (p) { - return p.isFunction(); - }); - if (!parentFn) return; - - if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { - var shadow = parentFn.node.shadow; +function crawl(node) { + var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (shadow && (!key || shadow[key] !== false)) { - return parentFn; - } - } else if (parentFn.isArrowFunctionExpression()) { - return parentFn; + if (t.isMemberExpression(node)) { + crawl(node.object, state); + if (node.computed) crawl(node.property, state); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + crawl(node.left, state); + crawl(node.right, state); + } else if (t.isCallExpression(node)) { + state.hasCall = true; + crawl(node.callee, state); + } else if (t.isFunction(node)) { + state.hasFunction = true; + } else if (t.isIdentifier(node)) { + state.hasHelper = state.hasHelper || isHelper(node.callee); } - return null; + return state; } -},{"./index":119,"babel-runtime/core-js/get-iterator":89,"babel-types":145}],114:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.shareCommentsWithSiblings = shareCommentsWithSiblings; -exports.addComment = addComment; -exports.addComments = addComments; -function shareCommentsWithSiblings() { - if (typeof this.key === "string") return; - var node = this.node; - if (!node) return; - - var trailing = node.trailingComments; - var leading = node.leadingComments; - if (!trailing && !leading) return; +function isHelper(node) { + if (t.isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (t.isIdentifier(node)) { + return node.name === "require" || node.name[0] === "_"; + } else if (t.isCallExpression(node)) { + return isHelper(node.callee); + } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { + return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); + } else { + return false; + } +} - var prev = this.getSibling(this.key - 1); - var next = this.getSibling(this.key + 1); +function isType(node) { + return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); +} - if (!prev.node) prev = next; - if (!next.node) next = prev; +exports.nodes = { + AssignmentExpression: function AssignmentExpression(node) { + var state = crawl(node.right); + if (state.hasCall && state.hasHelper || state.hasFunction) { + return { + before: state.hasFunction, + after: true + }; + } + }, + SwitchCase: function SwitchCase(node, parent) { + return { + before: node.consequent.length || parent.cases[0] === node + }; + }, + LogicalExpression: function LogicalExpression(node) { + if (t.isFunction(node.left) || t.isFunction(node.right)) { + return { + after: true + }; + } + }, + Literal: function Literal(node) { + if (node.value === "use strict") { + return { + after: true + }; + } + }, + CallExpression: function CallExpression(node) { + if (t.isFunction(node.callee) || isHelper(node)) { + return { + before: true, + after: true + }; + } + }, + VariableDeclaration: function VariableDeclaration(node) { + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; - prev.addComments("trailing", leading); - next.addComments("leading", trailing); -} + var enabled = isHelper(declar.id) && !isType(declar.init); + if (!enabled) { + var state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + } -function addComment(type, content, line) { - this.addComments(type, [{ - type: line ? "CommentLine" : "CommentBlock", - value: content - }]); -} + if (enabled) { + return { + before: true, + after: true + }; + } + } + }, + IfStatement: function IfStatement(node) { + if (t.isBlockStatement(node.consequent)) { + return { + before: true, + after: true + }; + } + } +}; -function addComments(type, comments) { - if (!comments) return; +exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { + if (parent.properties[0] === node) { + return { + before: true + }; + } +}; - var node = this.node; - if (!node) return; +exports.list = { + VariableDeclaration: function VariableDeclaration(node) { + return (0, _map2.default)(node.declarations, "init"); + }, + ArrayExpression: function ArrayExpression(node) { + return node.elements; + }, + ObjectExpression: function ObjectExpression(node) { + return node.properties; + } +}; - var key = type + "Comments"; +[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { + var type = _ref[0], + amounts = _ref[1]; - if (node[key]) { - node[key] = node[key].concat(comments); - } else { - node[key] = comments; + if (typeof amounts === "boolean") { + amounts = { after: amounts, before: amounts }; } -} -},{}],115:[function(require,module,exports){ + [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + exports.nodes[type] = function () { + return amounts; + }; + }); +}); +},{"babel-types":183,"lodash/map":527}],105:[function(require,module,exports){ "use strict"; exports.__esModule = true; +var _assign = require("babel-runtime/core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); -exports.call = call; -exports._call = _call; -exports.isBlacklisted = isBlacklisted; -exports.visit = visit; -exports.skip = skip; -exports.skipKey = skipKey; -exports.stop = stop; -exports.setScope = setScope; -exports.setContext = setContext; -exports.resync = resync; -exports._resyncParent = _resyncParent; -exports._resyncKey = _resyncKey; -exports._resyncList = _resyncList; -exports._resyncRemoved = _resyncRemoved; -exports.popContext = popContext; -exports.pushContext = pushContext; -exports.setup = setup; -exports.setKey = setKey; -exports.requeue = requeue; -exports._getQueueContexts = _getQueueContexts; +var _stringify = require("babel-runtime/core-js/json/stringify"); -var _index = require("../index"); +var _stringify2 = _interopRequireDefault(_stringify); -var _index2 = _interopRequireDefault(_index); +var _weakSet = require("babel-runtime/core-js/weak-set"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _weakSet2 = _interopRequireDefault(_weakSet); -function call(key) { - var opts = this.opts; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - this.debug(function () { - return key; - }); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - if (this.node) { - if (this._call(opts[key])) return true; - } +var _find = require("lodash/find"); - if (this.node) { - return this._call(opts[this.node.type] && opts[this.node.type][key]); - } +var _find2 = _interopRequireDefault(_find); - return false; -} +var _findLast = require("lodash/findLast"); -function _call(fns) { - if (!fns) return false; +var _findLast2 = _interopRequireDefault(_findLast); - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _isInteger = require("lodash/isInteger"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _isInteger2 = _interopRequireDefault(_isInteger); - var fn = _ref; +var _repeat = require("lodash/repeat"); - if (!fn) continue; +var _repeat2 = _interopRequireDefault(_repeat); - var node = this.node; - if (!node) return true; +var _buffer = require("./buffer"); - var ret = fn.call(this.state, this, this.state); - if (ret) throw new Error("Unexpected return value from visitor method " + fn); +var _buffer2 = _interopRequireDefault(_buffer); - if (this.node !== node) return true; +var _node = require("./node"); - if (this.shouldStop || this.shouldSkip || this.removed) return true; - } +var n = _interopRequireWildcard(_node); - return false; -} +var _whitespace = require("./whitespace"); -function isBlacklisted() { - var blacklist = this.opts.blacklist; - return blacklist && blacklist.indexOf(this.node.type) > -1; -} +var _whitespace2 = _interopRequireDefault(_whitespace); -function visit() { - if (!this.node) { - return false; - } +var _babelTypes = require("babel-types"); - if (this.isBlacklisted()) { - return false; - } +var t = _interopRequireWildcard(_babelTypes); - if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { - return false; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (this.call("enter") || this.shouldSkip) { - this.debug(function () { - return "Skip..."; - }); - return this.shouldStop; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - this.debug(function () { - return "Recursing into..."; - }); - _index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); +var SCIENTIFIC_NOTATION = /e/i; +var ZERO_DECIMAL_INTEGER = /\.0+$/; +var NON_DECIMAL_LITERAL = /^0[box]/; - this.call("exit"); +var Printer = function () { + function Printer(format, map, tokens) { + (0, _classCallCheck3.default)(this, Printer); + this.inForStatementInitCounter = 0; + this._printStack = []; + this._indent = 0; + this._insideAux = false; + this._printedCommentStarts = {}; + this._parenPushNewlineState = null; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new _weakSet2.default(); + this._endsWithInteger = false; + this._endsWithWord = false; - return this.shouldStop; -} + this.format = format || {}; + this._buf = new _buffer2.default(map); + this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; + } -function skip() { - this.shouldSkip = true; -} + Printer.prototype.generate = function generate(ast) { + this.print(ast); + this._maybeAddAuxComment(); -function skipKey(key) { - this.skipKeys[key] = true; -} + return this._buf.get(); + }; -function stop() { - this.shouldStop = true; - this.shouldSkip = true; -} + Printer.prototype.indent = function indent() { + if (this.format.compact || this.format.concise) return; -function setScope() { - if (this.opts && this.opts.noScope) return; + this._indent++; + }; - var target = this.context && this.context.scope; + Printer.prototype.dedent = function dedent() { + if (this.format.compact || this.format.concise) return; - if (!target) { - var path = this.parentPath; - while (path && !target) { - if (path.opts && path.opts.noScope) return; + this._indent--; + }; - target = path.scope; - path = path.parentPath; - } - } + Printer.prototype.semicolon = function semicolon() { + var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - this.scope = this.getScope(target); - if (this.scope) this.scope.init(); -} + this._maybeAddAuxComment(); + this._append(";", !force); + }; -function setContext(context) { - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.skipKeys = {}; + Printer.prototype.rightBrace = function rightBrace() { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } + this.token("}"); + }; - if (context) { - this.context = context; - this.state = context.state; - this.opts = context.opts; - } + Printer.prototype.space = function space() { + var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - this.setScope(); + if (this.format.compact) return; - return this; -} + if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { + this._space(); + } + }; -function resync() { - if (this.removed) return; + Printer.prototype.word = function word(str) { + if (this._endsWithWord) this._space(); - this._resyncParent(); - this._resyncList(); - this._resyncKey(); -} + this._maybeAddAuxComment(); + this._append(str); -function _resyncParent() { - if (this.parentPath) { - this.parent = this.parentPath.node; - } -} + this._endsWithWord = true; + }; -function _resyncKey() { - if (!this.container) return; + Printer.prototype.number = function number(str) { + this.word(str); - if (this.node === this.container[this.key]) return; + this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; + }; - if (Array.isArray(this.container)) { - for (var i = 0; i < this.container.length; i++) { - if (this.container[i] === this.node) { - return this.setKey(i); - } - } - } else { - for (var key in this.container) { - if (this.container[key] === this.node) { - return this.setKey(key); - } + Printer.prototype.token = function token(str) { + if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { + this._space(); } - } - this.key = null; -} + this._maybeAddAuxComment(); + this._append(str); + }; -function _resyncList() { - if (!this.parent || !this.inList) return; + Printer.prototype.newline = function newline(i) { + if (this.format.retainLines || this.format.compact) return; - var newContainer = this.parent[this.listKey]; - if (this.container === newContainer) return; + if (this.format.concise) { + this.space(); + return; + } - this.container = newContainer || null; -} + if (this.endsWith("\n\n")) return; -function _resyncRemoved() { - if (this.key == null || !this.container || this.container[this.key] !== this.node) { - this._markRemoved(); - } -} + if (typeof i !== "number") i = 1; -function popContext() { - this.contexts.pop(); - this.setContext(this.contexts[this.contexts.length - 1]); -} + i = Math.min(2, i); + if (this.endsWith("{\n") || this.endsWith(":\n")) i--; + if (i <= 0) return; -function pushContext(context) { - this.contexts.push(context); - this.setContext(context); -} + for (var j = 0; j < i; j++) { + this._newline(); + } + }; -function setup(parentPath, container, listKey, key) { - this.inList = !!listKey; - this.listKey = listKey; - this.parentKey = listKey || key; - this.container = container; + Printer.prototype.endsWith = function endsWith(str) { + return this._buf.endsWith(str); + }; - this.parentPath = parentPath || this.parentPath; - this.setKey(key); -} + Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { + this._buf.removeTrailingNewline(); + }; -function setKey(key) { - this.key = key; - this.node = this.container[this.key]; - this.type = this.node && this.node.type; -} + Printer.prototype.source = function source(prop, loc) { + this._catchUp(prop, loc); -function requeue() { - var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this; + this._buf.source(prop, loc); + }; - if (pathToQueue.removed) return; + Printer.prototype.withSource = function withSource(prop, loc, cb) { + this._catchUp(prop, loc); - var contexts = this.contexts; + this._buf.withSource(prop, loc, cb); + }; - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + Printer.prototype._space = function _space() { + this._append(" ", true); + }; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + Printer.prototype._newline = function _newline() { + this._append("\n", true); + }; - var context = _ref2; + Printer.prototype._append = function _append(str) { + var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - context.maybeQueue(pathToQueue); - } -} + this._maybeAddParen(str); + this._maybeIndent(str); -function _getQueueContexts() { - var path = this; - var contexts = this.contexts; - while (!contexts.length) { - path = path.parentPath; - contexts = path.contexts; - } - return contexts; -} -},{"../index":112,"babel-runtime/core-js/get-iterator":89}],116:[function(require,module,exports){ -"use strict"; + if (queue) this._buf.queue(str);else this._buf.append(str); -exports.__esModule = true; -exports.toComputedKey = toComputedKey; -exports.ensureBlock = ensureBlock; -exports.arrowFunctionToShadowed = arrowFunctionToShadowed; + this._endsWithWord = false; + this._endsWithInteger = false; + }; -var _babelTypes = require("babel-types"); + Printer.prototype._maybeIndent = function _maybeIndent(str) { + if (this._indent && this.endsWith("\n") && str[0] !== "\n") { + this._buf.queue(this._getIndent()); + } + }; -var t = _interopRequireWildcard(_babelTypes); + Printer.prototype._maybeAddParen = function _maybeAddParen(str) { + var parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + this._parenPushNewlineState = null; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var i = void 0; + for (i = 0; i < str.length && str[i] === " "; i++) { + continue; + }if (i === str.length) return; -function toComputedKey() { - var node = this.node; + var cha = str[i]; + if (cha === "\n" || cha === "/") { + this.token("("); + this.indent(); + parenPushNewlineState.printed = true; + } + }; - var key = void 0; - if (this.isMemberExpression()) { - key = node.property; - } else if (this.isProperty() || this.isMethod()) { - key = node.key; - } else { - throw new ReferenceError("todo"); - } + Printer.prototype._catchUp = function _catchUp(prop, loc) { + if (!this.format.retainLines) return; - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } + var pos = loc ? loc[prop] : null; + if (pos && pos.line !== null) { + var count = pos.line - this._buf.getCurrentLine(); - return key; -} + for (var i = 0; i < count; i++) { + this._newline(); + } + } + }; -function ensureBlock() { - return t.ensureBlock(this.node); -} + Printer.prototype._getIndent = function _getIndent() { + return (0, _repeat2.default)(this.format.indent.style, this._indent); + }; -function arrowFunctionToShadowed() { - if (!this.isArrowFunctionExpression()) return; + Printer.prototype.startTerminatorless = function startTerminatorless() { + return this._parenPushNewlineState = { + printed: false + }; + }; - this.ensureBlock(); + Printer.prototype.endTerminatorless = function endTerminatorless(state) { + if (state.printed) { + this.dedent(); + this.newline(); + this.token(")"); + } + }; - var node = this.node; + Printer.prototype.print = function print(node, parent) { + var _this = this; - node.expression = false; - node.type = "FunctionExpression"; - node.shadow = node.shadow || true; -} -},{"babel-types":145}],117:[function(require,module,exports){ -(function (global){ -"use strict"; + if (!node) return; -exports.__esModule = true; + var oldConcise = this.format.concise; + if (node._compact) { + this.format.concise = true; + } -var _typeof2 = require("babel-runtime/helpers/typeof"); + var printMethod = this[node.type]; + if (!printMethod) { + throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); + } -var _typeof3 = _interopRequireDefault(_typeof2); + this._printStack.push(node); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var oldInAux = this._insideAux; + this._insideAux = !node.loc; + this._maybeAddAuxComment(this._insideAux && !oldInAux); -var _getIterator3 = _interopRequireDefault(_getIterator2); + var needsParens = n.needsParens(node, parent, this._printStack); + if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { + needsParens = true; + } + if (needsParens) this.token("("); -var _map = require("babel-runtime/core-js/map"); + this._printLeadingComments(node, parent); -var _map2 = _interopRequireDefault(_map); + var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; + this.withSource("start", loc, function () { + _this[node.type](node, parent); + }); -exports.evaluateTruthy = evaluateTruthy; -exports.evaluate = evaluate; + this._printTrailingComments(node, parent); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (needsParens) this.token(")"); -var VALID_CALLEES = ["String", "Number", "Math"]; -var INVALID_METHODS = ["random"]; + this._printStack.pop(); -function evaluateTruthy() { - var res = this.evaluate(); - if (res.confident) return !!res.value; -} + this.format.concise = oldConcise; + this._insideAux = oldInAux; + }; -function evaluate() { - var confident = true; - var deoptPath = void 0; - var seen = new _map2.default(); + Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + }; - function deopt(path) { - if (!confident) return; - deoptPath = path; - confident = false; - } + Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; - var value = evaluate(this); - if (!confident) value = undefined; - return { - confident: confident, - deopt: deoptPath, - value: value + var comment = this.format.auxiliaryCommentBefore; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } }; - function evaluate(path) { - var node = path.node; + Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + var comment = this.format.auxiliaryCommentAfter; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + }; - if (seen.has(node)) { - var existing = seen.get(node); - if (existing.resolved) { - return existing.value; - } else { - deopt(path); - return; + Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { + var extra = node.extra; + if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } + }; + + Printer.prototype.printJoin = function printJoin(nodes, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!nodes || !nodes.length) return; + + if (opts.indent) this.indent(); + + var newlineOpts = { + addNewlines: opts.addNewlines + }; + + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (!node) continue; + + if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + + this.print(node, parent); + + if (opts.iterator) { + opts.iterator(node, i); } - } else { - var item = { resolved: false }; - seen.set(node, item); - var val = _evaluate(path); - if (confident) { - item.resolved = true; - item.value = val; + if (opts.separator && i < nodes.length - 1) { + opts.separator.call(this); } - return val; + + if (opts.statement) this._printNewline(false, node, parent, newlineOpts); } - } - function _evaluate(path) { - if (!confident) return; + if (opts.indent) this.dedent(); + }; - var node = path.node; + Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { + var indent = !!node.leadingComments; + if (indent) this.indent(); + this.print(node, parent); + if (indent) this.dedent(); + }; + Printer.prototype.printBlock = function printBlock(parent) { + var node = parent.body; - if (path.isSequenceExpression()) { - var exprs = path.get("expressions"); - return evaluate(exprs[exprs.length - 1]); + if (!t.isEmptyStatement(node)) { + this.space(); } - if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { - return node.value; - } + this.print(node, parent); + }; - if (path.isNullLiteral()) { - return null; - } + Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) { + this._printComments(this._getComments(false, node, parent)); + }; - if (path.isTemplateLiteral()) { - var str = ""; + Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { + this._printComments(this._getComments(true, node, parent)); + }; - var i = 0; - var _exprs = path.get("expressions"); + Printer.prototype.printInnerComments = function printInnerComments(node) { + var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (!node.innerComments) return; + if (indent) this.indent(); + this._printComments(node.innerComments); + if (indent) this.dedent(); + }; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + Printer.prototype.printSequence = function printSequence(nodes, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var elem = _ref; + opts.statement = true; + return this.printJoin(nodes, parent, opts); + }; - if (!confident) break; + Printer.prototype.printList = function printList(items, parent) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - str += elem.value.cooked; + if (opts.separator == null) { + opts.separator = commaSeparator; + } - var expr = _exprs[i++]; - if (expr) str += String(evaluate(expr)); - } + return this.printJoin(items, parent, opts); + }; - if (!confident) return; - return str; + Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { + var _this2 = this; + + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; } - if (path.isConditionalExpression()) { - var testResult = evaluate(path.get("test")); - if (!confident) return; - if (testResult) { - return evaluate(path.get("consequent")); + var lines = 0; + + if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { + if (leading) { + var _comments = node.leadingComments; + var _comment = _comments && (0, _find2.default)(_comments, function (comment) { + return !!comment.loc && _this2.format.shouldPrintComment(comment.value); + }); + + lines = this._whitespace.getNewlinesBefore(_comment || node); } else { - return evaluate(path.get("alternate")); + var _comments2 = node.trailingComments; + var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { + return !!comment.loc && _this2.format.shouldPrintComment(comment.value); + }); + + lines = this._whitespace.getNewlinesAfter(_comment2 || node); } - } + } else { + if (!leading) lines++; + if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; - if (path.isExpressionWrapper()) { - return evaluate(path.get("expression")); + var needs = n.needsWhitespaceAfter; + if (leading) needs = n.needsWhitespaceBefore; + if (needs(node, parent)) lines++; + + if (!this._buf.hasContent()) lines = 0; } - if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { - var property = path.get("property"); - var object = path.get("object"); + this.newline(lines); + }; - if (object.isLiteral() && property.isIdentifier()) { - var _value = object.node.value; - var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); - if (type === "number" || type === "string") { - return _value[property.node.name]; - } - } - } + Printer.prototype._getComments = function _getComments(leading, node) { + return node && (leading ? node.leadingComments : node.trailingComments) || []; + }; - if (path.isReferencedIdentifier()) { - var binding = path.scope.getBinding(node.name); + Printer.prototype._printComment = function _printComment(comment) { + var _this3 = this; - if (binding && binding.constantViolations.length > 0) { - return deopt(binding.path); - } + if (!this.format.shouldPrintComment(comment.value)) return; - if (binding && path.node.start < binding.path.node.end) { - return deopt(binding.path); - } + if (comment.ignore) return; - if (binding && binding.hasValue) { - return binding.value; - } else { - if (node.name === "undefined") { - return binding ? deopt(binding.path) : undefined; - } else if (node.name === "Infinity") { - return binding ? deopt(binding.path) : Infinity; - } else if (node.name === "NaN") { - return binding ? deopt(binding.path) : NaN; - } + if (this._printedComments.has(comment)) return; + this._printedComments.add(comment); - var resolved = path.resolve(); - if (resolved === path) { - return deopt(path); - } else { - return evaluate(resolved); - } - } + if (comment.start != null) { + if (this._printedCommentStarts[comment.start]) return; + this._printedCommentStarts[comment.start] = true; } - if (path.isUnaryExpression({ prefix: true })) { - if (node.operator === "void") { - return undefined; - } + this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); - var argument = path.get("argument"); - if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { - return "function"; - } + if (!this.endsWith("[") && !this.endsWith("{")) this.space(); - var arg = evaluate(argument); - if (!confident) return; - switch (node.operator) { - case "!": - return !arg; - case "+": - return +arg; - case "-": - return -arg; - case "~": - return ~arg; - case "typeof": - return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); + var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; + + if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { + var offset = comment.loc && comment.loc.start.column; + if (offset) { + var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + val = val.replace(newlineRegex, "\n"); } + + var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); + val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); } - if (path.isArrayExpression()) { - var arr = []; - var elems = path.get("elements"); - for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + this.withSource("start", comment.loc, function () { + _this3._append(val); + }); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); + }; - var _elem = _ref2; + Printer.prototype._printComments = function _printComments(comments) { + if (!comments || !comments.length) return; - _elem = _elem.evaluate(); + for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (_elem.confident) { - arr.push(_elem.value); - } else { - return deopt(_elem); - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } - return arr; - } - if (path.isObjectExpression()) { - var obj = {}; - var props = path.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + var _comment3 = _ref; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + this._printComment(_comment3); + } + }; - var prop = _ref3; + return Printer; +}(); - if (prop.isObjectMethod() || prop.isSpreadProperty()) { - return deopt(prop); - } - var keyPath = prop.get("key"); - var key = keyPath; - if (prop.node.computed) { - key = key.evaluate(); - if (!key.confident) { - return deopt(keyPath); - } - key = key.value; - } else if (key.isIdentifier()) { - key = key.node.name; - } else { - key = key.node.value; - } - var valuePath = prop.get("value"); - var _value2 = valuePath.evaluate(); - if (!_value2.confident) { - return deopt(valuePath); - } - _value2 = _value2.value; - obj[key] = _value2; - } - return obj; - } +exports.default = Printer; - if (path.isLogicalExpression()) { - var wasConfident = confident; - var left = evaluate(path.get("left")); - var leftConfident = confident; - confident = wasConfident; - var right = evaluate(path.get("right")); - var rightConfident = confident; - confident = leftConfident && rightConfident; - - switch (node.operator) { - case "||": - if (left && leftConfident) { - confident = true; - return left; - } - - if (!confident) return; - - return left || right; - case "&&": - if (!left && leftConfident || !right && rightConfident) { - confident = true; - } - - if (!confident) return; - - return left && right; - } - } - - if (path.isBinaryExpression()) { - var _left = evaluate(path.get("left")); - if (!confident) return; - var _right = evaluate(path.get("right")); - if (!confident) return; - - switch (node.operator) { - case "-": - return _left - _right; - case "+": - return _left + _right; - case "/": - return _left / _right; - case "*": - return _left * _right; - case "%": - return _left % _right; - case "**": - return Math.pow(_left, _right); - case "<": - return _left < _right; - case ">": - return _left > _right; - case "<=": - return _left <= _right; - case ">=": - return _left >= _right; - case "==": - return _left == _right; - case "!=": - return _left != _right; - case "===": - return _left === _right; - case "!==": - return _left !== _right; - case "|": - return _left | _right; - case "&": - return _left & _right; - case "^": - return _left ^ _right; - case "<<": - return _left << _right; - case ">>": - return _left >> _right; - case ">>>": - return _left >>> _right; - } - } - - if (path.isCallExpression()) { - var callee = path.get("callee"); - var context = void 0; - var func = void 0; - - if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { - func = global[node.callee.name]; - } - - if (callee.isMemberExpression()) { - var _object = callee.get("object"); - var _property = callee.get("property"); - - if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { - context = global[_object.node.name]; - func = context[_property.node.name]; - } - - if (_object.isLiteral() && _property.isIdentifier()) { - var _type = (0, _typeof3.default)(_object.node.value); - if (_type === "string" || _type === "number") { - context = _object.node.value; - func = context[_property.node.name]; - } - } - } - - if (func) { - var args = path.get("arguments").map(evaluate); - if (!confident) return; - return func.apply(context, args); - } - } +function commaSeparator() { + this.token(","); + this.space(); +} - deopt(path); - } +var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; +for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var generator = _arr[_i2]; + (0, _assign2.default)(Printer.prototype, generator); } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/map":91,"babel-runtime/helpers/typeof":107}],118:[function(require,module,exports){ +module.exports = exports["default"]; +},{"./buffer":90,"./generators/base":91,"./generators/classes":92,"./generators/expressions":93,"./generators/flow":94,"./generators/jsx":95,"./generators/methods":96,"./generators/modules":97,"./generators/statements":98,"./generators/template-literals":99,"./generators/types":100,"./node":102,"./whitespace":107,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/json/stringify":128,"babel-runtime/core-js/object/assign":131,"babel-runtime/core-js/weak-set":140,"babel-runtime/helpers/classCallCheck":141,"babel-types":183,"lodash/find":501,"lodash/findLast":503,"lodash/isInteger":516,"lodash/repeat":532}],106:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _keys = require("babel-runtime/core-js/object/keys"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _keys2 = _interopRequireDefault(_keys); -exports.getStatementParent = getStatementParent; -exports.getOpposite = getOpposite; -exports.getCompletionRecords = getCompletionRecords; -exports.getSibling = getSibling; -exports.getPrevSibling = getPrevSibling; -exports.getNextSibling = getNextSibling; -exports.getAllNextSiblings = getAllNextSiblings; -exports.getAllPrevSiblings = getAllPrevSiblings; -exports.get = get; -exports._getKey = _getKey; -exports._getPattern = _getPattern; -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; -exports.getBindingIdentifierPaths = getBindingIdentifierPaths; -exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; +var _typeof2 = require("babel-runtime/helpers/typeof"); -var _index = require("./index"); +var _typeof3 = _interopRequireDefault(_typeof2); -var _index2 = _interopRequireDefault(_index); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _babelTypes = require("babel-types"); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -var t = _interopRequireWildcard(_babelTypes); +var _sourceMap = require("source-map"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _sourceMap2 = _interopRequireDefault(_sourceMap); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function getStatementParent() { - var path = this; - - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { - break; - } else { - path = path.parentPath; - } - } while (path); +var SourceMap = function () { + function SourceMap(opts, code) { + (0, _classCallCheck3.default)(this, SourceMap); - if (path && (path.isProgram() || path.isFile())) { - throw new Error("File/Program node, we can't possibly find a statement parent to this"); + this._cachedMap = null; + this._code = code; + this._opts = opts; + this._rawMappings = []; } - return path; -} + SourceMap.prototype.get = function get() { + if (!this._cachedMap) { + var map = this._cachedMap = new _sourceMap2.default.SourceMapGenerator({ + file: this._opts.sourceMapTarget, + sourceRoot: this._opts.sourceRoot + }); -function getOpposite() { - if (this.key === "left") { - return this.getSibling("right"); - } else if (this.key === "right") { - return this.getSibling("left"); - } -} + var code = this._code; + if (typeof code === "string") { + map.setSourceContent(this._opts.sourceFileName, code); + } else if ((typeof code === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { + (0, _keys2.default)(code).forEach(function (sourceFileName) { + map.setSourceContent(sourceFileName, code[sourceFileName]); + }); + } -function getCompletionRecords() { - var paths = []; + this._rawMappings.forEach(map.addMapping, map); + } - var add = function add(path) { - if (path) paths = paths.concat(path.getCompletionRecords()); + return this._cachedMap.toJSON(); }; - if (this.isIfStatement()) { - add(this.get("consequent")); - add(this.get("alternate")); - } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { - add(this.get("body")); - } else if (this.isProgram() || this.isBlockStatement()) { - add(this.get("body").pop()); - } else if (this.isFunction()) { - return this.get("body").getCompletionRecords(); - } else if (this.isTryStatement()) { - add(this.get("block")); - add(this.get("handler")); - add(this.get("finalizer")); - } else { - paths.push(this); - } + SourceMap.prototype.getRawMappings = function getRawMappings() { + return this._rawMappings.slice(); + }; - return paths; -} + SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { + if (this._lastGenLine !== generatedLine && line === null) return; -function getSibling(key) { - return _index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: key - }); -} + if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { + return; + } -function getPrevSibling() { - return this.getSibling(this.key - 1); -} + this._cachedMap = null; + this._lastGenLine = generatedLine; + this._lastSourceLine = line; + this._lastSourceColumn = column; -function getNextSibling() { - return this.getSibling(this.key + 1); -} + this._rawMappings.push({ + name: identifierName || undefined, + generated: { + line: generatedLine, + column: generatedColumn + }, + source: line == null ? undefined : filename || this._opts.sourceFileName, + original: line == null ? undefined : { + line: line, + column: column + } + }); + }; -function getAllNextSiblings() { - var _key = this.key; - var sibling = this.getSibling(++_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(++_key); - } - return siblings; -} + return SourceMap; +}(); -function getAllPrevSiblings() { - var _key = this.key; - var sibling = this.getSibling(--_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(--_key); - } - return siblings; -} +exports.default = SourceMap; +module.exports = exports["default"]; +},{"babel-runtime/core-js/object/keys":134,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/typeof":145,"source-map":572}],107:[function(require,module,exports){ +"use strict"; -function get(key, context) { - if (context === true) context = this.context; - var parts = key.split("."); - if (parts.length === 1) { - return this._getKey(key, context); - } else { - return this._getPattern(parts, context); - } -} +exports.__esModule = true; -function _getKey(key, context) { - var _this = this; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - var node = this.node; - var container = node[key]; +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - if (Array.isArray(container)) { - return container.map(function (_, i) { - return _index2.default.get({ - listKey: key, - parentPath: _this, - parent: node, - container: container, - key: i - }).setContext(context); - }); - } else { - return _index2.default.get({ - parentPath: this, - parent: node, - container: node, - key: key - }).setContext(context); - } -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _getPattern(parts, context) { - var path = this; - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var Whitespace = function () { + function Whitespace(tokens) { + (0, _classCallCheck3.default)(this, Whitespace); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.tokens = tokens; + this.used = {}; + } - var part = _ref; + Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { + var startToken = void 0; + var endToken = void 0; + var tokens = this.tokens; - if (part === ".") { - path = path.parentPath; - } else { - if (Array.isArray(path)) { - path = path[part]; - } else { - path = path.get(part, context); - } + var index = this._findToken(function (token) { + return token.start - node.start; + }, 0, tokens.length); + if (index >= 0) { + while (index && node.start === tokens[index - 1].start) { + --index; + }startToken = tokens[index - 1]; + endToken = tokens[index]; } - } - return path; -} - -function getBindingIdentifiers(duplicates) { - return t.getBindingIdentifiers(this.node, duplicates); -} -function getOuterBindingIdentifiers(duplicates) { - return t.getOuterBindingIdentifiers(this.node, duplicates); -} + return this._getNewlinesBetween(startToken, endToken); + }; -function getBindingIdentifierPaths() { - var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { + var startToken = void 0; + var endToken = void 0; + var tokens = this.tokens; - var path = this; - var search = [].concat(path); - var ids = (0, _create2.default)(null); + var index = this._findToken(function (token) { + return token.end - node.end; + }, 0, tokens.length); + if (index >= 0) { + while (index && node.end === tokens[index - 1].end) { + --index; + }startToken = tokens[index]; + endToken = tokens[index + 1]; + if (endToken.type.label === ",") endToken = tokens[index + 2]; + } - while (search.length) { - var id = search.shift(); - if (!id) continue; - if (!id.node) continue; + if (endToken && endToken.type.label === "eof") { + return 1; + } else { + return this._getNewlinesBetween(startToken, endToken); + } + }; - var keys = t.getBindingIdentifiers.keys[id.node.type]; + Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) { + if (!endToken || !endToken.loc) return 0; - if (id.isIdentifier()) { - if (duplicates) { - var _ids = ids[id.node.name] = ids[id.node.name] || []; - _ids.push(id); - } else { - ids[id.node.name] = id; - } - continue; - } + var start = startToken ? startToken.loc.end.line : 1; + var end = endToken.loc.start.line; + var lines = 0; - if (id.isExportDeclaration()) { - var declaration = id.get("declaration"); - if (declaration.isDeclaration()) { - search.push(declaration); + for (var line = start; line < end; line++) { + if (typeof this.used[line] === "undefined") { + this.used[line] = true; + lines++; } - continue; } - if (outerOnly) { - if (id.isFunctionDeclaration()) { - search.push(id.get("id")); - continue; - } - if (id.isFunctionExpression()) { - continue; - } - } + return lines; + }; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = id.get(key); - if (Array.isArray(child) || child.node) { - search = search.concat(child); - } - } + Whitespace.prototype._findToken = function _findToken(test, start, end) { + if (start >= end) return -1; + var middle = start + end >>> 1; + var match = test(this.tokens[middle]); + if (match < 0) { + return this._findToken(test, middle + 1, end); + } else if (match > 0) { + return this._findToken(test, start, middle); + } else if (match === 0) { + return middle; } - } + return -1; + }; - return ids; -} + return Whitespace; +}(); -function getOuterBindingIdentifierPaths(duplicates) { - return this.getBindingIdentifierPaths(duplicates, true); -} -},{"./index":119,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/object/create":94,"babel-types":145}],119:[function(require,module,exports){ +exports.default = Whitespace; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":141}],108:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _virtualTypes = require("./lib/virtual-types"); - -var virtualTypes = _interopRequireWildcard(_virtualTypes); - -var _debug2 = require("debug"); - -var _debug3 = _interopRequireDefault(_debug2); - -var _invariant = require("invariant"); - -var _invariant2 = _interopRequireDefault(_invariant); +var _keys = require("babel-runtime/core-js/object/keys"); -var _index = require("../index"); +var _keys2 = _interopRequireDefault(_keys); -var _index2 = _interopRequireDefault(_index); +exports.push = push; +exports.hasComputed = hasComputed; +exports.toComputedObjectFromClass = toComputedObjectFromClass; +exports.toClassObject = toClassObject; +exports.toDefineObject = toDefineObject; -var _assign = require("lodash/assign"); +var _babelHelperFunctionName = require("babel-helper-function-name"); -var _assign2 = _interopRequireDefault(_assign); +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); -var _scope = require("../scope"); +var _has = require("lodash/has"); -var _scope2 = _interopRequireDefault(_scope); +var _has2 = _interopRequireDefault(_has); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); -var _cache = require("../cache"); - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _debug = (0, _debug3.default)("babel"); - -var NodePath = function () { - function NodePath(hub, parent) { - (0, _classCallCheck3.default)(this, NodePath); - - this.parent = parent; - this.hub = hub; - this.contexts = []; - this.data = {}; - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.state = null; - this.opts = null; - this.skipKeys = null; - this.parentPath = null; - this.context = null; - this.container = null; - this.listKey = null; - this.inList = false; - this.parentKey = null; - this.key = null; - this.node = null; - this.scope = null; - this.type = null; - this.typeAnnotation = null; +function toKind(node) { + if (t.isClassMethod(node) || t.isObjectMethod(node)) { + if (node.kind === "get" || node.kind === "set") { + return node.kind; + } } - NodePath.get = function get(_ref) { - var hub = _ref.hub, - parentPath = _ref.parentPath, - parent = _ref.parent, - container = _ref.container, - listKey = _ref.listKey, - key = _ref.key; - - if (!hub && parentPath) { - hub = parentPath.hub; - } + return "value"; +} - (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); +function push(mutatorMap, node, kind, file, scope) { + var alias = t.toKeyAlias(node); - var targetNode = container[key]; + var map = {}; + if ((0, _has2.default)(mutatorMap, alias)) map = mutatorMap[alias]; + mutatorMap[alias] = map; - var paths = _cache.path.get(parent) || []; - if (!_cache.path.has(parent)) { - _cache.path.set(parent, paths); - } + map._inherits = map._inherits || []; + map._inherits.push(node); - var path = void 0; + map._key = node.key; - for (var i = 0; i < paths.length; i++) { - var pathCheck = paths[i]; - if (pathCheck.node === targetNode) { - path = pathCheck; - break; - } - } + if (node.computed) { + map._computed = true; + } - if (!path) { - path = new NodePath(hub, parent); - paths.push(path); - } + if (node.decorators) { + var decorators = map.decorators = map.decorators || t.arrayExpression([]); + decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) { + return dec.expression; + }).reverse()); + } - path.setup(parentPath, container, listKey, key); + if (map.value || map.initializer) { + throw file.buildCodeFrameError(node, "Key conflict with sibling node"); + } - return path; - }; + var key = void 0, + value = void 0; - NodePath.prototype.getScope = function getScope(scope) { - var ourScope = scope; + if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { + key = t.toComputedKey(node, node.key); + } - if (this.isScope()) { - ourScope = new _scope2.default(this, scope); - } + if (t.isObjectProperty(node) || t.isClassProperty(node)) { + value = node.value; + } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { + value = t.functionExpression(null, node.params, node.body, node.generator, node.async); + value.returnType = node.returnType; + } - return ourScope; - }; + var inheritedKind = toKind(node); + if (!kind || inheritedKind !== "value") { + kind = inheritedKind; + } - NodePath.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; + if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { + value = (0, _babelHelperFunctionName2.default)({ id: key, node: value, scope: scope }); + } - NodePath.prototype.getData = function getData(key, def) { - var val = this.data[key]; - if (!val && def) val = this.data[key] = def; - return val; - }; + if (value) { + t.inheritsComments(value, node); + map[kind] = value; + } - NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { - var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; + return map; +} - return this.hub.file.buildCodeFrameError(this.node, msg, Error); - }; +function hasComputed(mutatorMap) { + for (var key in mutatorMap) { + if (mutatorMap[key]._computed) { + return true; + } + } + return false; +} - NodePath.prototype.traverse = function traverse(visitor, state) { - (0, _index2.default)(this.node, visitor, this.scope, state, this); - }; +function toComputedObjectFromClass(obj) { + var objExpr = t.arrayExpression([]); - NodePath.prototype.mark = function mark(type, message) { - this.hub.file.metadata.marked.push({ - type: type, - message: message, - loc: this.node.loc - }); - }; + for (var i = 0; i < obj.properties.length; i++) { + var prop = obj.properties[i]; + var val = prop.value; + val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); + objExpr.elements.push(val); + } - NodePath.prototype.set = function set(key, node) { - t.validate(this.node, key, node); - this.node[key] = node; - }; + return objExpr; +} - NodePath.prototype.getPathLocation = function getPathLocation() { - var parts = []; - var path = this; - do { - var key = path.key; - if (path.inList) key = path.listKey + "[" + key + "]"; - parts.unshift(key); - } while (path = path.parentPath); - return parts.join("."); - }; +function toClassObject(mutatorMap) { + var objExpr = t.objectExpression([]); - NodePath.prototype.debug = function debug(buildMessage) { - if (!_debug.enabled) return; - _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); - }; + (0, _keys2.default)(mutatorMap).forEach(function (mutatorMapKey) { + var map = mutatorMap[mutatorMapKey]; + var mapNode = t.objectExpression([]); - return NodePath; -}(); + var propNode = t.objectProperty(map._key, mapNode, map._computed); -exports.default = NodePath; + (0, _keys2.default)(map).forEach(function (key) { + var node = map[key]; + if (key[0] === "_") return; + var inheritNode = node; + if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; -(0, _assign2.default)(NodePath.prototype, require("./ancestry")); -(0, _assign2.default)(NodePath.prototype, require("./inference")); -(0, _assign2.default)(NodePath.prototype, require("./replacement")); -(0, _assign2.default)(NodePath.prototype, require("./evaluation")); -(0, _assign2.default)(NodePath.prototype, require("./conversion")); -(0, _assign2.default)(NodePath.prototype, require("./introspection")); -(0, _assign2.default)(NodePath.prototype, require("./context")); -(0, _assign2.default)(NodePath.prototype, require("./removal")); -(0, _assign2.default)(NodePath.prototype, require("./modification")); -(0, _assign2.default)(NodePath.prototype, require("./family")); -(0, _assign2.default)(NodePath.prototype, require("./comments")); + var prop = t.objectProperty(t.identifier(key), node); + t.inheritsComments(prop, inheritNode); + t.removeComments(inheritNode); -var _loop2 = function _loop2() { - if (_isArray) { - if (_i >= _iterator.length) return "break"; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) return "break"; - _ref2 = _i.value; - } + mapNode.properties.push(prop); + }); - var type = _ref2; + objExpr.properties.push(propNode); + }); - var typeKey = "is" + type; - NodePath.prototype[typeKey] = function (opts) { - return t[typeKey](this.node, opts); - }; + return objExpr; +} - NodePath.prototype["assert" + type] = function (opts) { - if (!this[typeKey](opts)) { - throw new TypeError("Expected node path of type " + type); - } - }; -}; +function toDefineObject(mutatorMap) { + (0, _keys2.default)(mutatorMap).forEach(function (key) { + var map = mutatorMap[key]; + if (map.value) map.writable = t.booleanLiteral(true); + map.configurable = t.booleanLiteral(true); + map.enumerable = t.booleanLiteral(true); + }); -for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; + return toClassObject(mutatorMap); +} +},{"babel-helper-function-name":109,"babel-runtime/core-js/object/keys":134,"babel-types":183,"lodash/has":506}],109:[function(require,module,exports){ +"use strict"; - var _ret2 = _loop2(); +exports.__esModule = true; - if (_ret2 === "break") break; -} +exports.default = function (_ref) { + var node = _ref.node, + parent = _ref.parent, + scope = _ref.scope, + id = _ref.id; -var _loop = function _loop(type) { - if (type[0] === "_") return "continue"; - if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); + if (node.id) return; - var virtualType = virtualTypes[type]; + if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t.isLiteral(parent.key))) { + id = parent.key; + } else if (t.isVariableDeclarator(parent)) { + id = parent.id; - NodePath.prototype["is" + type] = function (opts) { - return virtualType.checkPath(this, opts); - }; -}; + if (t.isIdentifier(id)) { + var binding = scope.parent.getBinding(id.name); + if (binding && binding.constant && scope.getBinding(id.name) === binding) { + node.id = id; + node.id[t.NOT_LOCAL_BINDING] = true; + return; + } + } + } else if (t.isAssignmentExpression(parent)) { + id = parent.left; + } else if (!id) { + return; + } -for (var type in virtualTypes) { - var _ret = _loop(type); + var name = void 0; + if (id && t.isLiteral(id)) { + name = id.value; + } else if (id && t.isIdentifier(id)) { + name = id.name; + } else { + return; + } - if (_ret === "continue") continue; -} -module.exports = exports["default"]; -},{"../cache":109,"../index":112,"../scope":131,"./ancestry":113,"./comments":114,"./context":115,"./conversion":116,"./evaluation":117,"./family":118,"./inference":120,"./introspection":123,"./lib/virtual-types":126,"./modification":127,"./removal":128,"./replacement":129,"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/classCallCheck":103,"babel-types":145,"debug":271,"invariant":284,"lodash/assign":452}],120:[function(require,module,exports){ -"use strict"; + name = t.toBindingIdentifierName(name); + id = t.identifier(name); -exports.__esModule = true; + id[t.NOT_LOCAL_BINDING] = true; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var state = visit(node, name, scope); + return wrap(state, node, id, scope) || node; +}; -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); -exports.getTypeAnnotation = getTypeAnnotation; -exports._getTypeAnnotation = _getTypeAnnotation; -exports.isBaseType = isBaseType; -exports.couldBeBaseType = couldBeBaseType; -exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; -exports.isGenericType = isGenericType; +var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); -var _inferers = require("./inferers"); +var _babelTemplate = require("babel-template"); -var inferers = _interopRequireWildcard(_inferers); +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); var _babelTypes = require("babel-types"); @@ -16102,148 +18412,137 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function getTypeAnnotation() { - if (this.typeAnnotation) return this.typeAnnotation; +var buildPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); - var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); - if (t.isTypeAnnotation(type)) type = type.typeAnnotation; - return this.typeAnnotation = type; -} +var buildGeneratorPropertyMethodAssignmentWrapper = (0, _babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); -function _getTypeAnnotation() { - var node = this.node; +var visitor = { + "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { + if (path.node.name !== state.name) return; - if (!node) { - if (this.key === "init" && this.parentPath.isVariableDeclarator()) { - var declar = this.parentPath.parentPath; - var declarParent = declar.parentPath; + var localDeclar = path.scope.getBindingIdentifier(state.name); + if (localDeclar !== state.outerDeclar) return; - if (declar.key === "left" && declarParent.isForInStatement()) { - return t.stringTypeAnnotation(); - } + state.selfReference = true; + path.stop(); + } +}; - if (declar.key === "left" && declarParent.isForOfStatement()) { - return t.anyTypeAnnotation(); +function wrap(state, method, id, scope) { + if (state.selfReference) { + if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { + scope.rename(id.name); + } else { + if (!t.isFunction(method)) return; + + var build = buildPropertyMethodAssignmentWrapper; + if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; + var _template = build({ + FUNCTION: method, + FUNCTION_ID: id, + FUNCTION_KEY: scope.generateUidIdentifier(id.name) + }).expression; + _template.callee._skipModulesRemap = true; + + var params = _template.callee.body.body[0].params; + for (var i = 0, len = (0, _babelHelperGetFunctionArity2.default)(method); i < len; i++) { + params.push(scope.generateUidIdentifier("x")); } - return t.voidTypeAnnotation(); - } else { - return; + return _template; } } - if (node.typeAnnotation) { - return node.typeAnnotation; - } + method.id = id; + scope.getProgramParent().references[id.name] = true; +} - var inferer = inferers[node.type]; - if (inferer) { - return inferer.call(this, node); - } +function visit(node, name, scope) { + var state = { + selfAssignment: false, + selfReference: false, + outerDeclar: scope.getBindingIdentifier(name), + references: [], + name: name + }; - inferer = inferers[this.parentPath.type]; - if (inferer && inferer.validParent) { - return this.parentPath.getTypeAnnotation(); + var binding = scope.getOwnBinding(name); + + if (binding) { + if (binding.kind === "param") { + state.selfReference = true; + } else {} + } else if (state.outerDeclar || scope.hasGlobal(name)) { + scope.traverse(node, visitor, state); } -} -function isBaseType(baseName, soft) { - return _isBaseType(baseName, this.getTypeAnnotation(), soft); + return state; } -function _isBaseType(baseName, type, soft) { - if (baseName === "string") { - return t.isStringTypeAnnotation(type); - } else if (baseName === "number") { - return t.isNumberTypeAnnotation(type); - } else if (baseName === "boolean") { - return t.isBooleanTypeAnnotation(type); - } else if (baseName === "any") { - return t.isAnyTypeAnnotation(type); - } else if (baseName === "mixed") { - return t.isMixedTypeAnnotation(type); - } else if (baseName === "empty") { - return t.isEmptyTypeAnnotation(type); - } else if (baseName === "void") { - return t.isVoidTypeAnnotation(type); - } else { - if (soft) { - return false; - } else { - throw new Error("Unknown base type " + baseName); +module.exports = exports["default"]; +},{"babel-helper-get-function-arity":110,"babel-template":146,"babel-types":183}],110:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (node) { + var params = node.params; + for (var i = 0; i < params.length; i++) { + var param = params[i]; + if (t.isAssignmentPattern(param) || t.isRestElement(param)) { + return i; } } -} + return params.length; +}; -function couldBeBaseType(name) { - var type = this.getTypeAnnotation(); - if (t.isAnyTypeAnnotation(type)) return true; +var _babelTypes = require("babel-types"); - if (t.isUnionTypeAnnotation(type)) { - for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var t = _interopRequireWildcard(_babelTypes); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var type2 = _ref; +module.exports = exports["default"]; +},{"babel-types":183}],111:[function(require,module,exports){ +"use strict"; - if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { - return true; - } - } - return false; +exports.__esModule = true; + +exports.default = function (callee, thisNode, args) { + if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { + return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); } else { - return _isBaseType(name, type, true); + return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode].concat(args)); } -} +}; -function baseTypeStrictlyMatches(right) { - var left = this.getTypeAnnotation(); - right = right.getTypeAnnotation(); +var _babelTypes = require("babel-types"); - if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { - return right.type === left.type; - } -} +var t = _interopRequireWildcard(_babelTypes); -function isGenericType(genericName) { - var type = this.getTypeAnnotation(); - return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); -} -},{"./inferers":122,"babel-runtime/core-js/get-iterator":89,"babel-types":145}],121:[function(require,module,exports){ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +module.exports = exports["default"]; +},{"babel-types":183}],112:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -exports.default = function (node) { - if (!this.isReferenced()) return; +var _symbol = require("babel-runtime/core-js/symbol"); - var binding = this.scope.getBinding(node.name); - if (binding) { - if (binding.identifier.typeAnnotation) { - return binding.identifier.typeAnnotation; - } else { - return getTypeAnnotationBindingConstantViolations(this, node.name); - } - } +var _symbol2 = _interopRequireDefault(_symbol); - if (node.name === "undefined") { - return t.voidTypeAnnotation(); - } else if (node.name === "NaN" || node.name === "Infinity") { - return t.numberTypeAnnotation(); - } else if (node.name === "arguments") {} -}; +var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + +var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); var _babelTypes = require("babel-types"); @@ -16253,1161 +18552,1118 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function getTypeAnnotationBindingConstantViolations(path, name) { - var binding = path.scope.getBinding(name); +var HARDCORE_THIS_REF = (0, _symbol2.default)(); - var types = []; - path.typeAnnotation = t.unionTypeAnnotation(types); +function isIllegalBareSuper(node, parent) { + if (!t.isSuper(node)) return false; + if (t.isMemberExpression(parent, { computed: false })) return false; + if (t.isCallExpression(parent, { callee: node })) return false; + return true; +} - var functionConstantViolations = []; - var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); +function isMemberExpressionSuper(node) { + return t.isMemberExpression(node) && t.isSuper(node.object); +} - var testType = getConditionalAnnotation(path, name); - if (testType) { - var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); +function getPrototypeOfExpression(objectRef, isStatic) { + var targetRef = isStatic ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); - constantViolations = constantViolations.filter(function (path) { - return testConstantViolations.indexOf(path) < 0; - }); + return t.logicalExpression("||", t.memberExpression(targetRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [targetRef])); +} - types.push(testType.typeAnnotation); - } +var visitor = { + Function: function Function(path) { + if (!path.inShadow("this")) { + path.skip(); + } + }, + ReturnStatement: function ReturnStatement(path, state) { + if (!path.inShadow("this")) { + state.returns.push(path); + } + }, + ThisExpression: function ThisExpression(path, state) { + if (!path.node[HARDCORE_THIS_REF]) { + state.thises.push(path); + } + }, + enter: function enter(path, state) { + var callback = state.specHandle; + if (state.isLoose) callback = state.looseHandle; - if (constantViolations.length) { - constantViolations = constantViolations.concat(functionConstantViolations); + var isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); - for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var result = callback.call(state, path); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + if (result) { + state.hasSuper = true; + } - var violation = _ref; + if (isBareSuper) { + state.bareSupers.push(path); + } - types.push(violation.getTypeAnnotation()); + if (result === true) { + path.requeue(); + } + + if (result !== true && result) { + if (Array.isArray(result)) { + path.replaceWithMultiple(result); + } else { + path.replaceWith(result); + } } } +}; - if (types.length) { - return t.createUnionTypeAnnotation(types); +var ReplaceSupers = function () { + function ReplaceSupers(opts) { + var inClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + (0, _classCallCheck3.default)(this, ReplaceSupers); + + this.forceSuperMemoisation = opts.forceSuperMemoisation; + this.methodPath = opts.methodPath; + this.methodNode = opts.methodNode; + this.superRef = opts.superRef; + this.isStatic = opts.isStatic; + this.hasSuper = false; + this.inClass = inClass; + this.isLoose = opts.isLoose; + this.scope = this.methodPath.scope; + this.file = opts.file; + this.opts = opts; + + this.bareSupers = []; + this.returns = []; + this.thises = []; } -} -function getConstantViolationsBefore(binding, path, functions) { - var violations = binding.constantViolations.slice(); - violations.unshift(binding.path); - return violations.filter(function (violation) { - violation = violation.resolve(); - var status = violation._guessExecutionStatusRelativeTo(path); - if (functions && status === "function") functions.push(violation); - return status === "before"; - }); -} + ReplaceSupers.prototype.getObjectRef = function getObjectRef() { + return this.opts.objectRef || this.opts.getObjectRef(); + }; -function inferAnnotationFromBinaryExpression(name, path) { - var operator = path.node.operator; + ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed) { + return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), value, t.thisExpression()]); + }; - var right = path.get("right").resolve(); - var left = path.get("left").resolve(); + ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed) { + return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), t.thisExpression()]); + }; - var target = void 0; - if (left.isIdentifier({ name: name })) { - target = right; - } else if (right.isIdentifier({ name: name })) { - target = left; - } - if (target) { - if (operator === "===") { - return target.getTypeAnnotation(); - } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else { + ReplaceSupers.prototype.replace = function replace() { + this.methodPath.traverse(visitor, this); + }; + + ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) { + var methodNode = this.methodNode; + var superRef = this.superRef || t.identifier("Function"); + + if (parent.property === id) { + return; + } else if (t.isCallExpression(parent, { callee: id })) { return; + } else if (t.isMemberExpression(parent) && !methodNode.static) { + return t.memberExpression(superRef, t.identifier("prototype")); + } else { + return superRef; } - } else { - if (operator !== "===") return; - } + }; - var typeofPath = void 0; - var typePath = void 0; - if (left.isUnaryExpression({ operator: "typeof" })) { - typeofPath = left; - typePath = right; - } else if (right.isUnaryExpression({ operator: "typeof" })) { - typeofPath = right; - typePath = left; - } - if (!typePath && !typeofPath) return; + ReplaceSupers.prototype.looseHandle = function looseHandle(path) { + var node = path.node; + if (path.isSuper()) { + return this.getLooseSuperProperty(node, path.parent); + } else if (path.isCallExpression()) { + var callee = node.callee; + if (!t.isMemberExpression(callee)) return; + if (!t.isSuper(callee.object)) return; - typePath = typePath.resolve(); - if (!typePath.isLiteral()) return; + t.appendToMemberExpression(callee, t.identifier("call")); + node.arguments.unshift(t.thisExpression()); + return true; + } + }; - var typeValue = typePath.node.value; - if (typeof typeValue !== "string") return; + ReplaceSupers.prototype.specHandleAssignmentExpression = function specHandleAssignmentExpression(ref, path, node) { + if (node.operator === "=") { + return this.setSuperProperty(node.left.property, node.right, node.left.computed); + } else { + ref = ref || path.scope.generateUidIdentifier("ref"); + return [t.variableDeclaration("var", [t.variableDeclarator(ref, node.left)]), t.expressionStatement(t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right)))]; + } + }; - if (!typeofPath.get("argument").isIdentifier({ name: name })) return; + ReplaceSupers.prototype.specHandle = function specHandle(path) { + var property = void 0; + var computed = void 0; + var args = void 0; - return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); -} + var parent = path.parent; + var node = path.node; -function getParentConditionalPath(path) { - var parentPath = void 0; - while (parentPath = path.parentPath) { - if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { - if (path.key === "test") { + if (isIllegalBareSuper(node, parent)) { + throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); + } + + if (t.isCallExpression(node)) { + var callee = node.callee; + if (t.isSuper(callee)) { return; + } else if (isMemberExpressionSuper(callee)) { + property = callee.property; + computed = callee.computed; + args = node.arguments; + } + } else if (t.isMemberExpression(node) && t.isSuper(node.object)) { + property = node.property; + computed = node.computed; + } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { + var binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); + if (node.prefix) { + return this.specHandleAssignmentExpression(null, path, binary); } else { - return parentPath; + var ref = path.scope.generateUidIdentifier("ref"); + return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); } - } else { - path = parentPath; + } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { + return this.specHandleAssignmentExpression(null, path, node); } - } -} - -function getConditionalAnnotation(path, name) { - var ifStatement = getParentConditionalPath(path); - if (!ifStatement) return; - var test = ifStatement.get("test"); - var paths = [test]; - var types = []; + if (!property) return; - do { - var _path = paths.shift().resolve(); + var superProperty = this.getSuperProperty(property, computed); - if (_path.isLogicalExpression()) { - paths.push(_path.get("left")); - paths.push(_path.get("right")); + if (args) { + return this.optimiseCall(superProperty, args); + } else { + return superProperty; } + }; - if (_path.isBinaryExpression()) { - var type = inferAnnotationFromBinaryExpression(name, _path); - if (type) types.push(type); - } - } while (paths.length); + ReplaceSupers.prototype.optimiseCall = function optimiseCall(callee, args) { + var thisNode = t.thisExpression(); + thisNode[HARDCORE_THIS_REF] = true; + return (0, _babelHelperOptimiseCallExpression2.default)(callee, thisNode, args); + }; - if (types.length) { - return { - typeAnnotation: t.createUnionTypeAnnotation(types), - ifStatement: ifStatement - }; - } else { - return getConditionalAnnotation(ifStatement, name); - } -} + return ReplaceSupers; +}(); + +exports.default = ReplaceSupers; module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":89,"babel-types":145}],122:[function(require,module,exports){ +},{"babel-helper-optimise-call-expression":111,"babel-messages":115,"babel-runtime/core-js/symbol":136,"babel-runtime/helpers/classCallCheck":141,"babel-types":183}],113:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined; -var _infererReference = require("./inferer-reference"); - -Object.defineProperty(exports, "Identifier", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_infererReference).default; - } -}); -exports.VariableDeclarator = VariableDeclarator; -exports.TypeCastExpression = TypeCastExpression; -exports.NewExpression = NewExpression; -exports.TemplateLiteral = TemplateLiteral; -exports.UnaryExpression = UnaryExpression; -exports.BinaryExpression = BinaryExpression; -exports.LogicalExpression = LogicalExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.SequenceExpression = SequenceExpression; -exports.AssignmentExpression = AssignmentExpression; -exports.UpdateExpression = UpdateExpression; -exports.StringLiteral = StringLiteral; -exports.NumericLiteral = NumericLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.RegExpLiteral = RegExpLiteral; -exports.ObjectExpression = ObjectExpression; -exports.ArrayExpression = ArrayExpression; -exports.RestElement = RestElement; -exports.CallExpression = CallExpression; -exports.TaggedTemplateExpression = TaggedTemplateExpression; +var _babelTemplate = require("babel-template"); -var _babelTypes = require("babel-types"); +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); -var t = _interopRequireWildcard(_babelTypes); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var helpers = {}; +exports.default = helpers; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function VariableDeclarator() { - var id = this.get("id"); +helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); - if (id.isIdentifier()) { - return this.get("init").getTypeAnnotation(); - } else { - return; - } -} +helpers.jsx = (0, _babelTemplate2.default)("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n"); -function TypeCastExpression(node) { - return node.typeAnnotation; -} +helpers.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); -TypeCastExpression.validParent = true; +helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); -function NewExpression(node) { - if (this.get("callee").isIdentifier()) { - return t.genericTypeAnnotation(node.callee); - } -} +helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); -function TemplateLiteral() { - return t.stringTypeAnnotation(); -} +helpers.asyncToGenerator = (0, _babelTemplate2.default)("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); -function UnaryExpression(node) { - var operator = node.operator; +helpers.classCallCheck = (0, _babelTemplate2.default)("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n"); - if (operator === "void") { - return t.voidTypeAnnotation(); - } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.stringTypeAnnotation(); - } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } -} +helpers.createClass = (0, _babelTemplate2.default)("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n"); -function BinaryExpression(node) { - var operator = node.operator; +helpers.defineEnumerableProperties = (0, _babelTemplate2.default)("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n"); - if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } else if (operator === "+") { - var right = this.get("right"); - var left = this.get("left"); +helpers.defaults = (0, _babelTemplate2.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"); - if (left.isBaseType("number") && right.isBaseType("number")) { - return t.numberTypeAnnotation(); - } else if (left.isBaseType("string") || right.isBaseType("string")) { - return t.stringTypeAnnotation(); - } +helpers.defineProperty = (0, _babelTemplate2.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"); - return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); - } -} +helpers.extends = (0, _babelTemplate2.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"); -function LogicalExpression() { - return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); -} +helpers.get = (0, _babelTemplate2.default)("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n"); -function ConditionalExpression() { - return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); -} +helpers.inherits = (0, _babelTemplate2.default)("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n"); -function SequenceExpression() { - return this.get("expressions").pop().getTypeAnnotation(); -} +helpers.instanceof = (0, _babelTemplate2.default)("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n"); -function AssignmentExpression() { - return this.get("right").getTypeAnnotation(); -} +helpers.interopRequireDefault = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); -function UpdateExpression(node) { - var operator = node.operator; - if (operator === "++" || operator === "--") { - return t.numberTypeAnnotation(); - } -} +helpers.interopRequireWildcard = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"); -function StringLiteral() { - return t.stringTypeAnnotation(); -} +helpers.newArrowCheck = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); -function NumericLiteral() { - return t.numberTypeAnnotation(); -} +helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); -function BooleanLiteral() { - return t.booleanTypeAnnotation(); -} +helpers.objectWithoutProperties = (0, _babelTemplate2.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"); -function NullLiteral() { - return t.nullLiteralTypeAnnotation(); -} +helpers.possibleConstructorReturn = (0, _babelTemplate2.default)("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n"); -function RegExpLiteral() { - return t.genericTypeAnnotation(t.identifier("RegExp")); -} +helpers.selfGlobal = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); -function ObjectExpression() { - return t.genericTypeAnnotation(t.identifier("Object")); -} +helpers.set = (0, _babelTemplate2.default)("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n"); -function ArrayExpression() { - return t.genericTypeAnnotation(t.identifier("Array")); -} +helpers.slicedToArray = (0, _babelTemplate2.default)("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n"); -function RestElement() { - return ArrayExpression(); -} +helpers.slicedToArrayLoose = (0, _babelTemplate2.default)("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n"); -RestElement.validParent = true; +helpers.taggedTemplateLiteral = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); -function Func() { - return t.genericTypeAnnotation(t.identifier("Function")); -} +helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); -exports.FunctionExpression = Func; -exports.ArrowFunctionExpression = Func; -exports.FunctionDeclaration = Func; -exports.ClassExpression = Func; -exports.ClassDeclaration = Func; -function CallExpression() { - return resolveCall(this.get("callee")); -} +helpers.temporalRef = (0, _babelTemplate2.default)("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n"); -function TaggedTemplateExpression() { - return resolveCall(this.get("tag")); -} +helpers.temporalUndefined = (0, _babelTemplate2.default)("\n ({})\n"); -function resolveCall(callee) { - callee = callee.resolve(); +helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); - if (callee.isFunction()) { - if (callee.is("async")) { - if (callee.is("generator")) { - return t.genericTypeAnnotation(t.identifier("AsyncIterator")); - } else { - return t.genericTypeAnnotation(t.identifier("Promise")); - } - } else { - if (callee.node.returnType) { - return callee.node.returnType; - } else {} - } - } -} -},{"./inferer-reference":121,"babel-types":145}],123:[function(require,module,exports){ +helpers.toConsumableArray = (0, _babelTemplate2.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"); +module.exports = exports["default"]; +},{"babel-template":146}],114:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.is = undefined; +exports.list = undefined; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _keys = require("babel-runtime/core-js/object/keys"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _keys2 = _interopRequireDefault(_keys); -exports.matchesPattern = matchesPattern; -exports.has = has; -exports.isStatic = isStatic; -exports.isnt = isnt; -exports.equals = equals; -exports.isNodeType = isNodeType; -exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; -exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; -exports.isCompletionRecord = isCompletionRecord; -exports.isStatementOrBlock = isStatementOrBlock; -exports.referencesImport = referencesImport; -exports.getSource = getSource; -exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; -exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; -exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; -exports.resolve = resolve; -exports._resolve = _resolve; +exports.get = get; -var _includes = require("lodash/includes"); +var _helpers = require("./helpers"); -var _includes2 = _interopRequireDefault(_includes); +var _helpers2 = _interopRequireDefault(_helpers); -var _babelTypes = require("babel-types"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var t = _interopRequireWildcard(_babelTypes); +function get(name) { + var fn = _helpers2.default[name]; + if (!fn) throw new ReferenceError("Unknown helper " + name); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return fn().expression; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { + return name.replace(/^_/, ""); +}).filter(function (name) { + return name !== "__esModule"; +}); -function matchesPattern(pattern, allowPartial) { - if (!this.isMemberExpression()) return false; +exports.default = get; +},{"./helpers":113,"babel-runtime/core-js/object/keys":134}],115:[function(require,module,exports){ +"use strict"; - var parts = pattern.split("."); - var search = [this.node]; - var i = 0; - - function matches(name) { - var part = parts[i]; - return part === "*" || name === part; - } - - while (search.length) { - var node = search.shift(); +exports.__esModule = true; +exports.MESSAGES = undefined; - if (allowPartial && i === parts.length) { - return true; - } +var _stringify = require("babel-runtime/core-js/json/stringify"); - if (t.isIdentifier(node)) { - if (!matches(node.name)) return false; - } else if (t.isLiteral(node)) { - if (!matches(node.value)) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isLiteral(node.property)) { - return false; - } else { - search.unshift(node.property); - search.unshift(node.object); - continue; - } - } else if (t.isThisExpression(node)) { - if (!matches("this")) return false; - } else { - return false; - } +var _stringify2 = _interopRequireDefault(_stringify); - if (++i > parts.length) { - return false; - } - } +exports.get = get; +exports.parseArgs = parseArgs; - return i === parts.length; -} +var _util = require("util"); -function has(key) { - var val = this.node && this.node[key]; - if (val && Array.isArray(val)) { - return !!val.length; - } else { - return !!val; - } -} +var util = _interopRequireWildcard(_util); -function isStatic() { - return this.scope.isStatic(this.node); -} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var is = exports.is = has; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function isnt(key) { - return !this.has(key); -} +var MESSAGES = exports.MESSAGES = { + tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", + classesIllegalBareSuper: "Illegal use of bare super", + classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", + scopeDuplicateDeclaration: "Duplicate declaration $1", + settersNoRest: "Setters aren't allowed to have a rest", + noAssignmentsInForHead: "No assignments allowed in for-in/of head", + expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", + invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", + readOnly: "$1 is read-only", + unknownForHead: "Unknown node type $1 in ForStatement", + didYouMean: "Did you mean $1?", + codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", + missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", + unsupportedOutputType: "Unsupported output type $1", + illegalMethodName: "Illegal method name $1", + lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", -function equals(key, value) { - return this.node[key] === value; -} + modulesIllegalExportName: "Illegal export $1", + modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", -function isNodeType(type) { - return t.isType(this.type, type); -} + undeclaredVariable: "Reference to undeclared variable $1", + undeclaredVariableType: "Referencing a type alias outside of a type annotation", + undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", -function canHaveVariableDeclarationOrExpression() { - return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); -} + traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.", + traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", + traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", + traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", -function canSwapBetweenExpressionAndStatement(replacement) { - if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { - return false; - } + pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", + pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", + pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", + pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" +}; - if (this.isExpression()) { - return t.isBlockStatement(replacement); - } else if (this.isBlockStatement()) { - return t.isExpression(replacement); +function get(key) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; } - return false; -} + var msg = MESSAGES[key]; + if (!msg) throw new ReferenceError("Unknown message " + (0, _stringify2.default)(key)); -function isCompletionRecord(allowInsideFunction) { - var path = this; - var first = true; + args = parseArgs(args); - do { - var container = path.container; + return msg.replace(/\$(\d+)/g, function (str, i) { + return args[i - 1]; + }); +} - if (path.isFunction() && !first) { - return !!allowInsideFunction; +function parseArgs(args) { + return args.map(function (val) { + if (val != null && val.inspect) { + return val.inspect(); + } else { + try { + return (0, _stringify2.default)(val) || val + ""; + } catch (e) { + return util.inspect(val); + } } + }); +} +},{"babel-runtime/core-js/json/stringify":128,"util":36}],116:[function(require,module,exports){ +"use strict"; - first = false; +exports.__esModule = true; - if (Array.isArray(container) && path.key !== container.length - 1) { - return false; +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("asyncFunctions"); } - } while ((path = path.parentPath) && !path.isProgram()); - - return true; -} - -function isStatementOrBlock() { - if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { - return false; - } else { - return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); - } -} + }; +}; -function referencesImport(moduleSource, importName) { - if (!this.isReferencedIdentifier()) return false; +module.exports = exports["default"]; +},{}],117:[function(require,module,exports){ +"use strict"; - var binding = this.scope.getBinding(this.node.name); - if (!binding || binding.kind !== "module") return false; +exports.__esModule = true; - var path = binding.path; - var parent = path.parentPath; - if (!parent.isImportDeclaration()) return false; +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("asyncGenerators"); + } + }; +}; - if (parent.node.source.value === moduleSource) { - if (!importName) return true; - } else { - return false; - } +module.exports = exports["default"]; +},{}],118:[function(require,module,exports){ +"use strict"; - if (path.isImportDefaultSpecifier() && importName === "default") { - return true; - } +exports.__esModule = true; - if (path.isImportNamespaceSpecifier() && importName === "*") { - return true; - } +exports.default = function (_ref) { + var t = _ref.types; - if (path.isImportSpecifier() && path.node.imported.name === importName) { - return true; - } + return { + visitor: { + ArrowFunctionExpression: function ArrowFunctionExpression(path, state) { + if (state.opts.spec) { + var node = path.node; - return false; -} + if (node.shadow) return; -function getSource() { - var node = this.node; - if (node.end) { - return this.hub.file.code.slice(node.start, node.end); - } else { - return ""; - } -} + node.shadow = { this: false }; + node.type = "FunctionExpression"; -function willIMaybeExecuteBefore(target) { - return this._guessExecutionStatusRelativeTo(target) !== "after"; -} + var boundThis = t.thisExpression(); + boundThis._forceShadow = path; -function _guessExecutionStatusRelativeTo(target) { - var targetFuncParent = target.scope.getFunctionParent(); - var selfFuncParent = this.scope.getFunctionParent(); + path.ensureBlock(); + path.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [t.thisExpression(), boundThis]))); - if (targetFuncParent.node !== selfFuncParent.node) { - var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); - if (status) { - return status; - } else { - target = targetFuncParent.path; + path.replaceWith(t.callExpression(t.memberExpression(node, t.identifier("bind")), [t.thisExpression()])); + } else { + path.arrowFunctionToShadowed(); + } + } } - } + }; +}; - var targetPaths = target.getAncestry(); - if (targetPaths.indexOf(this) >= 0) return "after"; +module.exports = exports["default"]; +},{}],119:[function(require,module,exports){ +"use strict"; - var selfPaths = this.getAncestry(); +exports.__esModule = true; - var commonPath = void 0; - var targetIndex = void 0; - var selfIndex = void 0; - for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { - var selfPath = selfPaths[selfIndex]; - targetIndex = targetPaths.indexOf(selfPath); - if (targetIndex >= 0) { - commonPath = selfPath; - break; - } - } - if (!commonPath) { - return "before"; - } +var _symbol = require("babel-runtime/core-js/symbol"); - var targetRelationship = targetPaths[targetIndex - 1]; - var selfRelationship = selfPaths[selfIndex - 1]; - if (!targetRelationship || !selfRelationship) { - return "before"; - } +var _symbol2 = _interopRequireDefault(_symbol); - if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { - return targetRelationship.key > selfRelationship.key ? "before" : "after"; - } +var _create = require("babel-runtime/core-js/object/create"); - var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); - var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); - return targetKeyPosition > selfKeyPosition ? "before" : "after"; -} +var _create2 = _interopRequireDefault(_create); -function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { - var targetFuncPath = targetFuncParent.path; - if (!targetFuncPath.isFunctionDeclaration()) return; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - if (!binding.references) return "before"; +exports.default = function () { + return { + visitor: { + VariableDeclaration: function VariableDeclaration(path, file) { + var node = path.node, + parent = path.parent, + scope = path.scope; - var referencePaths = binding.referencePaths; + if (!isBlockScoped(node)) return; + convertBlockScopedToVar(path, null, parent, scope, true); - for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (node._tdzThis) { + var nodes = [node]; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + for (var i = 0; i < node.declarations.length; i++) { + var decl = node.declarations[i]; + if (decl.init) { + var assign = t.assignmentExpression("=", decl.id, decl.init); + assign._ignoreBlockScopingTDZ = true; + nodes.push(t.expressionStatement(assign)); + } + decl.init = file.addHelper("temporalUndefined"); + } - var path = _ref; + node._blockHoist = 2; - if (path.key !== "callee" || !path.parentPath.isCallExpression()) { - return; - } - } + if (path.isCompletionRecord()) { + nodes.push(t.expressionStatement(scope.buildUndefinedNode())); + } - var allStatus = void 0; + path.replaceWithMultiple(nodes); + } + }, + Loop: function Loop(path, file) { + var node = path.node, + parent = path.parent, + scope = path.scope; - for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + t.ensureBlock(node); + var blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); + var replace = blockScoping.run(); + if (replace) path.replaceWith(replace); + }, + CatchClause: function CatchClause(path, file) { + var parent = path.parent, + scope = path.scope; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + var blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); + blockScoping.run(); + }, + "BlockStatement|SwitchStatement|Program": function BlockStatementSwitchStatementProgram(path, file) { + if (!ignoreBlock(path)) { + var blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); + blockScoping.run(); + } + } } + }; +}; - var _path = _ref2; - - var childOfFunction = !!_path.find(function (path) { - return path.node === targetFuncPath.node; - }); - if (childOfFunction) continue; +var _babelTraverse = require("babel-traverse"); - var status = this._guessExecutionStatusRelativeTo(_path); +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - if (allStatus) { - if (allStatus !== status) return; - } else { - allStatus = status; - } - } +var _tdz = require("./tdz"); - return allStatus; -} +var _babelTypes = require("babel-types"); -function resolve(dangerous, resolved) { - return this._resolve(dangerous, resolved) || this; -} +var t = _interopRequireWildcard(_babelTypes); -function _resolve(dangerous, resolved) { - if (resolved && resolved.indexOf(this) >= 0) return; +var _values = require("lodash/values"); - resolved = resolved || []; - resolved.push(this); +var _values2 = _interopRequireDefault(_values); - if (this.isVariableDeclarator()) { - if (this.get("id").isIdentifier()) { - return this.get("init").resolve(dangerous, resolved); - } else {} - } else if (this.isReferencedIdentifier()) { - var binding = this.scope.getBinding(this.node.name); - if (!binding) return; +var _extend = require("lodash/extend"); - if (!binding.constant) return; +var _extend2 = _interopRequireDefault(_extend); - if (binding.kind === "module") return; +var _babelTemplate = require("babel-template"); - if (binding.path !== this) { - var ret = binding.path.resolve(dangerous, resolved); +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - if (this.find(function (parent) { - return parent.node === ret.node; - })) return; - return ret; - } - } else if (this.isTypeCastExpression()) { - return this.get("expression").resolve(dangerous, resolved); - } else if (dangerous && this.isMemberExpression()) { +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var targetKey = this.toComputedKey(); - if (!t.isLiteral(targetKey)) return; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var targetName = targetKey.value; +function ignoreBlock(path) { + return t.isLoop(path.parent) || t.isCatchClause(path.parent); +} - var target = this.get("object").resolve(dangerous, resolved); +var buildRetCheck = (0, _babelTemplate2.default)("\n if (typeof RETURN === \"object\") return RETURN.v;\n"); - if (target.isObjectExpression()) { - var props = target.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +function isBlockScoped(node) { + if (!t.isVariableDeclaration(node)) return false; + if (node[t.BLOCK_SCOPED_SYMBOL]) return true; + if (node.kind !== "let" && node.kind !== "const") return false; + return true; +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +function convertBlockScopedToVar(path, node, parent, scope) { + var moveBindingsToParent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var prop = _ref3; + if (!node) { + node = path.node; + } - if (!prop.isProperty()) continue; + if (!t.isFor(parent)) { + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; + declar.init = declar.init || scope.buildUndefinedNode(); + } + } - var key = prop.get("key"); + node[t.BLOCK_SCOPED_SYMBOL] = true; + node.kind = "var"; - var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); + if (moveBindingsToParent) { + var parentScope = scope.getFunctionParent(); + var ids = path.getBindingIdentifiers(); + for (var name in ids) { + var binding = scope.getOwnBinding(name); + if (binding) binding.kind = "var"; + scope.moveBindingTo(name, parentScope); + } + } +} - match = match || key.isLiteral({ value: targetName }); +function isVar(node) { + return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); +} - if (match) return prop.get("value").resolve(dangerous, resolved); - } - } else if (target.isArrayExpression() && !isNaN(+targetName)) { - var elems = target.get("elements"); - var elem = elems[targetName]; - if (elem) return elem.resolve(dangerous, resolved); +var letReferenceBlockVisitor = _babelTraverse2.default.visitors.merge([{ + Loop: { + enter: function enter(path, state) { + state.loopDepth++; + }, + exit: function exit(path, state) { + state.loopDepth--; + } + }, + Function: function Function(path, state) { + if (state.loopDepth > 0) { + path.traverse(letReferenceFunctionVisitor, state); } + return path.skip(); } -} -},{"babel-runtime/core-js/get-iterator":89,"babel-types":145,"lodash/includes":471}],124:[function(require,module,exports){ -"use strict"; +}, _tdz.visitor]); -exports.__esModule = true; +var letReferenceFunctionVisitor = _babelTraverse2.default.visitors.merge([{ + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + var ref = state.letReferences[path.node.name]; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (!ref) return; -var _getIterator3 = _interopRequireDefault(_getIterator2); + var localBinding = path.scope.getBindingIdentifier(path.node.name); + if (localBinding && localBinding !== ref) return; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + state.closurify = true; + } +}, _tdz.visitor]); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +var hoistVarDeclarationsVisitor = { + enter: function enter(path, self) { + var node = path.node, + parent = path.parent; -var _babelTypes = require("babel-types"); -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var referenceVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { - return; - } - - if (path.node.name === "this") { - var scope = path.scope; - do { - if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break; - } while (scope = scope.parent); - if (scope) state.breakOnScopePaths.push(scope.path); + if (path.isForStatement()) { + if (isVar(node.init, node)) { + var nodes = self.pushDeclar(node.init); + if (nodes.length === 1) { + node.init = nodes[0]; + } else { + node.init = t.sequenceExpression(nodes); + } + } + } else if (path.isFor()) { + if (isVar(node.left, node)) { + self.pushDeclar(node.left); + node.left = node.left.declarations[0].id; + } + } else if (isVar(node, parent)) { + path.replaceWithMultiple(self.pushDeclar(node).map(function (expr) { + return t.expressionStatement(expr); + })); + } else if (path.isFunction()) { + return path.skip(); } + } +}; - var binding = path.scope.getBinding(path.node.name); - if (!binding) return; +var loopLabelVisitor = { + LabeledStatement: function LabeledStatement(_ref, state) { + var node = _ref.node; - if (binding !== state.scope.getBinding(path.node.name)) return; + state.innerLabels.push(node.label.name); + } +}; - state.bindings[path.node.name] = binding; +var continuationVisitor = { + enter: function enter(path, state) { + if (path.isAssignmentExpression() || path.isUpdateExpression()) { + var bindings = path.getBindingIdentifiers(); + for (var name in bindings) { + if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; + state.reassignments[name] = true; + } + } } }; -var PathHoister = function () { - function PathHoister(path, scope) { - (0, _classCallCheck3.default)(this, PathHoister); +function loopNodeTo(node) { + if (t.isBreakStatement(node)) { + return "break"; + } else if (t.isContinueStatement(node)) { + return "continue"; + } +} - this.breakOnScopePaths = []; +var loopVisitor = { + Loop: function Loop(path, state) { + var oldIgnoreLabeless = state.ignoreLabeless; + state.ignoreLabeless = true; + path.traverse(loopVisitor, state); + state.ignoreLabeless = oldIgnoreLabeless; + path.skip(); + }, + Function: function Function(path) { + path.skip(); + }, + SwitchCase: function SwitchCase(path, state) { + var oldInSwitchCase = state.inSwitchCase; + state.inSwitchCase = true; + path.traverse(loopVisitor, state); + state.inSwitchCase = oldInSwitchCase; + path.skip(); + }, + "BreakStatement|ContinueStatement|ReturnStatement": function BreakStatementContinueStatementReturnStatement(path, state) { + var node = path.node, + parent = path.parent, + scope = path.scope; - this.bindings = {}; + if (node[this.LOOP_IGNORE]) return; - this.scopes = []; + var replace = void 0; + var loopText = loopNodeTo(node); - this.scope = scope; - this.path = path; + if (loopText) { + if (node.label) { + if (state.innerLabels.indexOf(node.label.name) >= 0) { + return; + } - this.attachAfter = false; - } + loopText = loopText + "|" + node.label.name; + } else { + if (state.ignoreLabeless) return; - PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { - for (var key in this.bindings) { - var binding = this.bindings[key]; - if (!scope.bindingIdentifierEquals(key, binding.identifier)) { - return false; + if (state.inSwitchCase) return; + + if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; } + + state.hasBreakContinue = true; + state.map[loopText] = node; + replace = t.stringLiteral(loopText); } - return true; - }; + if (path.isReturnStatement()) { + state.hasReturn = true; + replace = t.objectExpression([t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode())]); + } - PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { - var scope = this.path.scope; - do { - if (this.isCompatibleScope(scope)) { - this.scopes.push(scope); - } else { - break; - } + if (replace) { + replace = t.returnStatement(replace); + replace[this.LOOP_IGNORE] = true; + path.skip(); + path.replaceWith(t.inherits(replace, node)); + } + } +}; - if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { - break; - } - } while (scope = scope.parent); - }; +var BlockScoping = function () { + function BlockScoping(loopPath, blockPath, parent, scope, file) { + (0, _classCallCheck3.default)(this, BlockScoping); - PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { - var path = this._getAttachmentPath(); - if (!path) return; + this.parent = parent; + this.scope = scope; + this.file = file; - var targetScope = path.scope; + this.blockPath = blockPath; + this.block = blockPath.node; - if (targetScope.path === path) { - targetScope = path.scope.parent; + this.outsideLetReferences = (0, _create2.default)(null); + this.hasLetReferences = false; + this.letReferences = (0, _create2.default)(null); + this.body = []; + + if (loopPath) { + this.loopParent = loopPath.parent; + this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; + this.loopPath = loopPath; + this.loop = loopPath.node; } + } - if (targetScope.path.isProgram() || targetScope.path.isFunction()) { - for (var name in this.bindings) { - if (!targetScope.hasOwnBinding(name)) continue; + BlockScoping.prototype.run = function run() { + var block = this.block; + if (block._letDone) return; + block._letDone = true; - var binding = this.bindings[name]; + var needsClosure = this.getLetReferences(); - if (binding.kind === "param") continue; + if (t.isFunction(this.parent) || t.isProgram(this.block)) { + this.updateScopeInfo(); + return; + } - if (this.getAttachmentParentForPath(binding.path).key > path.key) { - this.attachAfter = true; - path = binding.path; + if (!this.hasLetReferences) return; - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (needsClosure) { + this.wrapClosure(); + } else { + this.remap(); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + this.updateScopeInfo(needsClosure); - var violationPath = _ref; + if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { + return t.labeledStatement(this.loopLabel, this.loop); + } + }; - if (this.getAttachmentParentForPath(violationPath).key > path.key) { - path = violationPath; - } - } + BlockScoping.prototype.updateScopeInfo = function updateScopeInfo(wrappedInClosure) { + var scope = this.scope; + var parentScope = scope.getFunctionParent(); + var letRefs = this.letReferences; + + for (var key in letRefs) { + var ref = letRefs[key]; + var binding = scope.getBinding(ref.name); + if (!binding) continue; + if (binding.kind === "let" || binding.kind === "const") { + binding.kind = "var"; + + if (wrappedInClosure) { + scope.removeBinding(ref.name); + } else { + scope.moveBindingTo(ref.name, parentScope); } } } - - if (path.parentPath.isExportDeclaration()) { - path = path.parentPath; - } - - return path; }; - PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { - var scopes = this.scopes; - - var scope = scopes.pop(); + BlockScoping.prototype.remap = function remap() { + var letRefs = this.letReferences; + var scope = this.scope; - if (!scope) return; + for (var key in letRefs) { + var ref = letRefs[key]; - if (scope.path.isFunction()) { - if (this.hasOwnParamBindings(scope)) { - if (this.scope === scope) return; + if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { + if (scope.hasOwnBinding(key)) scope.rename(ref.name); - return scope.path.get("body").get("body")[0]; - } else { - return this.getNextScopeAttachmentParent(); + if (this.blockPath.scope.hasOwnBinding(key)) this.blockPath.scope.rename(ref.name); } - } else if (scope.path.isProgram()) { - return this.getNextScopeAttachmentParent(); } }; - PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() { - var scope = this.scopes.pop(); - if (scope) return this.getAttachmentParentForPath(scope.path); - }; + BlockScoping.prototype.wrapClosure = function wrapClosure() { + if (this.file.opts.throwIfClosureRequired) { + throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired)."); + } + var block = this.block; - PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) { - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path; - } while (path = path.parentPath); - }; + var outsideRefs = this.outsideLetReferences; - PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { - for (var name in this.bindings) { - if (!scope.hasOwnBinding(name)) continue; + if (this.loop) { + for (var name in outsideRefs) { + var id = outsideRefs[name]; - var binding = this.bindings[name]; + if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { + delete outsideRefs[id.name]; + delete this.letReferences[id.name]; - if (binding.kind === "param" && binding.constant) return true; + this.scope.rename(id.name); + + this.letReferences[id.name] = id; + outsideRefs[id.name] = id; + } + } } - return false; - }; - PathHoister.prototype.run = function run() { - var node = this.path.node; - if (node._hoisted) return; - node._hoisted = true; + this.has = this.checkLoop(); - this.path.traverse(referenceVisitor, this); + this.hoistVarDeclarations(); - this.getCompatibleScopes(); + var params = (0, _values2.default)(outsideRefs); + var args = (0, _values2.default)(outsideRefs); - var attachTo = this.getAttachmentPath(); - if (!attachTo) return; + var isSwitch = this.blockPath.isSwitchStatement(); - if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; + var fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); + fn.shadow = true; - var uid = attachTo.scope.generateUidIdentifier("ref"); - var declarator = t.variableDeclarator(uid, this.path.node); + this.addContinuations(fn); - var insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; - attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]); + var ref = fn; - var parent = this.path.parentPath; - if (parent.isJSXElement() && this.path.container === parent.node.children) { - uid = t.JSXExpressionContainer(uid); + if (this.loop) { + ref = this.scope.generateUidIdentifier("loop"); + this.loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(ref, fn)])); } - this.path.replaceWith(uid); - }; + var call = t.callExpression(ref, args); + var ret = this.scope.generateUidIdentifier("ret"); - return PathHoister; -}(); + var hasYield = _babelTraverse2.default.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); + if (hasYield) { + fn.generator = true; + call = t.yieldExpression(call, true); + } -exports.default = PathHoister; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/classCallCheck":103,"babel-types":145}],125:[function(require,module,exports){ -"use strict"; + var hasAsync = _babelTraverse2.default.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); + if (hasAsync) { + fn.async = true; + call = t.awaitExpression(call); + } -exports.__esModule = true; -var hooks = exports.hooks = [function (self, parent) { - var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); + this.buildClosure(ret, call); - if (removeParent) { - parent.remove(); - return true; - } -}, function (self, parent) { - if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { - parent.replaceWith(parent.node.expressions[0]); - return true; - } -}, function (self, parent) { - if (parent.isBinary()) { - if (self.key === "left") { - parent.replaceWith(parent.node.right); + if (isSwitch) this.blockPath.replaceWithMultiple(this.body);else block.body = this.body; + }; + + BlockScoping.prototype.buildClosure = function buildClosure(ret, call) { + var has = this.has; + if (has.hasReturn || has.hasBreakContinue) { + this.buildHas(ret, call); } else { - parent.replaceWith(parent.node.left); + this.body.push(t.expressionStatement(call)); } - return true; - } -}, function (self, parent) { - if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { - self.replaceWith({ - type: "BlockStatement", - body: [] - }); - return true; - } -}]; -},{}],126:[function(require,module,exports){ -"use strict"; + }; -exports.__esModule = true; -exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; + BlockScoping.prototype.addContinuations = function addContinuations(fn) { + var state = { + reassignments: {}, + outsideReferences: this.outsideLetReferences + }; -var _babelTypes = require("babel-types"); + this.scope.traverse(fn, continuationVisitor, state); -var t = _interopRequireWildcard(_babelTypes); + for (var i = 0; i < fn.params.length; i++) { + var param = fn.params[i]; + if (!state.reassignments[param.name]) continue; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var newParam = this.scope.generateUidIdentifier(param.name); + fn.params[i] = newParam; -var ReferencedIdentifier = exports.ReferencedIdentifier = { - types: ["Identifier", "JSXIdentifier"], - checkPath: function checkPath(_ref, opts) { - var node = _ref.node, - parent = _ref.parent; + this.scope.rename(param.name, newParam.name, fn); - if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { - if (t.isJSXIdentifier(node, opts)) { - if (_babelTypes.react.isCompatTag(node.name)) return false; - } else { - return false; - } + fn.body.body.push(t.expressionStatement(t.assignmentExpression("=", param, newParam))); } + }; - return t.isReferenced(node, parent); - } -}; - -var ReferencedMemberExpression = exports.ReferencedMemberExpression = { - types: ["MemberExpression"], - checkPath: function checkPath(_ref2) { - var node = _ref2.node, - parent = _ref2.parent; - - return t.isMemberExpression(node) && t.isReferenced(node, parent); - } -}; + BlockScoping.prototype.getLetReferences = function getLetReferences() { + var _this = this; -var BindingIdentifier = exports.BindingIdentifier = { - types: ["Identifier"], - checkPath: function checkPath(_ref3) { - var node = _ref3.node, - parent = _ref3.parent; + var block = this.block; - return t.isIdentifier(node) && t.isBinding(node, parent); - } -}; + var declarators = []; -var Statement = exports.Statement = { - types: ["Statement"], - checkPath: function checkPath(_ref4) { - var node = _ref4.node, - parent = _ref4.parent; + if (this.loop) { + var init = this.loop.left || this.loop.init; + if (isBlockScoped(init)) { + declarators.push(init); + (0, _extend2.default)(this.outsideLetReferences, t.getBindingIdentifiers(init)); + } + } - if (t.isStatement(node)) { - if (t.isVariableDeclaration(node)) { - if (t.isForXStatement(parent, { left: node })) return false; - if (t.isForStatement(parent, { init: node })) return false; + var addDeclarationsFromChild = function addDeclarationsFromChild(path, node) { + node = node || path.node; + if (t.isClassDeclaration(node) || t.isFunctionDeclaration(node) || isBlockScoped(node)) { + if (isBlockScoped(node)) { + convertBlockScopedToVar(path, node, block, _this.scope); + } + declarators = declarators.concat(node.declarations || node); + } + if (t.isLabeledStatement(node)) { + addDeclarationsFromChild(path.get("body"), node.body); } + }; - return true; - } else { - return false; + if (block.body) { + for (var i = 0; i < block.body.length; i++) { + var declarPath = this.blockPath.get("body")[i]; + addDeclarationsFromChild(declarPath); + } } - } -}; -var Expression = exports.Expression = { - types: ["Expression"], - checkPath: function checkPath(path) { - if (path.isIdentifier()) { - return path.isReferencedIdentifier(); - } else { - return t.isExpression(path.node); + if (block.cases) { + for (var _i = 0; _i < block.cases.length; _i++) { + var consequents = block.cases[_i].consequent; + + for (var j = 0; j < consequents.length; j++) { + var _declarPath = this.blockPath.get("cases")[_i]; + var declar = consequents[j]; + addDeclarationsFromChild(_declarPath, declar); + } + } } - } -}; -var Scope = exports.Scope = { - types: ["Scopable"], - checkPath: function checkPath(path) { - return t.isScope(path.node, path.parent); - } -}; + for (var _i2 = 0; _i2 < declarators.length; _i2++) { + var _declar = declarators[_i2]; -var Referenced = exports.Referenced = { - checkPath: function checkPath(path) { - return t.isReferenced(path.node, path.parent); - } -}; + var keys = t.getBindingIdentifiers(_declar, false, true); + (0, _extend2.default)(this.letReferences, keys); + this.hasLetReferences = true; + } -var BlockScoped = exports.BlockScoped = { - checkPath: function checkPath(path) { - return t.isBlockScoped(path.node); - } -}; + if (!this.hasLetReferences) return; -var Var = exports.Var = { - types: ["VariableDeclaration"], - checkPath: function checkPath(path) { - return t.isVar(path.node); - } -}; + var state = { + letReferences: this.letReferences, + closurify: false, + file: this.file, + loopDepth: 0 + }; -var User = exports.User = { - checkPath: function checkPath(path) { - return path.node && !!path.node.loc; - } -}; + var loopOrFunctionParent = this.blockPath.find(function (path) { + return path.isLoop() || path.isFunction(); + }); + if (loopOrFunctionParent && loopOrFunctionParent.isLoop()) { + state.loopDepth++; + } -var Generated = exports.Generated = { - checkPath: function checkPath(path) { - return !path.isUser(); - } -}; + this.blockPath.traverse(letReferenceBlockVisitor, state); -var Pure = exports.Pure = { - checkPath: function checkPath(path, opts) { - return path.scope.isPure(path.node, opts); - } -}; + return state.closurify; + }; -var Flow = exports.Flow = { - types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], - checkPath: function checkPath(_ref5) { - var node = _ref5.node; + BlockScoping.prototype.checkLoop = function checkLoop() { + var state = { + hasBreakContinue: false, + ignoreLabeless: false, + inSwitchCase: false, + innerLabels: [], + hasReturn: false, + isLoop: !!this.loop, + map: {}, + LOOP_IGNORE: (0, _symbol2.default)() + }; - if (t.isFlow(node)) { - return true; - } else if (t.isImportDeclaration(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else if (t.isExportDeclaration(node)) { - return node.exportKind === "type"; - } else if (t.isImportSpecifier(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else { - return false; + this.blockPath.traverse(loopLabelVisitor, state); + this.blockPath.traverse(loopVisitor, state); + + return state; + }; + + BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { + this.blockPath.traverse(hoistVarDeclarationsVisitor, this); + }; + + BlockScoping.prototype.pushDeclar = function pushDeclar(node) { + var declars = []; + var names = t.getBindingIdentifiers(node); + for (var name in names) { + declars.push(t.variableDeclarator(names[name])); } - } -}; -},{"babel-types":145}],127:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; + this.body.push(t.variableDeclaration(node.kind, declars)); -var _typeof2 = require("babel-runtime/helpers/typeof"); + var replace = []; -var _typeof3 = _interopRequireDefault(_typeof2); + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; + if (!declar.init) continue; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var expr = t.assignmentExpression("=", declar.id, declar.init); + replace.push(t.inherits(expr, declar)); + } -var _getIterator3 = _interopRequireDefault(_getIterator2); + return replace; + }; -exports.insertBefore = insertBefore; -exports._containerInsert = _containerInsert; -exports._containerInsertBefore = _containerInsertBefore; -exports._containerInsertAfter = _containerInsertAfter; -exports._maybePopFromStatements = _maybePopFromStatements; -exports.insertAfter = insertAfter; -exports.updateSiblingKeys = updateSiblingKeys; -exports._verifyNodeList = _verifyNodeList; -exports.unshiftContainer = unshiftContainer; -exports.pushContainer = pushContainer; -exports.hoist = hoist; + BlockScoping.prototype.buildHas = function buildHas(ret, call) { + var body = this.body; -var _cache = require("../cache"); + body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); -var _hoister = require("./lib/hoister"); + var retCheck = void 0; + var has = this.has; + var cases = []; -var _hoister2 = _interopRequireDefault(_hoister); + if (has.hasReturn) { + retCheck = buildRetCheck({ + RETURN: ret + }); + } -var _index = require("./index"); + if (has.hasBreakContinue) { + for (var key in has.map) { + cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); + } -var _index2 = _interopRequireDefault(_index); + if (has.hasReturn) { + cases.push(t.switchCase(null, [retCheck])); + } + + if (cases.length === 1) { + var single = cases[0]; + body.push(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0])); + } else { + if (this.loop) { + for (var i = 0; i < cases.length; i++) { + var caseConsequent = cases[i].consequent[0]; + if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { + caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); + } + } + } + + body.push(t.switchStatement(ret, cases)); + } + } else { + if (has.hasReturn) { + body.push(retCheck); + } + } + }; + + return BlockScoping; +}(); + +module.exports = exports["default"]; +},{"./tdz":120,"babel-runtime/core-js/object/create":132,"babel-runtime/core-js/symbol":136,"babel-runtime/helpers/classCallCheck":141,"babel-template":146,"babel-traverse":150,"babel-types":183,"lodash/extend":500,"lodash/values":543}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitor = undefined; var _babelTypes = require("babel-types"); @@ -17415,332 +19671,266 @@ var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function insertBefore(nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); +function getTDZStatus(refPath, bindingPath) { + var executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertBefore(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) nodes.push(this.node); - this.replaceExpressionWithStatements(nodes); + if (executionStatus === "before") { + return "inside"; + } else if (executionStatus === "after") { + return "outside"; } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertBefore(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.push(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); - } + return "maybe"; } +} - return [this]; +function buildTDZAssert(node, file) { + return t.callExpression(file.addHelper("temporalRef"), [node, t.stringLiteral(node.name), file.addHelper("temporalUndefined")]); } -function _containerInsert(from, nodes) { - this.updateSiblingKeys(from, nodes.length); +function isReference(node, scope, state) { + var declared = state.letReferences[node.name]; + if (!declared) return false; - var paths = []; + return scope.getBindingIdentifier(node.name) === declared; +} - for (var i = 0; i < nodes.length; i++) { - var to = from + i; - var node = nodes[i]; - this.container.splice(to, 0, node); +var visitor = exports.visitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (!this.file.opts.tdz) return; - if (this.context) { - var path = this.context.create(this.parent, this.container, to, this.listKey); + var node = path.node, + parent = path.parent, + scope = path.scope; - if (this.context.queue) path.pushContext(this.context); - paths.push(path); - } else { - paths.push(_index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: to - })); - } - } - var contexts = this._getQueueContexts(); + if (path.parentPath.isFor({ left: node })) return; + if (!isReference(node, scope, state)) return; - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var bindingPath = scope.getBinding(node.name).path; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + var status = getTDZStatus(path, bindingPath); + if (status === "inside") return; - var _path = _ref; + if (status === "maybe") { + var assert = buildTDZAssert(node, state.file); - _path.setScope(); - _path.debug(function () { - return "Inserted."; - }); + bindingPath.parent._tdzThis = true; - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + path.skip(); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; + if (path.parentPath.isUpdateExpression()) { + if (parent._ignoreBlockScopingTDZ) return; + path.parentPath.replaceWith(t.sequenceExpression([assert, parent])); } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + path.replaceWith(assert); } - - var context = _ref2; - - context.maybeQueue(_path, true); + } else if (status === "outside") { + path.replaceWith(t.throwStatement(t.inherits(t.newExpression(t.identifier("ReferenceError"), [t.stringLiteral(node.name + " is not defined - temporal dead zone")]), node))); } - } + }, - return paths; -} -function _containerInsertBefore(nodes) { - return this._containerInsert(this.key, nodes); -} + AssignmentExpression: { + exit: function exit(path, state) { + if (!this.file.opts.tdz) return; -function _containerInsertAfter(nodes) { - return this._containerInsert(this.key + 1, nodes); -} + var node = path.node; -function _maybePopFromStatements(nodes) { - var last = nodes[nodes.length - 1]; - var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); + if (node._ignoreBlockScopingTDZ) return; - if (isIdentifier && !this.isCompletionRecord()) { - nodes.pop(); - } -} + var nodes = []; + var ids = path.getBindingIdentifiers(); -function insertAfter(nodes) { - this._assertUnremoved(); + for (var name in ids) { + var id = ids[name]; - nodes = this._verifyNodeList(nodes); + if (isReference(id, path.scope, state)) { + nodes.push(buildTDZAssert(id, state.file)); + } + } - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertAfter(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) { - var temp = this.scope.generateDeclaredUidIdentifier(); - nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); - nodes.push(t.expressionStatement(temp)); - } - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertAfter(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.unshift(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); + if (nodes.length) { + node._ignoreBlockScopingTDZ = true; + nodes.push(node); + path.replaceWithMultiple(nodes.map(t.expressionStatement)); + } } } +}; +},{"babel-types":183}],121:[function(require,module,exports){ +"use strict"; - return [this]; -} - -function updateSiblingKeys(fromIndex, incrementBy) { - if (!this.parent) return; +exports.__esModule = true; - var paths = _cache.path.get(this.parent); - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (path.key >= fromIndex) { - path.key += incrementBy; - } - } -} +var _symbol = require("babel-runtime/core-js/symbol"); -function _verifyNodeList(nodes) { - if (!nodes) { - return []; - } +var _symbol2 = _interopRequireDefault(_symbol); - if (nodes.constructor !== Array) { - nodes = [nodes]; - } +exports.default = function (_ref) { + var t = _ref.types; - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - var msg = void 0; + var VISITED = (0, _symbol2.default)(); - if (!node) { - msg = "has falsy node"; - } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { - msg = "contains a non-object node"; - } else if (!node.type) { - msg = "without a type"; - } else if (node instanceof _index2.default) { - msg = "has a NodePath when it expected a raw object"; - } + return { + visitor: { + ExportDefaultDeclaration: function ExportDefaultDeclaration(path) { + if (!path.get("declaration").isClassDeclaration()) return; - if (msg) { - var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); - throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); - } - } + var node = path.node; - return nodes; -} + var ref = node.declaration.id || path.scope.generateUidIdentifier("class"); + node.declaration.id = ref; -function unshiftContainer(listKey, nodes) { - this._assertUnremoved(); + path.replaceWith(node.declaration); + path.insertAfter(t.exportDefaultDeclaration(ref)); + }, + ClassDeclaration: function ClassDeclaration(path) { + var node = path.node; - nodes = this._verifyNodeList(nodes); - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: this.node[listKey], - listKey: listKey, - key: 0 - }); + var ref = node.id || path.scope.generateUidIdentifier("class"); - return path.insertBefore(nodes); -} + path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(ref, t.toExpression(node))])); + }, + ClassExpression: function ClassExpression(path, state) { + var node = path.node; -function pushContainer(listKey, nodes) { - this._assertUnremoved(); + if (node[VISITED]) return; - nodes = this._verifyNodeList(nodes); + var inferred = (0, _babelHelperFunctionName2.default)(path); + if (inferred && inferred !== node) return path.replaceWith(inferred); - var container = this.node[listKey]; - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: container, - listKey: listKey, - key: container.length - }); + node[VISITED] = true; - return path.replaceWithMultiple(nodes); -} + var Constructor = _vanilla2.default; + if (state.opts.loose) Constructor = _loose2.default; -function hoist() { - var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope; + path.replaceWith(new Constructor(path, state.file).run()); + } + } + }; +}; - var hoister = new _hoister2.default(this, scope); - return hoister.run(); -} -},{"../cache":109,"./index":119,"./lib/hoister":124,"babel-runtime/core-js/get-iterator":89,"babel-runtime/helpers/typeof":107,"babel-types":145}],128:[function(require,module,exports){ -"use strict"; +var _loose = require("./loose"); -exports.__esModule = true; +var _loose2 = _interopRequireDefault(_loose); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _vanilla = require("./vanilla"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var _vanilla2 = _interopRequireDefault(_vanilla); -exports.remove = remove; -exports._callRemovalHooks = _callRemovalHooks; -exports._remove = _remove; -exports._markRemoved = _markRemoved; -exports._assertUnremoved = _assertUnremoved; +var _babelHelperFunctionName = require("babel-helper-function-name"); -var _removalHooks = require("./lib/removal-hooks"); +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function remove() { - this._assertUnremoved(); +module.exports = exports["default"]; +},{"./loose":122,"./vanilla":123,"babel-helper-function-name":109,"babel-runtime/core-js/symbol":136}],122:[function(require,module,exports){ +"use strict"; - this.resync(); +exports.__esModule = true; - if (this._callRemovalHooks()) { - this._markRemoved(); - return; - } +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - this.shareCommentsWithSiblings(); - this._remove(); - this._markRemoved(); -} +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -function _callRemovalHooks() { - for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - var fn = _ref; +var _inherits2 = require("babel-runtime/helpers/inherits"); - if (fn(this, this.parentPath)) return true; - } -} +var _inherits3 = _interopRequireDefault(_inherits2); -function _remove() { - if (Array.isArray(this.container)) { - this.container.splice(this.key, 1); - this.updateSiblingKeys(this.key, -1); - } else { - this._replaceWith(null); - } -} +var _babelHelperFunctionName = require("babel-helper-function-name"); -function _markRemoved() { - this.shouldSkip = true; - this.removed = true; - this.node = null; -} +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); -function _assertUnremoved() { - if (this.removed) { - throw this.buildCodeFrameError("NodePath has been removed so is read-only."); - } -} -},{"./lib/removal-hooks":125,"babel-runtime/core-js/get-iterator":89}],129:[function(require,module,exports){ -"use strict"; +var _vanilla = require("./vanilla"); -exports.__esModule = true; +var _vanilla2 = _interopRequireDefault(_vanilla); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _babelTypes = require("babel-types"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +var t = _interopRequireWildcard(_babelTypes); -exports.replaceWithMultiple = replaceWithMultiple; -exports.replaceWithSourceString = replaceWithSourceString; -exports.replaceWith = replaceWith; -exports._replaceWith = _replaceWith; -exports.replaceExpressionWithStatements = replaceExpressionWithStatements; -exports.replaceInline = replaceInline; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var _babelCodeFrame = require("babel-code-frame"); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); +var LooseClassTransformer = function (_VanillaTransformer) { + (0, _inherits3.default)(LooseClassTransformer, _VanillaTransformer); -var _index = require("../index"); + function LooseClassTransformer() { + (0, _classCallCheck3.default)(this, LooseClassTransformer); -var _index2 = _interopRequireDefault(_index); + var _this = (0, _possibleConstructorReturn3.default)(this, _VanillaTransformer.apply(this, arguments)); -var _index3 = require("./index"); + _this.isLoose = true; + return _this; + } -var _index4 = _interopRequireDefault(_index3); + LooseClassTransformer.prototype._processMethod = function _processMethod(node, scope) { + if (!node.decorators) { -var _babylon = require("babylon"); + var classRef = this.classRef; + if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); + var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); + + var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); + func.returnType = node.returnType; + var key = t.toComputedKey(node, node.key); + if (t.isStringLiteral(key)) { + func = (0, _babelHelperFunctionName2.default)({ + node: func, + id: key, + scope: scope + }); + } + + var expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); + t.inheritsComments(expr, node); + this.body.push(expr); + return true; + } + }; + + return LooseClassTransformer; +}(_vanilla2.default); + +exports.default = LooseClassTransformer; +module.exports = exports["default"]; +},{"./vanilla":123,"babel-helper-function-name":109,"babel-runtime/helpers/classCallCheck":141,"babel-runtime/helpers/inherits":142,"babel-runtime/helpers/possibleConstructorReturn":144,"babel-types":183}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _babelTraverse = require("babel-traverse"); + +var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); + +var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); + +var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + +var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + +var _babelHelperDefineMap = require("babel-helper-define-map"); + +var defineMap = _interopRequireWildcard(_babelHelperDefineMap); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); var _babelTypes = require("babel-types"); @@ -17750,182 +19940,213 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var hoistVariablesVisitor = { - Function: function Function(path) { - path.skip(); +var buildDerivedConstructor = (0, _babelTemplate2.default)("\n (function () {\n super(...arguments);\n })\n"); + +var noMethodVisitor = { + "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { + if (!path.is("shadow")) { + path.skip(); + } }, - VariableDeclaration: function VariableDeclaration(path) { - if (path.node.kind !== "var") return; + Method: function Method(path) { + path.skip(); + } +}; - var bindings = path.getBindingIdentifiers(); - for (var key in bindings) { - path.scope.push({ id: bindings[key] }); +var verifyConstructorVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { + Super: function Super(path) { + if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { + throw path.buildCodeFrameError("'super.*' is not allowed before super()"); } + }, - var exprs = []; - for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + CallExpression: { + exit: function exit(path) { + if (path.get("callee").isSuper()) { + this.hasBareSuper = true; - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + if (!this.isDerived) { + throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); + } } + } + }, - var declar = _ref; - - if (declar.init) { - exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); + ThisExpression: function ThisExpression(path) { + if (this.isDerived && !this.hasBareSuper) { + if (!path.inShadow("this")) { + throw path.buildCodeFrameError("'this' is not allowed before super()"); } } + } +}]); - path.replaceWithMultiple(exprs); +var findThisesVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { + ThisExpression: function ThisExpression(path) { + this.superThises.push(path); } -}; +}]); -function replaceWithMultiple(nodes) { - this.resync(); +var ClassTransformer = function () { + function ClassTransformer(path, file) { + (0, _classCallCheck3.default)(this, ClassTransformer); - nodes = this._verifyNodeList(nodes); - t.inheritLeadingComments(nodes[0], this.node); - t.inheritTrailingComments(nodes[nodes.length - 1], this.node); - this.node = this.container[this.key] = null; - this.insertAfter(nodes); + this.parent = path.parent; + this.scope = path.scope; + this.node = path.node; + this.path = path; + this.file = file; - if (this.node) { - this.requeue(); - } else { - this.remove(); - } -} + this.clearDescriptors(); -function replaceWithSourceString(replacement) { - this.resync(); + this.instancePropBody = []; + this.instancePropRefs = {}; + this.staticPropBody = []; + this.body = []; - try { - replacement = "(" + replacement + ")"; - replacement = (0, _babylon.parse)(replacement); - } catch (err) { - var loc = err.loc; - if (loc) { - err.message += " - make sure this is an expression."; - err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); - } - throw err; - } + this.bareSuperAfter = []; + this.bareSupers = []; - replacement = replacement.program.body[0].expression; - _index2.default.removeProperties(replacement); - return this.replaceWith(replacement); -} + this.pushedConstructor = false; + this.pushedInherits = false; + this.isLoose = false; -function replaceWith(replacement) { - this.resync(); + this.superThises = []; - if (this.removed) { - throw new Error("You can't replace this node, we've already removed it"); - } + this.classId = this.node.id; - if (replacement instanceof _index4.default) { - replacement = replacement.node; - } + this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class"); - if (!replacement) { - throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); + this.superName = this.node.superClass || t.identifier("Function"); + this.isDerived = !!this.node.superClass; } - if (this.node === replacement) { - return; - } + ClassTransformer.prototype.run = function run() { + var _this = this; - if (this.isProgram() && !t.isProgram(replacement)) { - throw new Error("You can only replace a Program root node with another Program node"); - } + var superName = this.superName; + var file = this.file; + var body = this.body; - if (Array.isArray(replacement)) { - throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); - } + var constructorBody = this.constructorBody = t.blockStatement([]); + this.constructor = this.buildConstructor(); - if (typeof replacement === "string") { - throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); - } + var closureParams = []; + var closureArgs = []; - if (this.isNodeType("Statement") && t.isExpression(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - replacement = t.expressionStatement(replacement); + if (this.isDerived) { + closureArgs.push(superName); + + superName = this.scope.generateUidIdentifierBasedOnNode(superName); + closureParams.push(superName); + + this.superName = superName; } - } - if (this.isNodeType("Expression") && t.isStatement(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - return this.replaceExpressionWithStatements([replacement]); + this.buildBody(); + + constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [t.thisExpression(), this.classRef]))); + + body = body.concat(this.staticPropBody.map(function (fn) { + return fn(_this.classRef); + })); + + if (this.classId) { + if (body.length === 1) return t.toExpression(body[0]); } - } - var oldNode = this.node; - if (oldNode) { - t.inheritsComments(replacement, oldNode); - t.removeComments(oldNode); - } + body.push(t.returnStatement(this.classRef)); - this._replaceWith(replacement); - this.type = replacement.type; + var container = t.functionExpression(null, closureParams, t.blockStatement(body)); + container.shadow = true; + return t.callExpression(container, closureArgs); + }; - this.setScope(); + ClassTransformer.prototype.buildConstructor = function buildConstructor() { + var func = t.functionDeclaration(this.classRef, [], this.constructorBody); + t.inherits(func, this.node); + return func; + }; - this.requeue(); -} + ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { + var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "value"; + var scope = arguments[3]; -function _replaceWith(node) { - if (!this.container) { - throw new ReferenceError("Container is falsy"); - } + var mutatorMap = void 0; + if (node.static) { + this.hasStaticDescriptors = true; + mutatorMap = this.staticMutatorMap; + } else { + this.hasInstanceDescriptors = true; + mutatorMap = this.instanceMutatorMap; + } - if (this.inList) { - t.validate(this.parent, this.key, [node]); - } else { - t.validate(this.parent, this.key, node); - } + var map = defineMap.push(mutatorMap, node, kind, this.file, scope); - this.debug(function () { - return "Replace with " + (node && node.type); - }); + if (enumerable) { + map.enumerable = t.booleanLiteral(true); + } - this.node = this.container[this.key] = node; -} + return map; + }; -function replaceExpressionWithStatements(nodes) { - this.resync(); + ClassTransformer.prototype.constructorMeMaybe = function constructorMeMaybe() { + var hasConstructor = false; + var paths = this.path.get("body.body"); + for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - if (t.isSequenceExpression(toSequenceExpression)) { - var exprs = toSequenceExpression.expressions; + var path = _ref; - if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { - this._maybePopFromStatements(exprs); + hasConstructor = path.equals("kind", "constructor"); + if (hasConstructor) break; } + if (hasConstructor) return; - if (exprs.length === 1) { - this.replaceWith(exprs[0]); + var params = void 0, + body = void 0; + + if (this.isDerived) { + var _constructor = buildDerivedConstructor().expression; + params = _constructor.params; + body = _constructor.body; } else { - this.replaceWith(toSequenceExpression); + params = []; + body = t.blockStatement([]); } - } else if (toSequenceExpression) { - this.replaceWith(toSequenceExpression); - } else { - var container = t.functionExpression(null, [], t.blockStatement(nodes)); - container.shadow = true; - this.replaceWith(t.callExpression(container, [])); - this.traverse(hoistVariablesVisitor); + this.path.get("body").unshiftContainer("body", t.classMethod("constructor", t.identifier("constructor"), params, body)); + }; - var completionRecords = this.get("callee").getCompletionRecords(); - for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + ClassTransformer.prototype.buildBody = function buildBody() { + this.constructorMeMaybe(); + this.pushBody(); + this.verifyConstructor(); + + if (this.userConstructor) { + var constructorBody = this.constructorBody; + constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); + t.inherits(this.constructor, this.userConstructor); + t.inherits(constructorBody, this.userConstructor.body); + } + + this.pushDescriptors(); + }; + + ClassTransformer.prototype.pushBody = function pushBody() { + var classBodyPaths = this.path.get("body.body"); + + for (var _iterator2 = classBodyPaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { var _ref2; if (_isArray2) { @@ -17939,264 +20160,165 @@ function replaceExpressionWithStatements(nodes) { var path = _ref2; - if (!path.isExpressionStatement()) continue; + var node = path.node; - var loop = path.findParent(function (path) { - return path.isLoop(); - }); - if (loop) { - var uid = loop.getData("expressionReplacementReturnUid"); + if (path.isClassProperty()) { + throw path.buildCodeFrameError("Missing class properties transform."); + } - if (!uid) { - var callee = this.get("callee"); - uid = callee.scope.generateDeclaredUidIdentifier("ret"); - callee.get("body").pushContainer("body", t.returnStatement(uid)); - loop.setData("expressionReplacementReturnUid", uid); - } else { - uid = t.identifier(uid.name); + if (node.decorators) { + throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); + } + + if (t.isClassMethod(node)) { + var isConstructor = node.kind === "constructor"; + + if (isConstructor) { + path.traverse(verifyConstructorVisitor, this); + + if (!this.hasBareSuper && this.isDerived) { + throw path.buildCodeFrameError("missing super() call in constructor"); + } } - path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); - } else { - path.replaceWith(t.returnStatement(path.node.expression)); + var replaceSupers = new _babelHelperReplaceSupers2.default({ + forceSuperMemoisation: isConstructor, + methodPath: path, + methodNode: node, + objectRef: this.classRef, + superRef: this.superName, + isStatic: node.static, + isLoose: this.isLoose, + scope: this.scope, + file: this.file + }, true); + + replaceSupers.replace(); + + if (isConstructor) { + this.pushConstructor(replaceSupers, node, path); + } else { + this.pushMethod(node, path); + } } } + }; - return this.node; - } -} + ClassTransformer.prototype.clearDescriptors = function clearDescriptors() { + this.hasInstanceDescriptors = false; + this.hasStaticDescriptors = false; -function replaceInline(nodes) { - this.resync(); + this.instanceMutatorMap = {}; + this.staticMutatorMap = {}; + }; - if (Array.isArray(nodes)) { - if (Array.isArray(this.container)) { - nodes = this._verifyNodeList(nodes); - this._containerInsertAfter(nodes); - return this.remove(); - } else { - return this.replaceWithMultiple(nodes); - } - } else { - return this.replaceWith(nodes); - } -} -},{"../index":112,"./index":119,"babel-code-frame":25,"babel-runtime/core-js/get-iterator":89,"babel-types":145,"babylon":149}],130:[function(require,module,exports){ -"use strict"; + ClassTransformer.prototype.pushDescriptors = function pushDescriptors() { + this.pushInherits(); -exports.__esModule = true; + var body = this.body; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + var instanceProps = void 0; + var staticProps = void 0; -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + if (this.hasInstanceDescriptors) { + instanceProps = defineMap.toClassObject(this.instanceMutatorMap); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.hasStaticDescriptors) { + staticProps = defineMap.toClassObject(this.staticMutatorMap); + } -var Binding = function () { - function Binding(_ref) { - var existing = _ref.existing, - identifier = _ref.identifier, - scope = _ref.scope, - path = _ref.path, - kind = _ref.kind; - (0, _classCallCheck3.default)(this, Binding); + if (instanceProps || staticProps) { + if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); + if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); - this.identifier = identifier; - this.scope = scope; - this.path = path; - this.kind = kind; + var nullNode = t.nullLiteral(); - this.constantViolations = []; - this.constant = true; + var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; - this.referencePaths = []; - this.referenced = false; - this.references = 0; + if (instanceProps) args[1] = instanceProps; + if (staticProps) args[2] = staticProps; - this.clearValue(); + if (this.instanceInitializersId) { + args[3] = this.instanceInitializersId; + body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); + } - if (existing) { - this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); - } - } + if (this.staticInitializersId) { + args[4] = this.staticInitializersId; + body.unshift(this.buildObjectAssignment(this.staticInitializersId)); + } - Binding.prototype.deoptValue = function deoptValue() { - this.clearValue(); - this.hasDeoptedValue = true; - }; + var lastNonNullIndex = 0; + for (var i = 0; i < args.length; i++) { + if (args[i] !== nullNode) lastNonNullIndex = i; + } + args = args.slice(0, lastNonNullIndex + 1); - Binding.prototype.setValue = function setValue(value) { - if (this.hasDeoptedValue) return; - this.hasValue = true; - this.value = value; + body.push(t.expressionStatement(t.callExpression(this.file.addHelper("createClass"), args))); + } + + this.clearDescriptors(); }; - Binding.prototype.clearValue = function clearValue() { - this.hasDeoptedValue = false; - this.hasValue = false; - this.value = null; + ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { + return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); }; - Binding.prototype.reassign = function reassign(path) { - this.constant = false; - if (this.constantViolations.indexOf(path) !== -1) { - return; - } - this.constantViolations.push(path); - }; + ClassTransformer.prototype.wrapSuperCall = function wrapSuperCall(bareSuper, superRef, thisRef, body) { + var bareSuperNode = bareSuper.node; - Binding.prototype.reference = function reference(path) { - if (this.referencePaths.indexOf(path) !== -1) { - return; + if (this.isLoose) { + bareSuperNode.arguments.unshift(t.thisExpression()); + if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { + bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; + bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); + } else { + bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); + } + } else { + bareSuperNode = (0, _babelHelperOptimiseCallExpression2.default)(t.logicalExpression("||", t.memberExpression(this.classRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef])), t.thisExpression(), bareSuperNode.arguments); } - this.referenced = true; - this.references++; - this.referencePaths.push(path); - }; - - Binding.prototype.dereference = function dereference() { - this.references--; - this.referenced = !!this.references; - }; - - return Binding; -}(); - -exports.default = Binding; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":103}],131:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); -var _repeat = require("lodash/repeat"); - -var _repeat2 = _interopRequireDefault(_repeat); - -var _renamer = require("./lib/renamer"); - -var _renamer2 = _interopRequireDefault(_renamer); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _defaults = require("lodash/defaults"); - -var _defaults2 = _interopRequireDefault(_defaults); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _binding2 = require("./binding"); - -var _binding3 = _interopRequireDefault(_binding2); - -var _globals = require("globals"); - -var _globals2 = _interopRequireDefault(_globals); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("../cache"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var call = t.callExpression(this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode]); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var bareSuperAfter = this.bareSuperAfter.map(function (fn) { + return fn(thisRef); + }); -var _crawlCallsCount = 0; + if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { -function getCache(path, parentScope, self) { - var scopes = _cache.scope.get(path.node) || []; + if (this.superThises.length || bareSuperAfter.length) { + bareSuper.scope.push({ id: thisRef }); + call = t.assignmentExpression("=", thisRef, call); + } - for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (bareSuperAfter.length) { + call = t.toSequenceExpression([call].concat(bareSuperAfter, [thisRef])); + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; + bareSuper.parentPath.replaceWith(t.returnStatement(call)); } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; + bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(thisRef, call)])].concat(bareSuperAfter, [t.expressionStatement(thisRef)])); } + }; - var scope = _ref; - - if (scope.parent === parentScope && scope.path === path) return scope; - } + ClassTransformer.prototype.verifyConstructor = function verifyConstructor() { + var _this2 = this; - scopes.push(self); + if (!this.isDerived) return; - if (!_cache.scope.has(path.node)) { - _cache.scope.set(path.node, scopes); - } -} + var path = this.userConstructorPath; + var body = path.get("body"); -function gatherNodeParts(node, parts) { - if (t.isModuleDeclaration(node)) { - if (node.source) { - gatherNodeParts(node.source, parts); - } else if (node.specifiers && node.specifiers.length) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + path.traverse(findThisesVisitor, this); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + var guaranteedSuperBeforeFinish = !!this.bareSupers.length; - var specifier = _ref2; + var superRef = this.superName || t.identifier("Function"); + var thisRef = path.scope.generateUidIdentifier("this"); - gatherNodeParts(specifier, parts); - } - } else if (node.declaration) { - gatherNodeParts(node.declaration, parts); - } - } else if (t.isModuleSpecifier(node)) { - gatherNodeParts(node.local, parts); - } else if (t.isMemberExpression(node)) { - gatherNodeParts(node.object, parts); - gatherNodeParts(node.property, parts); - } else if (t.isIdentifier(node)) { - parts.push(node.name); - } else if (t.isLiteral(node)) { - parts.push(node.value); - } else if (t.isCallExpression(node)) { - gatherNodeParts(node.callee, parts); - } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + for (var _iterator3 = this.bareSupers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { var _ref3; if (_isArray3) { @@ -18208,16 +20330,25 @@ function gatherNodeParts(node, parts) { _ref3 = _i3.value; } - var prop = _ref3; + var bareSuper = _ref3; - gatherNodeParts(prop.key || prop.argument, parts); + this.wrapSuperCall(bareSuper, superRef, thisRef, body); + + if (guaranteedSuperBeforeFinish) { + bareSuper.find(function (parentPath) { + if (parentPath === path) { + return true; + } + + if (parentPath.isLoop() || parentPath.isConditional()) { + guaranteedSuperBeforeFinish = false; + return true; + } + }); + } } - } -} -var collectorVisitor = { - For: function For(path) { - for (var _iterator4 = t.FOR_INIT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + for (var _iterator4 = this.superThises, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { var _ref4; if (_isArray4) { @@ -18229,948 +20360,871 @@ var collectorVisitor = { _ref4 = _i4.value; } - var key = _ref4; + var thisPath = _ref4; - var declar = path.get(key); - if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); + thisPath.replaceWith(thisRef); } - }, - Declaration: function Declaration(path) { - if (path.isBlockScoped()) return; - if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; + var wrapReturn = function wrapReturn(returnArg) { + return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || [])); + }; - path.scope.getFunctionParent().registerDeclaration(path); - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - state.references.push(path); - }, - ForXStatement: function ForXStatement(path, state) { - var left = path.get("left"); - if (left.isPattern() || left.isIdentifier()) { - state.constantViolations.push(left); + var bodyPaths = body.get("body"); + if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { + body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); } - }, - - - ExportDeclaration: { - exit: function exit(path) { - var node = path.node, - scope = path.scope; - - var declar = node.declaration; - if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { - var _id = declar.id; - if (!_id) return; - var binding = scope.getBinding(_id.name); - if (binding) binding.reference(path); - } else if (t.isVariableDeclaration(declar)) { - for (var _iterator5 = declar.declarations, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + for (var _iterator5 = this.superReturns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } - var decl = _ref5; + var returnPath = _ref5; - var ids = t.getBindingIdentifiers(decl); - for (var name in ids) { - var _binding = scope.getBinding(name); - if (_binding) _binding.reference(path); - } - } + if (returnPath.node.argument) { + var ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); + returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref)]); + } else { + returnPath.get("argument").replaceWith(wrapReturn()); } } - }, + }; - LabeledStatement: function LabeledStatement(path) { - path.scope.getProgramParent().addGlobal(path.node); - path.scope.getBlockParent().registerDeclaration(path); - }, - AssignmentExpression: function AssignmentExpression(path, state) { - state.assignments.push(path); - }, - UpdateExpression: function UpdateExpression(path, state) { - state.constantViolations.push(path.get("argument")); - }, - UnaryExpression: function UnaryExpression(path, state) { - if (path.node.operator === "delete") { - state.constantViolations.push(path.get("argument")); + ClassTransformer.prototype.pushMethod = function pushMethod(node, path) { + var scope = path ? path.scope : this.scope; + + if (node.kind === "method") { + if (this._processMethod(node, scope)) return; } - }, - BlockScoped: function BlockScoped(path) { - var scope = path.scope; - if (scope.path === path) scope = scope.parent; - scope.getBlockParent().registerDeclaration(path); - }, - ClassDeclaration: function ClassDeclaration(path) { - var id = path.node.id; - if (!id) return; - var name = id.name; - path.scope.bindings[name] = path.scope.getBinding(name); - }, - Block: function Block(path) { - var paths = path.get("body"); - for (var _iterator6 = paths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; + this.pushToMap(node, false, null, scope); + }; - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } + ClassTransformer.prototype._processMethod = function _processMethod() { + return false; + }; - var bodyPath = _ref6; + ClassTransformer.prototype.pushConstructor = function pushConstructor(replaceSupers, method, path) { + this.bareSupers = replaceSupers.bareSupers; + this.superReturns = replaceSupers.returns; - if (bodyPath.isFunctionDeclaration()) { - path.scope.getBlockParent().registerDeclaration(bodyPath); - } + if (path.scope.hasOwnBinding(this.classRef.name)) { + path.scope.rename(this.classRef.name); } - } -}; -var uid = 0; + var construct = this.constructor; -var Scope = function () { - function Scope(path, parentScope) { - (0, _classCallCheck3.default)(this, Scope); + this.userConstructorPath = path; + this.userConstructor = method; + this.hasConstructor = true; - if (parentScope && parentScope.block === path.node) { - return parentScope; - } + t.inheritsComments(construct, method); - var cached = getCache(path, parentScope, this); - if (cached) return cached; + construct._ignoreUserWhitespace = true; + construct.params = method.params; - this.uid = uid++; - this.parent = parentScope; - this.hub = path.hub; + t.inherits(construct.body, method.body); + construct.body.directives = method.body.directives; - this.parentBlock = path.parent; - this.block = path.node; - this.path = path; + this._pushConstructor(); + }; - this.labels = new _map2.default(); - } + ClassTransformer.prototype._pushConstructor = function _pushConstructor() { + if (this.pushedConstructor) return; + this.pushedConstructor = true; - Scope.prototype.traverse = function traverse(node, opts, state) { - (0, _index2.default)(node, opts, this, state, this.path); - }; + if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { + this.pushDescriptors(); + } - Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + this.body.push(this.constructor); - var id = this.generateUidIdentifier(name); - this.push({ id: id }); - return id; + this.pushInherits(); }; - Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + ClassTransformer.prototype.pushInherits = function pushInherits() { + if (!this.isDerived || this.pushedInherits) return; - return t.identifier(this.generateUid(name)); + this.pushedInherits = true; + this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"), [this.classRef, this.superName]))); }; - Scope.prototype.generateUid = function generateUid() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); + return ClassTransformer; +}(); - var uid = void 0; - var i = 0; - do { - uid = this._generateUid(name, i); - i++; - } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); +exports.default = ClassTransformer; +module.exports = exports["default"]; +},{"babel-helper-define-map":108,"babel-helper-optimise-call-expression":111,"babel-helper-replace-supers":112,"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/classCallCheck":141,"babel-template":146,"babel-traverse":150,"babel-types":183}],124:[function(require,module,exports){ +"use strict"; - var program = this.getProgramParent(); - program.references[uid] = true; - program.uids[uid] = true; +exports.__esModule = true; - return uid; - }; +exports.default = function (_ref) { + var messages = _ref.messages, + template = _ref.template, + t = _ref.types; - Scope.prototype._generateUid = function _generateUid(name, i) { - var id = name; - if (i > 1) id += i; - return "_" + id; - }; + var buildForOfArray = template("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "); - Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { - var node = parent; + var buildForOfLoose = template("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "); - if (t.isAssignmentExpression(parent)) { - node = parent.left; - } else if (t.isVariableDeclarator(parent)) { - node = parent.id; - } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { - node = node.key; - } + var buildForOf = template("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n "); - var parts = []; - gatherNodeParts(node, parts); - var id = parts.join("$"); - id = id.replace(/^_/, "") || defaultName || "ref"; + function _ForOfStatementArray(path) { + var node = path.node, + scope = path.scope; - return this.generateUidIdentifier(id.slice(0, 20)); - }; + var nodes = []; + var right = node.right; - Scope.prototype.isStatic = function isStatic(node) { - if (t.isThisExpression(node) || t.isSuper(node)) { - return true; + if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { + var uid = scope.generateUidIdentifier("arr"); + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)])); + right = uid; } - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding) { - return binding.constant; - } else { - return this.hasBinding(node.name); - } - } + var iterationKey = scope.generateUidIdentifier("i"); - return false; - }; + var loop = buildForOfArray({ + BODY: node.body, + KEY: iterationKey, + ARR: right + }); - Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { - if (this.isStatic(node)) { - return null; + t.inherits(loop, node); + t.ensureBlock(loop); + + var iterationValue = t.memberExpression(right, iterationKey, true); + + var left = node.left; + if (t.isVariableDeclaration(left)) { + left.declarations[0].init = iterationValue; + loop.body.body.unshift(left); } else { - var _id2 = this.generateUidIdentifierBasedOnNode(node); - if (!dontPush) this.push({ id: _id2 }); - return _id2; + loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue))); } - }; - Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { - if (kind === "param") return; + if (path.parentPath.isLabeledStatement()) { + loop = t.labeledStatement(path.parentPath.node.label, loop); + } - if (kind === "hoisted" && local.kind === "let") return; + nodes.push(loop); - var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); + return nodes; + } - if (duplicate) { - throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); - } - }; + return { + visitor: { + ForOfStatement: function ForOfStatement(path, state) { + if (path.get("right").isArrayExpression()) { + if (path.parentPath.isLabeledStatement()) { + return path.parentPath.replaceWithMultiple(_ForOfStatementArray(path)); + } else { + return path.replaceWithMultiple(_ForOfStatementArray(path)); + } + } - Scope.prototype.rename = function rename(oldName, newName, block) { - var binding = this.getBinding(oldName); - if (binding) { - newName = newName || this.generateUidIdentifier(oldName).name; - return new _renamer2.default(binding, oldName, newName).rename(block); - } - }; + var callback = spec; + if (state.opts.loose) callback = loose; - Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { - if (map[oldName]) { - map[newName] = value; - map[oldName] = null; - } - }; + var node = path.node; - Scope.prototype.dump = function dump() { - var sep = (0, _repeat2.default)("-", 60); - console.log(sep); - var scope = this; - do { - console.log("#", scope.block.type); - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - console.log(" -", name, { - constant: binding.constant, - references: binding.references, - violations: binding.constantViolations.length, - kind: binding.kind - }); - } - } while (scope = scope.parent); - console.log(sep); - }; + var build = callback(path, state); + var declar = build.declar; + var loop = build.loop; + var block = loop.body; - Scope.prototype.toArray = function toArray(node, i) { - var file = this.hub.file; + path.ensureBlock(); - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding && binding.constant && binding.path.isGenericType("Array")) return node; - } + if (declar) { + block.body.push(declar); + } - if (t.isArrayExpression(node)) { - return node; - } + block.body = block.body.concat(node.body.body); - if (t.isIdentifier(node, { name: "arguments" })) { - return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); - } + t.inherits(loop, node); + t.inherits(loop.body, node.body); - var helperName = "toArray"; - var args = [node]; - if (i === true) { - helperName = "toConsumableArray"; - } else if (i) { - args.push(t.numericLiteral(i)); - helperName = "slicedToArray"; + if (build.replaceParent) { + path.parentPath.replaceWithMultiple(build.node); + path.remove(); + } else { + path.replaceWithMultiple(build.node); + } + } } - return t.callExpression(file.addHelper(helperName), args); }; - Scope.prototype.hasLabel = function hasLabel(name) { - return !!this.getLabel(name); - }; + function loose(path, file) { + var node = path.node, + scope = path.scope, + parent = path.parent; + var left = node.left; - Scope.prototype.getLabel = function getLabel(name) { - return this.labels.get(name); - }; + var declar = void 0, + id = void 0; - Scope.prototype.registerLabel = function registerLabel(path) { - this.labels.set(path.node.label.name, path); - }; + if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { + id = left; + } else if (t.isVariableDeclaration(left)) { + id = scope.generateUidIdentifier("ref"); + declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]); + } else { + throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + } - Scope.prototype.registerDeclaration = function registerDeclaration(path) { - if (path.isLabeledStatement()) { - this.registerLabel(path); - } else if (path.isFunctionDeclaration()) { - this.registerBinding("hoisted", path.get("id"), path); - } else if (path.isVariableDeclaration()) { - var declarations = path.get("declarations"); - for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; + var iteratorKey = scope.generateUidIdentifier("iterator"); + var isArrayKey = scope.generateUidIdentifier("isArray"); - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } + var loop = buildForOfLoose({ + LOOP_OBJECT: iteratorKey, + IS_ARRAY: isArrayKey, + OBJECT: node.right, + INDEX: scope.generateUidIdentifier("i"), + ID: id + }); - var declar = _ref7; + if (!declar) { + loop.body.body.shift(); + } - this.registerBinding(path.node.kind, declar); - } - } else if (path.isClassDeclaration()) { - this.registerBinding("let", path); - } else if (path.isImportDeclaration()) { - var specifiers = path.get("specifiers"); - for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; + var isLabeledParent = t.isLabeledStatement(parent); + var labeled = void 0; - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } + if (isLabeledParent) { + labeled = t.labeledStatement(parent.label, loop); + } - var specifier = _ref8; + return { + replaceParent: isLabeledParent, + declar: declar, + node: labeled || loop, + loop: loop + }; + } - this.registerBinding("module", specifier); - } - } else if (path.isExportDeclaration()) { - var _declar = path.get("declaration"); - if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { - this.registerDeclaration(_declar); - } - } else { - this.registerBinding("unknown", path); - } - }; + function spec(path, file) { + var node = path.node, + scope = path.scope, + parent = path.parent; - Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { - if (this.hasBinding("undefined")) { - return t.unaryExpression("void", t.numericLiteral(0), true); - } else { - return t.identifier("undefined"); - } - }; + var left = node.left; + var declar = void 0; - Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = this.getBinding(name); - if (binding) binding.reassign(path); - } - }; + var stepKey = scope.generateUidIdentifier("step"); + var stepValue = t.memberExpression(stepKey, t.identifier("value")); - Scope.prototype.registerBinding = function registerBinding(kind, path) { - var bindingPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : path; + if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { + declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); + } else if (t.isVariableDeclaration(left)) { + declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); + } else { + throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + } - if (!kind) throw new ReferenceError("no `kind`"); + var iteratorKey = scope.generateUidIdentifier("iterator"); - if (path.isVariableDeclaration()) { - var declarators = path.get("declarations"); - for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; + var template = buildForOf({ + ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), + ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), + ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), + ITERATOR_KEY: iteratorKey, + STEP_KEY: stepKey, + OBJECT: node.right, + BODY: null + }); - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } + var isLabeledParent = t.isLabeledStatement(parent); - var declar = _ref9; + var tryBody = template[3].block.body; + var loop = tryBody[0]; - this.registerBinding(kind, declar); - } - return; + if (isLabeledParent) { + tryBody[0] = t.labeledStatement(parent.label, loop); } - var parent = this.getProgramParent(); - var ids = path.getBindingIdentifiers(true); + return { + replaceParent: isLabeledParent, + declar: declar, + loop: loop, + node: template + }; + } +}; - for (var name in ids) { - for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; +module.exports = exports["default"]; +},{}],125:[function(require,module,exports){ +"use strict"; - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } +exports.__esModule = true; - var _id3 = _ref10; +var _keys = require("babel-runtime/core-js/object/keys"); - var local = this.getOwnBinding(name); - if (local) { - if (local.identifier === _id3) continue; +var _keys2 = _interopRequireDefault(_keys); - this.checkBlockScopedCollisions(local, kind, name, _id3); - } +var _create = require("babel-runtime/core-js/object/create"); - if (local && local.path.isFlow()) local = null; +var _create2 = _interopRequireDefault(_create); - parent.references[name] = true; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - this.bindings[name] = new _binding3.default({ - identifier: _id3, - existing: local, - scope: this, - path: bindingPath, - kind: kind - }); - } - } - }; +var _getIterator3 = _interopRequireDefault(_getIterator2); - Scope.prototype.addGlobal = function addGlobal(node) { - this.globals[node.name] = node; - }; +var _symbol = require("babel-runtime/core-js/symbol"); - Scope.prototype.hasUid = function hasUid(name) { - var scope = this; +var _symbol2 = _interopRequireDefault(_symbol); - do { - if (scope.uids[name]) return true; - } while (scope = scope.parent); +exports.default = function () { + var REASSIGN_REMAP_SKIP = (0, _symbol2.default)(); - return false; - }; + var reassignmentVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path) { + var name = path.node.name; + var remap = this.remaps[name]; + if (!remap) return; - Scope.prototype.hasGlobal = function hasGlobal(name) { - var scope = this; + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - do { - if (scope.globals[name]) return true; - } while (scope = scope.parent); + if (path.parentPath.isCallExpression({ callee: path.node })) { + path.replaceWith(t.sequenceExpression([t.numericLiteral(0), remap])); + } else if (path.isJSXIdentifier() && t.isMemberExpression(remap)) { + var object = remap.object, + property = remap.property; - return false; - }; + path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name))); + } else { + path.replaceWith(remap); + } + this.requeueInParent(path); + }, + AssignmentExpression: function AssignmentExpression(path) { + var node = path.node; + if (node[REASSIGN_REMAP_SKIP]) return; - Scope.prototype.hasReference = function hasReference(name) { - var scope = this; + var left = path.get("left"); + if (!left.isIdentifier()) return; - do { - if (scope.references[name]) return true; - } while (scope = scope.parent); + var name = left.node.name; + var exports = this.exports[name]; + if (!exports) return; - return false; - }; + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - Scope.prototype.isPure = function isPure(node, constantsOnly) { - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (!binding) return false; - if (constantsOnly) return binding.constant; - return true; - } else if (t.isClass(node)) { - if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; - return this.isPure(node.body, constantsOnly); - } else if (t.isClassBody(node)) { - for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) { - var _ref11; + node[REASSIGN_REMAP_SKIP] = true; - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref11 = _iterator11[_i11++]; + for (var _iterator = exports, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref11 = _i11.value; + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } - var method = _ref11; + var reid = _ref; - if (!this.isPure(method, constantsOnly)) return false; + node = buildExportsAssignment(reid, node).expression; } - return true; - } else if (t.isBinary(node)) { - return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); - } else if (t.isArrayExpression(node)) { - for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) { - var _ref12; - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref12 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref12 = _i12.value; - } + path.replaceWith(node); + this.requeueInParent(path); + }, + UpdateExpression: function UpdateExpression(path) { + var arg = path.get("argument"); + if (!arg.isIdentifier()) return; - var elem = _ref12; + var name = arg.node.name; + var exports = this.exports[name]; + if (!exports) return; - if (!this.isPure(elem, constantsOnly)) return false; - } - return true; - } else if (t.isObjectExpression(node)) { - for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) { - var _ref13; + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref13 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref13 = _i13.value; - } + var node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); - var prop = _ref13; + if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord() || path.node.prefix) { + path.replaceWith(node); + this.requeueInParent(path); + return; + } - if (!this.isPure(prop, constantsOnly)) return false; + var nodes = []; + nodes.push(node); + + var operator = void 0; + if (path.node.operator === "--") { + operator = "+"; + } else { + operator = "-"; } - return true; - } else if (t.isClassMethod(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - if (node.kind === "get" || node.kind === "set") return false; - return true; - } else if (t.isClassProperty(node) || t.isObjectProperty(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - return this.isPure(node.value, constantsOnly); - } else if (t.isUnaryExpression(node)) { - return this.isPure(node.argument, constantsOnly); - } else { - return t.isPureish(node); + nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); + + path.replaceWithMultiple(t.sequenceExpression(nodes)); } }; - Scope.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; + return { + inherits: require("babel-plugin-transform-strict-mode"), - Scope.prototype.getData = function getData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) return data; - } while (scope = scope.parent); - }; + visitor: { + ThisExpression: function ThisExpression(path, state) { + if (this.ranCommonJS) return; - Scope.prototype.removeData = function removeData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) scope.data[key] = null; - } while (scope = scope.parent); - }; + if (state.opts.allowTopLevelThis !== true && !path.findParent(function (path) { + return !path.is("shadow") && THIS_BREAK_KEYS.indexOf(path.type) >= 0; + })) { + path.replaceWith(t.identifier("undefined")); + } + }, - Scope.prototype.init = function init() { - if (!this.references) this.crawl(); - }; - Scope.prototype.crawl = function crawl() { - _crawlCallsCount++; - this._crawl(); - _crawlCallsCount--; - }; + Program: { + exit: function exit(path) { + this.ranCommonJS = true; - Scope.prototype._crawl = function _crawl() { - var path = this.path; + var strict = !!this.opts.strict; + var noInterop = !!this.opts.noInterop; - this.references = (0, _create2.default)(null); - this.bindings = (0, _create2.default)(null); - this.globals = (0, _create2.default)(null); - this.uids = (0, _create2.default)(null); - this.data = (0, _create2.default)(null); + var scope = path.scope; - if (path.isLoop()) { - for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) { - var _ref14; + scope.rename("module"); + scope.rename("exports"); + scope.rename("require"); - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref14 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref14 = _i14.value; - } + var hasExports = false; + var hasImports = false; - var key = _ref14; + var body = path.get("body"); + var imports = (0, _create2.default)(null); + var exports = (0, _create2.default)(null); - var node = path.get(key); - if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); - } - } + var nonHoistedExportNames = (0, _create2.default)(null); - if (path.isFunctionExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path.get("id"), path); - } - } + var topNodes = []; + var remaps = (0, _create2.default)(null); - if (path.isClassExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path); - } - } + var requires = (0, _create2.default)(null); - if (path.isFunction()) { - var params = path.get("params"); - for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) { - var _ref15; + function addRequire(source, blockHoist) { + var cached = requires[source]; + if (cached) return cached; - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref15 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref15 = _i15.value; - } + var ref = path.scope.generateUidIdentifier((0, _path2.basename)(source, (0, _path2.extname)(source))); - var param = _ref15; + var varDecl = t.variableDeclaration("var", [t.variableDeclarator(ref, buildRequire(t.stringLiteral(source)).expression)]); - this.registerBinding("param", param); - } - } + if (imports[source]) { + varDecl.loc = imports[source].loc; + } - if (path.isCatchClause()) { - this.registerBinding("let", path); - } + if (typeof blockHoist === "number" && blockHoist > 0) { + varDecl._blockHoist = blockHoist; + } - var parent = this.getProgramParent(); - if (parent.crawling) return; + topNodes.push(varDecl); - var state = { - references: [], - constantViolations: [], - assignments: [] - }; + return requires[source] = ref; + } - this.crawling = true; - path.traverse(collectorVisitor, state); - this.crawling = false; + function addTo(obj, key, arr) { + var existing = obj[key] || []; + obj[key] = existing.concat(arr); + } - for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) { - var _ref16; + for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - if (_isArray16) { - if (_i16 >= _iterator16.length) break; - _ref16 = _iterator16[_i16++]; - } else { - _i16 = _iterator16.next(); - if (_i16.done) break; - _ref16 = _i16.value; - } + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } - var _path = _ref16; + var _path = _ref2; - var ids = _path.getBindingIdentifiers(); - var programParent = void 0; - for (var name in ids) { - if (_path.scope.getBinding(name)) continue; + if (_path.isExportDeclaration()) { + hasExports = true; - programParent = programParent || _path.scope.getProgramParent(); - programParent.addGlobal(ids[name]); - } + var specifiers = [].concat(_path.get("declaration"), _path.get("specifiers")); + for (var _iterator4 = specifiers, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; - _path.scope.registerConstantViolation(_path); - } + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } - for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) { - var _ref17; + var _specifier2 = _ref4; - if (_isArray17) { - if (_i17 >= _iterator17.length) break; - _ref17 = _iterator17[_i17++]; - } else { - _i17 = _iterator17.next(); - if (_i17.done) break; - _ref17 = _i17.value; - } + var ids = _specifier2.getBindingIdentifiers(); + if (ids.__esModule) { + throw _specifier2.buildCodeFrameError("Illegal export \"__esModule\""); + } + } + } - var ref = _ref17; + if (_path.isImportDeclaration()) { + var _importsEntry$specifi; - var binding = ref.scope.getBinding(ref.node.name); - if (binding) { - binding.reference(ref); - } else { - ref.scope.getProgramParent().addGlobal(ref.node); - } - } + hasImports = true; - for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) { - var _ref18; + var key = _path.node.source.value; + var importsEntry = imports[key] || { + specifiers: [], + maxBlockHoist: 0, + loc: _path.node.loc + }; - if (_isArray18) { - if (_i18 >= _iterator18.length) break; - _ref18 = _iterator18[_i18++]; - } else { - _i18 = _iterator18.next(); - if (_i18.done) break; - _ref18 = _i18.value; - } + (_importsEntry$specifi = importsEntry.specifiers).push.apply(_importsEntry$specifi, _path.node.specifiers); - var _path2 = _ref18; + if (typeof _path.node._blockHoist === "number") { + importsEntry.maxBlockHoist = Math.max(_path.node._blockHoist, importsEntry.maxBlockHoist); + } - _path2.scope.registerConstantViolation(_path2); - } - }; + imports[key] = importsEntry; + + _path.remove(); + } else if (_path.isExportDefaultDeclaration()) { + var declaration = _path.get("declaration"); + if (declaration.isFunctionDeclaration()) { + var id = declaration.node.id; + var defNode = t.identifier("default"); + if (id) { + addTo(exports, id.name, defNode); + topNodes.push(buildExportsAssignment(defNode, id)); + _path.replaceWith(declaration.node); + } else { + topNodes.push(buildExportsAssignment(defNode, t.toExpression(declaration.node))); + _path.remove(); + } + } else if (declaration.isClassDeclaration()) { + var _id = declaration.node.id; + var _defNode = t.identifier("default"); + if (_id) { + addTo(exports, _id.name, _defNode); + _path.replaceWithMultiple([declaration.node, buildExportsAssignment(_defNode, _id)]); + } else { + _path.replaceWith(buildExportsAssignment(_defNode, t.toExpression(declaration.node))); - Scope.prototype.push = function push(opts) { - var path = this.path; + _path.parentPath.requeue(_path.get("expression.left")); + } + } else { + _path.replaceWith(buildExportsAssignment(t.identifier("default"), declaration.node)); - if (!path.isBlockStatement() && !path.isProgram()) { - path = this.getBlockParent().path; - } + _path.parentPath.requeue(_path.get("expression.left")); + } + } else if (_path.isExportNamedDeclaration()) { + var _declaration = _path.get("declaration"); + if (_declaration.node) { + if (_declaration.isFunctionDeclaration()) { + var _id2 = _declaration.node.id; + addTo(exports, _id2.name, _id2); + topNodes.push(buildExportsAssignment(_id2, _id2)); + _path.replaceWith(_declaration.node); + } else if (_declaration.isClassDeclaration()) { + var _id3 = _declaration.node.id; + addTo(exports, _id3.name, _id3); + _path.replaceWithMultiple([_declaration.node, buildExportsAssignment(_id3, _id3)]); + nonHoistedExportNames[_id3.name] = true; + } else if (_declaration.isVariableDeclaration()) { + var declarators = _declaration.get("declarations"); + for (var _iterator5 = declarators, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } - if (path.isSwitchStatement()) { - path = this.getFunctionParent().path; - } + var decl = _ref5; - if (path.isLoop() || path.isCatchClause() || path.isFunction()) { - t.ensureBlock(path.node); - path = path.get("body"); - } + var _id4 = decl.get("id"); - var unique = opts.unique; - var kind = opts.kind || "var"; - var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; + var init = decl.get("init"); + if (!init.node) init.replaceWith(t.identifier("undefined")); - var dataKey = "declaration:" + kind + ":" + blockHoist; - var declarPath = !unique && path.getData(dataKey); + if (_id4.isIdentifier()) { + addTo(exports, _id4.node.name, _id4.node); + init.replaceWith(buildExportsAssignment(_id4.node, init.node).expression); + nonHoistedExportNames[_id4.node.name] = true; + } else {} + } + _path.replaceWith(_declaration.node); + } + continue; + } - if (!declarPath) { - var declar = t.variableDeclaration(kind, []); - declar._generated = true; - declar._blockHoist = blockHoist; + var _specifiers = _path.get("specifiers"); + var nodes = []; + var _source = _path.node.source; + if (_source) { + var ref = addRequire(_source.value, _path.node._blockHoist); + + for (var _iterator6 = _specifiers, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + var _specifier3 = _ref6; + + if (_specifier3.isExportNamespaceSpecifier()) {} else if (_specifier3.isExportDefaultSpecifier()) {} else if (_specifier3.isExportSpecifier()) { + if (!noInterop && _specifier3.node.local.name === "default") { + topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(t.callExpression(this.addHelper("interopRequireDefault"), [ref]), _specifier3.node.local))); + } else { + topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(ref, _specifier3.node.local))); + } + nonHoistedExportNames[_specifier3.node.exported.name] = true; + } + } + } else { + for (var _iterator7 = _specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + var _specifier4 = _ref7; + + if (_specifier4.isExportSpecifier()) { + addTo(exports, _specifier4.node.local.name, _specifier4.node.exported); + nonHoistedExportNames[_specifier4.node.exported.name] = true; + nodes.push(buildExportsAssignment(_specifier4.node.exported, _specifier4.node.local)); + } + } + } + _path.replaceWithMultiple(nodes); + } else if (_path.isExportAllDeclaration()) { + var exportNode = buildExportAll({ + OBJECT: addRequire(_path.node.source.value, _path.node._blockHoist) + }); + exportNode.loc = _path.node.loc; + topNodes.push(exportNode); + _path.remove(); + } + } - var _path$unshiftContaine = path.unshiftContainer("body", [declar]); + for (var source in imports) { + var _imports$source = imports[source], + specifiers = _imports$source.specifiers, + maxBlockHoist = _imports$source.maxBlockHoist; - declarPath = _path$unshiftContaine[0]; + if (specifiers.length) { + var uid = addRequire(source, maxBlockHoist); - if (!unique) path.setData(dataKey, declarPath); - } + var wildcard = void 0; - var declarator = t.variableDeclarator(opts.id, opts.init); - declarPath.node.declarations.push(declarator); - this.registerBinding(kind, declarPath.get("declarations").pop()); - }; + for (var i = 0; i < specifiers.length; i++) { + var specifier = specifiers[i]; + if (t.isImportNamespaceSpecifier(specifier)) { + if (strict || noInterop) { + remaps[specifier.local.name] = uid; + } else { + var varDecl = t.variableDeclaration("var", [t.variableDeclarator(specifier.local, t.callExpression(this.addHelper("interopRequireWildcard"), [uid]))]); - Scope.prototype.getProgramParent = function getProgramParent() { - var scope = this; - do { - if (scope.path.isProgram()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; + if (maxBlockHoist > 0) { + varDecl._blockHoist = maxBlockHoist; + } - Scope.prototype.getFunctionParent = function getFunctionParent() { - var scope = this; - do { - if (scope.path.isFunctionParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; + topNodes.push(varDecl); + } + wildcard = specifier.local; + } else if (t.isImportDefaultSpecifier(specifier)) { + specifiers[i] = t.importSpecifier(specifier.local, t.identifier("default")); + } + } - Scope.prototype.getBlockParent = function getBlockParent() { - var scope = this; - do { - if (scope.path.isBlockParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); - }; + for (var _iterator3 = specifiers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - Scope.prototype.getAllBindings = function getAllBindings() { - var ids = (0, _create2.default)(null); + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } - var scope = this; - do { - (0, _defaults2.default)(ids, scope.bindings); - scope = scope.parent; - } while (scope); + var _specifier = _ref3; - return ids; - }; + if (t.isImportSpecifier(_specifier)) { + var target = uid; + if (_specifier.imported.name === "default") { + if (wildcard) { + target = wildcard; + } else if (!noInterop) { + target = wildcard = path.scope.generateUidIdentifier(uid.name); + var _varDecl = t.variableDeclaration("var", [t.variableDeclarator(target, t.callExpression(this.addHelper("interopRequireDefault"), [uid]))]); - Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() { - var ids = (0, _create2.default)(null); + if (maxBlockHoist > 0) { + _varDecl._blockHoist = maxBlockHoist; + } - for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) { - var _ref19; + topNodes.push(_varDecl); + } + } + remaps[_specifier.local.name] = t.memberExpression(target, t.cloneWithoutLoc(_specifier.imported)); + } + } + } else { + var requireNode = buildRequire(t.stringLiteral(source)); + requireNode.loc = imports[source].loc; + topNodes.push(requireNode); + } + } - if (_isArray19) { - if (_i19 >= _iterator19.length) break; - _ref19 = _iterator19[_i19++]; - } else { - _i19 = _iterator19.next(); - if (_i19.done) break; - _ref19 = _i19.value; - } + if (hasImports && (0, _keys2.default)(nonHoistedExportNames).length) { + var maxHoistedExportsNodeAssignmentLength = 100; + var nonHoistedExportNamesArr = (0, _keys2.default)(nonHoistedExportNames); - var kind = _ref19; + var _loop = function _loop(currentExportsNodeAssignmentLength) { + var nonHoistedExportNamesChunk = nonHoistedExportNamesArr.slice(currentExportsNodeAssignmentLength, currentExportsNodeAssignmentLength + maxHoistedExportsNodeAssignmentLength); - var scope = this; - do { - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind === kind) ids[name] = binding; - } - scope = scope.parent; - } while (scope); - } + var hoistedExportsNode = t.identifier("undefined"); - return ids; - }; + nonHoistedExportNamesChunk.forEach(function (name) { + hoistedExportsNode = buildExportsAssignment(t.identifier(name), hoistedExportsNode).expression; + }); - Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) { - return this.getBindingIdentifier(name) === node; - }; + var node = t.expressionStatement(hoistedExportsNode); + node._blockHoist = 3; - Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) { - if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) { - console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 7. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "); + topNodes.unshift(node); + }; + + for (var currentExportsNodeAssignmentLength = 0; currentExportsNodeAssignmentLength < nonHoistedExportNamesArr.length; currentExportsNodeAssignmentLength += maxHoistedExportsNodeAssignmentLength) { + _loop(currentExportsNodeAssignmentLength); + } + } + + if (hasExports && !strict) { + var buildTemplate = buildExportsModuleDeclaration; + if (this.opts.loose) buildTemplate = buildLooseExportsModuleDeclaration; + + var declar = buildTemplate(); + declar._blockHoist = 3; + + topNodes.unshift(declar); + } + + path.unshiftContainer("body", topNodes); + path.traverse(reassignmentVisitor, { + remaps: remaps, + scope: scope, + exports: exports, + requeueInParent: function requeueInParent(newPath) { + return path.requeue(newPath); + } + }); + } + } } - return binding; }; +}; - Scope.prototype.getBinding = function getBinding(name) { - var scope = this; +var _path2 = require("path"); - do { - var binding = scope.getOwnBinding(name); - if (binding) return this.warnOnFlowBinding(binding); - } while (scope = scope.parent); - }; +var _babelTemplate = require("babel-template"); - Scope.prototype.getOwnBinding = function getOwnBinding(name) { - return this.warnOnFlowBinding(this.bindings[name]); - }; +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) { - var info = this.getBinding(name); - return info && info.identifier; - }; +var _babelTypes = require("babel-types"); - Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) { - var binding = this.bindings[name]; - return binding && binding.identifier; - }; +var t = _interopRequireWildcard(_babelTypes); - Scope.prototype.hasOwnBinding = function hasOwnBinding(name) { - return !!this.getOwnBinding(name); - }; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - Scope.prototype.hasBinding = function hasBinding(name, noGlobals) { - if (!name) return false; - if (this.hasOwnBinding(name)) return true; - if (this.parentHasBinding(name, noGlobals)) return true; - if (this.hasUid(name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true; - return false; - }; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) { - return this.parent && this.parent.hasBinding(name, noGlobals); - }; +var buildRequire = (0, _babelTemplate2.default)("\n require($0);\n"); - Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - info.scope = scope; - scope.bindings[name] = info; - } - }; +var buildExportsModuleDeclaration = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n"); - Scope.prototype.removeOwnBinding = function removeOwnBinding(name) { - delete this.bindings[name]; - }; +var buildExportsFrom = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, $0, {\n enumerable: true,\n get: function () {\n return $1;\n }\n });\n"); - Scope.prototype.removeBinding = function removeBinding(name) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - } +var buildLooseExportsModuleDeclaration = (0, _babelTemplate2.default)("\n exports.__esModule = true;\n"); - var scope = this; - do { - if (scope.uids[name]) { - scope.uids[name] = false; - } - } while (scope = scope.parent); - }; +var buildExportsAssignment = (0, _babelTemplate2.default)("\n exports.$0 = $1;\n"); - return Scope; -}(); +var buildExportAll = (0, _babelTemplate2.default)("\n Object.keys(OBJECT).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return OBJECT[key];\n }\n });\n });\n"); + +var THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod"]; -Scope.globals = (0, _keys2.default)(_globals2.default.builtin); -Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; -exports.default = Scope; module.exports = exports["default"]; -},{"../cache":109,"../index":112,"./binding":130,"./lib/renamer":132,"babel-messages":79,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/map":91,"babel-runtime/core-js/object/create":94,"babel-runtime/core-js/object/keys":96,"babel-runtime/helpers/classCallCheck":103,"babel-types":145,"globals":282,"lodash/defaults":459,"lodash/includes":471,"lodash/repeat":494}],132:[function(require,module,exports){ +},{"babel-plugin-transform-strict-mode":126,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/object/create":132,"babel-runtime/core-js/object/keys":134,"babel-runtime/core-js/symbol":136,"babel-template":146,"babel-types":183,"path":13}],126:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +var _getIterator3 = _interopRequireDefault(_getIterator2); -var _binding = require("../binding"); +exports.default = function () { + return { + visitor: { + Program: function Program(path, state) { + if (state.opts.strict === false || state.opts.strictMode === false) return; -var _binding2 = _interopRequireDefault(_binding); + var node = path.node; + + + for (var _iterator = node.directives, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var directive = _ref; + + if (directive.value.value === "use strict") return; + } + + path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); + } + } + }; +}; var _babelTypes = require("babel-types"); @@ -19180,3867 +21234,3532 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var renameVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { - var node = _ref.node; +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":127,"babel-types":183}],127:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; +},{"core-js/library/fn/get-iterator":193}],128:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; +},{"core-js/library/fn/json/stringify":194}],129:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; +},{"core-js/library/fn/map":195}],130:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; +},{"core-js/library/fn/number/max-safe-integer":196}],131:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; +},{"core-js/library/fn/object/assign":197}],132:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; +},{"core-js/library/fn/object/create":198}],133:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; +},{"core-js/library/fn/object/get-own-property-symbols":199}],134:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; +},{"core-js/library/fn/object/keys":200}],135:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; +},{"core-js/library/fn/object/set-prototype-of":201}],136:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; +},{"core-js/library/fn/symbol":203}],137:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; +},{"core-js/library/fn/symbol/for":202}],138:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; +},{"core-js/library/fn/symbol/iterator":204}],139:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; +},{"core-js/library/fn/weak-map":205}],140:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; +},{"core-js/library/fn/weak-set":206}],141:[function(require,module,exports){ +"use strict"; - if (node.name === state.oldName) { - node.name = state.newName; - } - }, - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { - path.skip(); - } - }, - "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { - var ids = path.getOuterBindingIdentifiers(); +exports.__esModule = true; - for (var name in ids) { - if (name === state.oldName) ids[name].name = state.newName; - } +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); } }; +},{}],142:[function(require,module,exports){ +"use strict"; -var Renamer = function () { - function Renamer(binding, oldName, newName) { - (0, _classCallCheck3.default)(this, Renamer); +exports.__esModule = true; - this.newName = newName; - this.oldName = oldName; - this.binding = binding; - } +var _setPrototypeOf = require("../core-js/object/set-prototype-of"); - Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { - var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; - if (!exportDeclar) return; +var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); - var isDefault = exportDeclar.isExportDefaultDeclaration(); +var _create = require("../core-js/object/create"); - if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { - parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); - } +var _create2 = _interopRequireDefault(_create); - var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); - var specifiers = []; +var _typeof2 = require("../helpers/typeof"); - for (var name in bindingIdentifiers) { - var localName = name === this.oldName ? this.newName : name; - var exportedName = isDefault ? "default" : name; - specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); - } +var _typeof3 = _interopRequireDefault(_typeof2); - if (specifiers.length) { - var aliasDeclar = t.exportNamedDeclaration(null, specifiers); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (parentDeclar.isFunctionDeclaration()) { - aliasDeclar._blockHoist = 3; - } +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } - exportDeclar.insertAfter(aliasDeclar); - exportDeclar.replaceWith(parentDeclar.node); + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true } - }; + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +},{"../core-js/object/create":132,"../core-js/object/set-prototype-of":135,"../helpers/typeof":145}],143:[function(require,module,exports){ +"use strict"; - Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) { - return; +exports.__esModule = true; - if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; - if (this.binding.kind !== "hoisted") return; +exports.default = function (obj, keys) { + var target = {}; - path.node.id = t.identifier(this.oldName); - path.node._blockHoist = 3; + for (var i in obj) { + if (keys.indexOf(i) >= 0) continue; + if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; + target[i] = obj[i]; + } - path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))])); - }; + return target; +}; +},{}],144:[function(require,module,exports){ +"use strict"; - Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) { - return; +exports.__esModule = true; - if (!path.isFunctionExpression() && !path.isClassExpression()) return; - if (this.binding.kind !== "local") return; +var _typeof2 = require("../helpers/typeof"); - path.node.id = t.identifier(this.oldName); +var _typeof3 = _interopRequireDefault(_typeof2); - this.binding.scope.parent.push({ - id: t.identifier(this.newName) - }); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node)); - }; +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } - Renamer.prototype.rename = function rename(block) { - var binding = this.binding, - oldName = this.oldName, - newName = this.newName; - var scope = binding.scope, - path = binding.path; + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +},{"../helpers/typeof":145}],145:[function(require,module,exports){ +"use strict"; +exports.__esModule = true; - var parentDeclar = path.find(function (path) { - return path.isDeclaration() || path.isFunctionExpression(); - }); - if (parentDeclar) { - this.maybeConvertFromExportDeclaration(parentDeclar); - } +var _iterator = require("../core-js/symbol/iterator"); - scope.traverse(block || scope.block, renameVisitor, this); +var _iterator2 = _interopRequireDefault(_iterator); - if (!block) { - scope.removeOwnBinding(oldName); - scope.bindings[newName] = binding; - this.binding.identifier.name = newName; - } +var _symbol = require("../core-js/symbol"); - if (binding.type === "hoisted") {} +var _symbol2 = _interopRequireDefault(_symbol); - if (parentDeclar) { - this.maybeConvertFromClassFunctionDeclaration(parentDeclar); - this.maybeConvertFromClassFunctionExpression(parentDeclar); - } - }; +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; - return Renamer; -}(); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -exports.default = Renamer; -module.exports = exports["default"]; -},{"../binding":130,"babel-runtime/helpers/classCallCheck":103,"babel-types":145}],133:[function(require,module,exports){ +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +},{"../core-js/symbol":136,"../core-js/symbol/iterator":138}],146:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _typeof2 = require("babel-runtime/helpers/typeof"); +var _symbol = require("babel-runtime/core-js/symbol"); -var _typeof3 = _interopRequireDefault(_typeof2); +var _symbol2 = _interopRequireDefault(_symbol); -var _keys = require("babel-runtime/core-js/object/keys"); +exports.default = function (code, opts) { + var stack = void 0; + try { + throw new Error(); + } catch (error) { + if (error.stack) { + stack = error.stack.split("\n").slice(1).join("\n"); + } + } -var _keys2 = _interopRequireDefault(_keys); + opts = (0, _assign2.default)({ + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, + preserveComments: false + }, opts); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + var _getAst = function getAst() { + var ast = void 0; -var _getIterator3 = _interopRequireDefault(_getIterator2); + try { + ast = babylon.parse(code, opts); -exports.explode = explode; -exports.verify = verify; -exports.merge = merge; + ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); -var _virtualTypes = require("./path/lib/virtual-types"); + _babelTraverse2.default.cheap(ast, function (node) { + node[FROM_TEMPLATE] = true; + }); + } catch (err) { + err.stack = err.stack + "from\n" + stack; + throw err; + } -var virtualTypes = _interopRequireWildcard(_virtualTypes); + _getAst = function getAst() { + return ast; + }; -var _babelMessages = require("babel-messages"); + return ast; + }; -var messages = _interopRequireWildcard(_babelMessages); + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -var _babelTypes = require("babel-types"); + return useTemplate(_getAst(), args); + }; +}; -var t = _interopRequireWildcard(_babelTypes); +var _cloneDeep = require("lodash/cloneDeep"); -var _clone = require("lodash/clone"); +var _cloneDeep2 = _interopRequireDefault(_cloneDeep); -var _clone2 = _interopRequireDefault(_clone); +var _assign = require("lodash/assign"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _assign2 = _interopRequireDefault(_assign); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _has = require("lodash/has"); -function explode(visitor) { - if (visitor._exploded) return visitor; - visitor._exploded = true; +var _has2 = _interopRequireDefault(_has); - for (var nodeType in visitor) { - if (shouldIgnoreKey(nodeType)) continue; +var _babelTraverse = require("babel-traverse"); - var parts = nodeType.split("|"); - if (parts.length === 1) continue; +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - var fns = visitor[nodeType]; - delete visitor[nodeType]; +var _babylon = require("babylon"); - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var babylon = _interopRequireWildcard(_babylon); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _babelTypes = require("babel-types"); - var part = _ref; +var t = _interopRequireWildcard(_babelTypes); - visitor[part] = fns; - } - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - verify(visitor); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - delete visitor.__esModule; +var FROM_TEMPLATE = "_fromTemplate"; +var TEMPLATE_SKIP = (0, _symbol2.default)(); - ensureEntranceObjects(visitor); +function useTemplate(ast, nodes) { + ast = (0, _cloneDeep2.default)(ast); + var _ast = ast, + program = _ast.program; - ensureCallbackArrays(visitor); - for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (nodes.length) { + (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + if (program.body.length > 1) { + return program.body; + } else { + return program.body[0]; + } +} - var _nodeType3 = _ref2; +var templateVisitor = { + noScope: true, - if (shouldIgnoreKey(_nodeType3)) continue; + enter: function enter(path, args) { + var node = path.node; - var wrapper = virtualTypes[_nodeType3]; - if (!wrapper) continue; + if (node[TEMPLATE_SKIP]) return path.skip(); - var _fns2 = visitor[_nodeType3]; - for (var type in _fns2) { - _fns2[type] = wrapCheck(wrapper, _fns2[type]); + if (t.isExpressionStatement(node)) { + node = node.expression; } - delete visitor[_nodeType3]; - - if (wrapper.types) { - for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + var replacement = void 0; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } + if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { + if ((0, _has2.default)(args[0], node.name)) { + replacement = args[0][node.name]; + } else if (node.name[0] === "$") { + var i = +node.name.slice(1); + if (args[i]) replacement = args[i]; + } + } - var _type = _ref4; + if (replacement === null) { + path.remove(); + } - if (visitor[_type]) { - mergePair(visitor[_type], _fns2); - } else { - visitor[_type] = _fns2; - } - } - } else { - mergePair(visitor, _fns2); + if (replacement) { + replacement[TEMPLATE_SKIP] = true; + path.replaceInline(replacement); } + }, + exit: function exit(_ref) { + var node = _ref.node; + + if (!node.loc) _babelTraverse2.default.clearNode(node); } +}; +module.exports = exports["default"]; +},{"babel-runtime/core-js/symbol":136,"babel-traverse":150,"babel-types":183,"babylon":187,"lodash/assign":490,"lodash/cloneDeep":494,"lodash/has":506}],147:[function(require,module,exports){ +"use strict"; - for (var _nodeType in visitor) { - if (shouldIgnoreKey(_nodeType)) continue; +exports.__esModule = true; +exports.scope = exports.path = undefined; - var _fns = visitor[_nodeType]; +var _weakMap = require("babel-runtime/core-js/weak-map"); - var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; +var _weakMap2 = _interopRequireDefault(_weakMap); - var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; - if (deprecratedKey) { - console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); - aliases = [deprecratedKey]; - } +exports.clear = clear; +exports.clearPath = clearPath; +exports.clearScope = clearScope; - if (!aliases) continue; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - delete visitor[_nodeType]; +var path = exports.path = new _weakMap2.default(); +var scope = exports.scope = new _weakMap2.default(); - for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +function clear() { + clearPath(); + clearScope(); +} - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } +function clearPath() { + exports.path = path = new _weakMap2.default(); +} - var alias = _ref3; +function clearScope() { + exports.scope = scope = new _weakMap2.default(); +} +},{"babel-runtime/core-js/weak-map":139}],148:[function(require,module,exports){ +(function (process){ +"use strict"; - var existing = visitor[alias]; - if (existing) { - mergePair(existing, _fns); - } else { - visitor[alias] = (0, _clone2.default)(_fns); - } - } - } +exports.__esModule = true; - for (var _nodeType2 in visitor) { - if (shouldIgnoreKey(_nodeType2)) continue; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - ensureCallbackArrays(visitor[_nodeType2]); - } +var _getIterator3 = _interopRequireDefault(_getIterator2); - return visitor; -} +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -function verify(visitor) { - if (visitor._verified) return; +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - if (typeof visitor === "function") { - throw new Error(messages.get("traverseVerifyRootFunction")); - } +var _path2 = require("./path"); - for (var nodeType in visitor) { - if (nodeType === "enter" || nodeType === "exit") { - validateVisitorMethods(nodeType, visitor[nodeType]); - } +var _path3 = _interopRequireDefault(_path2); - if (shouldIgnoreKey(nodeType)) continue; +var _babelTypes = require("babel-types"); - if (t.TYPES.indexOf(nodeType) < 0) { - throw new Error(messages.get("traverseVerifyNodeType", nodeType)); - } +var t = _interopRequireWildcard(_babelTypes); - var visitors = visitor[nodeType]; - if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { - for (var visitorKey in visitors) { - if (visitorKey === "enter" || visitorKey === "exit") { - validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); - } else { - throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); - } - } - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var testing = process.env.NODE_ENV === "test"; + +var TraversalContext = function () { + function TraversalContext(scope, opts, state, parentPath) { + (0, _classCallCheck3.default)(this, TraversalContext); + this.queue = null; + + this.parentPath = parentPath; + this.scope = scope; + this.state = state; + this.opts = opts; } - visitor._verified = true; -} + TraversalContext.prototype.shouldVisit = function shouldVisit(node) { + var opts = this.opts; + if (opts.enter || opts.exit) return true; -function validateVisitorMethods(path, val) { - var fns = [].concat(val); - for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + if (opts[node.type]) return true; - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } + var keys = t.VISITOR_KEYS[node.type]; + if (!keys || !keys.length) return false; - var fn = _ref5; + for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (typeof fn !== "function") { - throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var key = _ref; + + if (node[key]) return true; } - } -} -function merge(visitors) { - var states = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var wrapper = arguments[2]; + return false; + }; - var rootVisitor = {}; + TraversalContext.prototype.create = function create(node, obj, key, listKey) { + return _path3.default.get({ + parentPath: this.parentPath, + parent: node, + container: obj, + key: key, + listKey: listKey + }); + }; - for (var i = 0; i < visitors.length; i++) { - var visitor = visitors[i]; - var state = states[i]; + TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { + if (this.trap) { + throw new Error("Infinite cycle detected"); + } - explode(visitor); + if (this.queue) { + if (notPriority) { + this.queue.push(path); + } else { + this.priorityQueue.push(path); + } + } + }; - for (var type in visitor) { - var visitorType = visitor[type]; + TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { + if (container.length === 0) return false; - if (state || wrapper) { - visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); + var queue = []; + + for (var key = 0; key < container.length; key++) { + var node = container[key]; + if (node && this.shouldVisit(node)) { + queue.push(this.create(parent, container, key, listKey)); } + } - var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; - mergePair(nodeVisitor, visitorType); + return this.visitQueue(queue); + }; + + TraversalContext.prototype.visitSingle = function visitSingle(node, key) { + if (this.shouldVisit(node[key])) { + return this.visitQueue([this.create(node, node, key)]); + } else { + return false; } - } + }; - return rootVisitor; -} + TraversalContext.prototype.visitQueue = function visitQueue(queue) { + this.queue = queue; + this.priorityQueue = []; -function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { - var newVisitor = {}; + var visited = []; + var stop = false; - var _loop = function _loop(key) { - var fns = oldVisitor[key]; + for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - if (!Array.isArray(fns)) return "continue"; + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } - fns = fns.map(function (fn) { - var newFn = fn; + var path = _ref2; - if (state) { - newFn = function newFn(path) { - return fn.call(state, path, state); - }; + path.resync(); + + if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { + path.pushContext(this); } - if (wrapper) { - newFn = wrapper(state.key, key, newFn); + if (path.key === null) continue; + + if (testing && queue.length >= 10000) { + this.trap = true; } - return newFn; - }); + if (visited.indexOf(path.node) >= 0) continue; + visited.push(path.node); - newVisitor[key] = fns; - }; + if (path.visit()) { + stop = true; + break; + } - for (var key in oldVisitor) { - var _ret = _loop(key); + if (this.priorityQueue.length) { + stop = this.visitQueue(this.priorityQueue); + this.priorityQueue = []; + this.queue = queue; + if (stop) break; + } + } - if (_ret === "continue") continue; - } + for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - return newVisitor; -} + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } -function ensureEntranceObjects(obj) { - for (var key in obj) { - if (shouldIgnoreKey(key)) continue; + var _path = _ref3; - var fns = obj[key]; - if (typeof fns === "function") { - obj[key] = { enter: fns }; + _path.popContext(); } - } -} -function ensureCallbackArrays(obj) { - if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; - if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; -} + this.queue = null; -function wrapCheck(wrapper, fn) { - var newFn = function newFn(path) { - if (wrapper.checkPath(path)) { - return fn.apply(this, arguments); - } - }; - newFn.toString = function () { - return fn.toString(); + return stop; }; - return newFn; -} - -function shouldIgnoreKey(key) { - if (key[0] === "_") return true; - if (key === "enter" || key === "exit" || key === "shouldSkip") return true; + TraversalContext.prototype.visit = function visit(node, key) { + var nodes = node[key]; + if (!nodes) return false; - if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; + if (Array.isArray(nodes)) { + return this.visitMultiple(nodes, node, key); + } else { + return this.visitSingle(node, key); + } + }; - return false; -} + return TraversalContext; +}(); -function mergePair(dest, src) { - for (var key in src) { - dest[key] = [].concat(dest[key] || [], src[key]); - } -} -},{"./path/lib/virtual-types":126,"babel-messages":79,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/object/keys":96,"babel-runtime/helpers/typeof":107,"babel-types":145,"lodash/clone":455}],134:[function(require,module,exports){ +exports.default = TraversalContext; +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"./path":157,"_process":15,"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/classCallCheck":141,"babel-types":183}],149:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; -var _for = require("babel-runtime/core-js/symbol/for"); +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -var _for2 = _interopRequireDefault(_for); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var STATEMENT_OR_BLOCK_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; -var FLATTENABLE_KEYS = exports.FLATTENABLE_KEYS = ["body", "expressions"]; -var FOR_INIT_KEYS = exports.FOR_INIT_KEYS = ["left", "init"]; -var COMMENT_KEYS = exports.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; - -var LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = ["||", "&&"]; -var UPDATE_OPERATORS = exports.UPDATE_OPERATORS = ["++", "--"]; - -var BOOLEAN_NUMBER_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; -var EQUALITY_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; -var COMPARISON_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = [].concat(EQUALITY_BINARY_OPERATORS, ["in", "instanceof"]); -var BOOLEAN_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); -var NUMBER_BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; -var BINARY_OPERATORS = exports.BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); - -var BOOLEAN_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; -var NUMBER_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; -var STRING_UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = ["typeof"]; -var UNARY_OPERATORS = exports.UNARY_OPERATORS = ["void"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); +var Hub = function Hub(file, options) { + (0, _classCallCheck3.default)(this, Hub); -var INHERIT_KEYS = exports.INHERIT_KEYS = { - optional: ["typeAnnotation", "typeParameters", "returnType"], - force: ["start", "loc", "end"] + this.file = file; + this.options = options; }; -var BLOCK_SCOPED_SYMBOL = exports.BLOCK_SCOPED_SYMBOL = (0, _for2.default)("var used to be block scoped"); -var NOT_LOCAL_BINDING = exports.NOT_LOCAL_BINDING = (0, _for2.default)("should not be considered a local binding"); -},{"babel-runtime/core-js/symbol/for":99}],135:[function(require,module,exports){ +exports.default = Hub; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":141}],150:[function(require,module,exports){ "use strict"; exports.__esModule = true; +exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; -var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger); +var _getIterator3 = _interopRequireDefault(_getIterator2); -var _stringify = require("babel-runtime/core-js/json/stringify"); +var _path = require("./path"); -var _stringify2 = _interopRequireDefault(_stringify); +Object.defineProperty(exports, "NodePath", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_path).default; + } +}); -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _scope = require("./scope"); -var _getIterator3 = _interopRequireDefault(_getIterator2); +Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_scope).default; + } +}); -exports.toComputedKey = toComputedKey; -exports.toSequenceExpression = toSequenceExpression; -exports.toKeyAlias = toKeyAlias; -exports.toIdentifier = toIdentifier; -exports.toBindingIdentifierName = toBindingIdentifierName; -exports.toStatement = toStatement; -exports.toExpression = toExpression; -exports.toBlock = toBlock; -exports.valueToNode = valueToNode; +var _hub = require("./hub"); -var _isPlainObject = require("lodash/isPlainObject"); +Object.defineProperty(exports, "Hub", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_hub).default; + } +}); +exports.default = traverse; -var _isPlainObject2 = _interopRequireDefault(_isPlainObject); +var _context = require("./context"); -var _isRegExp = require("lodash/isRegExp"); +var _context2 = _interopRequireDefault(_context); -var _isRegExp2 = _interopRequireDefault(_isRegExp); +var _visitors = require("./visitors"); -var _index = require("./index"); +var visitors = _interopRequireWildcard(_visitors); -var t = _interopRequireWildcard(_index); +var _babelMessages = require("babel-messages"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var messages = _interopRequireWildcard(_babelMessages); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _includes = require("lodash/includes"); -function toComputedKey(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key || node.property; +var _includes2 = _interopRequireDefault(_includes); - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - return key; -} +var _babelTypes = require("babel-types"); -function toSequenceExpression(nodes, scope) { - if (!nodes || !nodes.length) return; +var t = _interopRequireWildcard(_babelTypes); - var declars = []; - var bailed = false; +var _cache = require("./cache"); - var result = convert(nodes); - if (bailed) return; +var cache = _interopRequireWildcard(_cache); - for (var i = 0; i < declars.length; i++) { - scope.push(declars[i]); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - return result; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function convert(nodes) { - var ensureLastUndefined = false; - var exprs = []; +exports.visitors = visitors; +function traverse(parent, opts, scope, state, parentPath) { + if (!parent) return; + if (!opts) opts = {}; - for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + if (!opts.noScope && !scope) { + if (parent.type !== "Program" && parent.type !== "File") { + throw new Error(messages.get("traverseNeedsParent", parent.type)); + } + } - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + visitors.explode(opts); - var node = _ref; + traverse.node(parent, opts, scope, state, parentPath); +} - if (t.isExpression(node)) { - exprs.push(node); - } else if (t.isExpressionStatement(node)) { - exprs.push(node.expression); - } else if (t.isVariableDeclaration(node)) { - if (node.kind !== "var") return bailed = true; +traverse.visitors = visitors; +traverse.verify = visitors.verify; +traverse.explode = visitors.explode; - for (var _iterator2 = node.declarations, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; +traverse.NodePath = require("./path"); +traverse.Scope = require("./scope"); +traverse.Hub = require("./hub"); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } +traverse.cheap = function (node, enter) { + return t.traverseFast(node, enter); +}; - var declar = _ref2; +traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { + var keys = t.VISITOR_KEYS[node.type]; + if (!keys) return; - var bindings = t.getBindingIdentifiers(declar); - for (var key in bindings) { - declars.push({ - kind: node.kind, - id: bindings[key] - }); - } + var context = new _context2.default(scope, opts, state, parentPath); + for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (declar.init) { - exprs.push(t.assignmentExpression("=", declar.id, declar.init)); - } - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - ensureLastUndefined = true; - continue; - } else if (t.isIfStatement(node)) { - var consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode(); - var alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode(); - if (!consequent || !alternate) return bailed = true; + var key = _ref; - exprs.push(t.conditionalExpression(node.test, consequent, alternate)); - } else if (t.isBlockStatement(node)) { - exprs.push(convert(node.body)); - } else if (t.isEmptyStatement(node)) { - ensureLastUndefined = true; - continue; - } else { - return bailed = true; - } + if (skipKeys && skipKeys[key]) continue; + if (context.visit(node, key)) return; + } +}; - ensureLastUndefined = false; - } +traverse.clearNode = function (node, opts) { + t.removeProperties(node, opts); - if (ensureLastUndefined || exprs.length === 0) { - exprs.push(scope.buildUndefinedNode()); - } + cache.path.delete(node); +}; - if (exprs.length === 1) { - return exprs[0]; - } else { - return t.sequenceExpression(exprs); - } +traverse.removeProperties = function (tree, opts) { + t.traverseFast(tree, traverse.clearNode, opts); + return tree; +}; + +function hasBlacklistedType(path, state) { + if (path.node.type === state.type) { + state.has = true; + path.stop(); } } -function toKeyAlias(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key; +traverse.hasType = function (tree, scope, type, blacklistTypes) { + if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; - var alias = void 0; + if (tree.type === type) return true; - if (node.kind === "method") { - return toKeyAlias.increment() + ""; - } else if (t.isIdentifier(key)) { - alias = key.name; - } else if (t.isStringLiteral(key)) { - alias = (0, _stringify2.default)(key.value); - } else { - alias = (0, _stringify2.default)(t.removePropertiesDeep(t.cloneDeep(key))); - } + var state = { + has: false, + type: type + }; - if (node.computed) { - alias = "[" + alias + "]"; - } + traverse(tree, { + blacklist: blacklistTypes, + enter: hasBlacklistedType + }, scope, state); - if (node.static) { - alias = "static:" + alias; - } + return state.has; +}; - return alias; -} +traverse.clearCache = function () { + cache.clear(); +}; -toKeyAlias.uid = 0; +traverse.clearCache.clearPath = cache.clearPath; +traverse.clearCache.clearScope = cache.clearScope; -toKeyAlias.increment = function () { - if (toKeyAlias.uid >= _maxSafeInteger2.default) { - return toKeyAlias.uid = 0; - } else { - return toKeyAlias.uid++; +traverse.copyCache = function (source, destination) { + if (cache.path.has(source)) { + cache.path.set(destination, cache.path.get(source)); } }; +},{"./cache":147,"./context":148,"./hub":149,"./path":157,"./scope":169,"./visitors":171,"babel-messages":115,"babel-runtime/core-js/get-iterator":127,"babel-types":183,"lodash/includes":509}],151:[function(require,module,exports){ +"use strict"; -function toIdentifier(name) { - name = name + ""; +exports.__esModule = true; - name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - name = name.replace(/^[-0-9]+/, ""); +var _getIterator3 = _interopRequireDefault(_getIterator2); - name = name.replace(/[-\s]+(.)?/g, function (match, c) { - return c ? c.toUpperCase() : ""; - }); +exports.findParent = findParent; +exports.find = find; +exports.getFunctionParent = getFunctionParent; +exports.getStatementParent = getStatementParent; +exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; +exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; +exports.getAncestry = getAncestry; +exports.isAncestor = isAncestor; +exports.isDescendant = isDescendant; +exports.inType = inType; +exports.inShadow = inShadow; - if (!t.isValidIdentifier(name)) { - name = "_" + name; +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function findParent(callback) { + var path = this; + while (path = path.parentPath) { + if (callback(path)) return path; } + return null; +} - return name || "_"; +function find(callback) { + var path = this; + do { + if (callback(path)) return path; + } while (path = path.parentPath); + return null; } -function toBindingIdentifierName(name) { - name = toIdentifier(name); - if (name === "eval" || name === "arguments") name = "_" + name; - return name; +function getFunctionParent() { + return this.findParent(function (path) { + return path.isFunction() || path.isProgram(); + }); } -function toStatement(node, ignore) { - if (t.isStatement(node)) { - return node; - } +function getStatementParent() { + var path = this; + do { + if (Array.isArray(path.container)) { + return path; + } + } while (path = path.parentPath); +} - var mustHaveId = false; - var newType = void 0; +function getEarliestCommonAncestorFrom(paths) { + return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { + var earliest = void 0; + var keys = t.VISITOR_KEYS[deepest.type]; - if (t.isClass(node)) { - mustHaveId = true; - newType = "ClassDeclaration"; - } else if (t.isFunction(node)) { - mustHaveId = true; - newType = "FunctionDeclaration"; - } else if (t.isAssignmentExpression(node)) { - return t.expressionStatement(node); - } + for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (mustHaveId && !node.id) { - newType = false; - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - if (!newType) { - if (ignore) { - return false; - } else { - throw new Error("cannot turn " + node.type + " to a statement"); - } - } + var ancestry = _ref; - node.type = newType; + var path = ancestry[i + 1]; - return node; + if (!earliest) { + earliest = path; + continue; + } + + if (path.listKey && earliest.listKey === path.listKey) { + if (path.key < earliest.key) { + earliest = path; + continue; + } + } + + var earliestKeyIndex = keys.indexOf(earliest.parentKey); + var currentKeyIndex = keys.indexOf(path.parentKey); + if (earliestKeyIndex > currentKeyIndex) { + earliest = path; + } + } + + return earliest; + }); } -function toExpression(node) { - if (t.isExpressionStatement(node)) { - node = node.expression; - } +function getDeepestCommonAncestorFrom(paths, filter) { + var _this = this; - if (t.isExpression(node)) { - return node; + if (!paths.length) { + return this; } - if (t.isClass(node)) { - node.type = "ClassExpression"; - } else if (t.isFunction(node)) { - node.type = "FunctionExpression"; + if (paths.length === 1) { + return paths[0]; } - if (!t.isExpression(node)) { - throw new Error("cannot turn " + node.type + " to an expression"); - } + var minDepth = Infinity; - return node; -} + var lastCommonIndex = void 0, + lastCommon = void 0; -function toBlock(node, parent) { - if (t.isBlockStatement(node)) { - return node; - } + var ancestries = paths.map(function (path) { + var ancestry = []; - if (t.isEmptyStatement(node)) { - node = []; - } + do { + ancestry.unshift(path); + } while ((path = path.parentPath) && path !== _this); - if (!Array.isArray(node)) { - if (!t.isStatement(node)) { - if (t.isFunction(parent)) { - node = t.returnStatement(node); + if (ancestry.length < minDepth) { + minDepth = ancestry.length; + } + + return ancestry; + }); + + var first = ancestries[0]; + + depthLoop: for (var i = 0; i < minDepth; i++) { + var shouldMatch = first[i]; + + for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; } else { - node = t.expressionStatement(node); + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var ancestry = _ref2; + + if (ancestry[i] !== shouldMatch) { + break depthLoop; } } - node = [node]; + lastCommonIndex = i; + lastCommon = shouldMatch; } - return t.blockStatement(node); + if (lastCommon) { + if (filter) { + return filter(lastCommon, lastCommonIndex, ancestries); + } else { + return lastCommon; + } + } else { + throw new Error("Couldn't find intersection"); + } } -function valueToNode(value) { - if (value === undefined) { - return t.identifier("undefined"); - } +function getAncestry() { + var path = this; + var paths = []; + do { + paths.push(path); + } while (path = path.parentPath); + return paths; +} - if (value === true || value === false) { - return t.booleanLiteral(value); - } +function isAncestor(maybeDescendant) { + return maybeDescendant.isDescendant(this); +} - if (value === null) { - return t.nullLiteral(); - } +function isDescendant(maybeAncestor) { + return !!this.findParent(function (parent) { + return parent === maybeAncestor; + }); +} - if (typeof value === "string") { - return t.stringLiteral(value); - } +function inType() { + var path = this; + while (path) { + for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - if (typeof value === "number") { - return t.numericLiteral(value); - } + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } - if ((0, _isRegExp2.default)(value)) { - var pattern = value.source; - var flags = value.toString().match(/\/([a-z]+|)$/)[1]; - return t.regExpLiteral(pattern, flags); - } + var type = _ref3; - if (Array.isArray(value)) { - return t.arrayExpression(value.map(t.valueToNode)); + if (path.node.type === type) return true; + } + path = path.parentPath; } - if ((0, _isPlainObject2.default)(value)) { - var props = []; - for (var key in value) { - var nodeKey = void 0; - if (t.isValidIdentifier(key)) { - nodeKey = t.identifier(key); - } else { - nodeKey = t.stringLiteral(key); - } - props.push(t.objectProperty(nodeKey, t.valueToNode(value[key]))); + return false; +} + +function inShadow(key) { + var parentFn = this.isFunction() ? this : this.findParent(function (p) { + return p.isFunction(); + }); + if (!parentFn) return; + + if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { + var shadow = parentFn.node.shadow; + + if (shadow && (!key || shadow[key] !== false)) { + return parentFn; } - return t.objectExpression(props); + } else if (parentFn.isArrowFunctionExpression()) { + return parentFn; } - throw new Error("don't know how to turn this value into a node"); + return null; } -},{"./index":145,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/json/stringify":90,"babel-runtime/core-js/number/max-safe-integer":92,"lodash/isPlainObject":482,"lodash/isRegExp":483}],136:[function(require,module,exports){ +},{"./index":157,"babel-runtime/core-js/get-iterator":127,"babel-types":183}],152:[function(require,module,exports){ "use strict"; -var _index = require("../index"); +exports.__esModule = true; +exports.shareCommentsWithSiblings = shareCommentsWithSiblings; +exports.addComment = addComment; +exports.addComments = addComments; +function shareCommentsWithSiblings() { + if (typeof this.key === "string") return; -var t = _interopRequireWildcard(_index); + var node = this.node; + if (!node) return; -var _constants = require("../constants"); + var trailing = node.trailingComments; + var leading = node.leadingComments; + if (!trailing && !leading) return; -var _index2 = require("./index"); + var prev = this.getSibling(this.key - 1); + var next = this.getSibling(this.key + 1); -var _index3 = _interopRequireDefault(_index2); + if (!prev.node) prev = next; + if (!next.node) next = prev; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + prev.addComments("trailing", leading); + next.addComments("leading", trailing); +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -(0, _index3.default)("ArrayExpression", { - fields: { - elements: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), - default: [] - } - }, - visitor: ["elements"], - aliases: ["Expression"] -}); +function addComment(type, content, line) { + this.addComments(type, [{ + type: line ? "CommentLine" : "CommentBlock", + value: content + }]); +} -(0, _index3.default)("AssignmentExpression", { - fields: { - operator: { - validate: (0, _index2.assertValueType)("string") - }, - left: { - validate: (0, _index2.assertNodeType)("LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Expression"] -}); +function addComments(type, comments) { + if (!comments) return; -(0, _index3.default)("BinaryExpression", { - builder: ["operator", "left", "right"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.BINARY_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - visitor: ["left", "right"], - aliases: ["Binary", "Expression"] -}); + var node = this.node; + if (!node) return; -(0, _index3.default)("Directive", { - visitor: ["value"], - fields: { - value: { - validate: (0, _index2.assertNodeType)("DirectiveLiteral") - } - } -}); + var key = type + "Comments"; -(0, _index3.default)("DirectiveLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } + if (node[key]) { + node[key] = node[key].concat(comments); + } else { + node[key] = comments; } -}); - -(0, _index3.default)("BlockStatement", { - builder: ["body", "directives"], - visitor: ["directives", "body"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "Statement"] -}); +} +},{}],153:[function(require,module,exports){ +"use strict"; -(0, _index3.default)("BreakStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); +exports.__esModule = true; -(0, _index3.default)("CallExpression", { - visitor: ["callee", "arguments"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - }, - aliases: ["Expression"] -}); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -(0, _index3.default)("CatchClause", { - visitor: ["param", "body"], - fields: { - param: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - } - }, - aliases: ["Scopable"] -}); +var _getIterator3 = _interopRequireDefault(_getIterator2); -(0, _index3.default)("ConditionalExpression", { - visitor: ["test", "consequent", "alternate"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Expression") - }, - alternate: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Expression", "Conditional"] -}); +exports.call = call; +exports._call = _call; +exports.isBlacklisted = isBlacklisted; +exports.visit = visit; +exports.skip = skip; +exports.skipKey = skipKey; +exports.stop = stop; +exports.setScope = setScope; +exports.setContext = setContext; +exports.resync = resync; +exports._resyncParent = _resyncParent; +exports._resyncKey = _resyncKey; +exports._resyncList = _resyncList; +exports._resyncRemoved = _resyncRemoved; +exports.popContext = popContext; +exports.pushContext = pushContext; +exports.setup = setup; +exports.setKey = setKey; +exports.requeue = requeue; +exports._getQueueContexts = _getQueueContexts; -(0, _index3.default)("ContinueStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); +var _index = require("../index"); -(0, _index3.default)("DebuggerStatement", { - aliases: ["Statement"] -}); +var _index2 = _interopRequireDefault(_index); -(0, _index3.default)("DoWhileStatement", { - visitor: ["test", "body"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - }, - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] -}); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -(0, _index3.default)("EmptyStatement", { - aliases: ["Statement"] -}); +function call(key) { + var opts = this.opts; -(0, _index3.default)("ExpressionStatement", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Statement", "ExpressionWrapper"] -}); + this.debug(function () { + return key; + }); -(0, _index3.default)("File", { - builder: ["program", "comments", "tokens"], - visitor: ["program"], - fields: { - program: { - validate: (0, _index2.assertNodeType)("Program") - } + if (this.node) { + if (this._call(opts[key])) return true; } -}); -(0, _index3.default)("ForInStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } + if (this.node) { + return this._call(opts[this.node.type] && opts[this.node.type][key]); } -}); -(0, _index3.default)("ForStatement", { - visitor: ["init", "test", "update", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], - fields: { - init: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "Expression"), - optional: true - }, - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - update: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") + return false; +} + +function _call(fns) { + if (!fns) return false; + + for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } + + var fn = _ref; + + if (!fn) continue; + + var node = this.node; + if (!node) return true; + + var ret = fn.call(this.state, this, this.state); + if (ret) throw new Error("Unexpected return value from visitor method " + fn); + + if (this.node !== node) return true; + + if (this.shouldStop || this.shouldSkip || this.removed) return true; } -}); -(0, _index3.default)("FunctionDeclaration", { - builder: ["id", "params", "body", "generator", "async"], - visitor: ["id", "params", "body", "returnType", "typeParameters"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] -}); + return false; +} -(0, _index3.default)("FunctionExpression", { - inherits: "FunctionDeclaration", - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } +function isBlacklisted() { + var blacklist = this.opts.blacklist; + return blacklist && blacklist.indexOf(this.node.type) > -1; +} + +function visit() { + if (!this.node) { + return false; } -}); -(0, _index3.default)("Identifier", { - builder: ["name"], - visitor: ["typeAnnotation"], - aliases: ["Expression", "LVal"], - fields: { - name: { - validate: function validate(node, key, val) { - if (!t.isValidIdentifier(val)) {} - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } + if (this.isBlacklisted()) { + return false; } -}); -(0, _index3.default)("IfStatement", { - visitor: ["test", "consequent", "alternate"], - aliases: ["Statement", "Conditional"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Statement") - }, - alternate: { - optional: true, - validate: (0, _index2.assertNodeType)("Statement") - } + if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { + return false; } -}); -(0, _index3.default)("LabeledStatement", { - visitor: ["label", "body"], - aliases: ["Statement"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } + if (this.call("enter") || this.shouldSkip) { + this.debug(function () { + return "Skip..."; + }); + return this.shouldStop; } -}); -(0, _index3.default)("StringLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + this.debug(function () { + return "Recursing into..."; + }); + _index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); -(0, _index3.default)("NumericLiteral", { - builder: ["value"], - deprecatedAlias: "NumberLiteral", - fields: { - value: { - validate: (0, _index2.assertValueType)("number") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + this.call("exit"); -(0, _index3.default)("NullLiteral", { - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); + return this.shouldStop; +} -(0, _index3.default)("BooleanLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); +function skip() { + this.shouldSkip = true; +} -(0, _index3.default)("RegExpLiteral", { - builder: ["pattern", "flags"], - deprecatedAlias: "RegexLiteral", - aliases: ["Expression", "Literal"], - fields: { - pattern: { - validate: (0, _index2.assertValueType)("string") - }, - flags: { - validate: (0, _index2.assertValueType)("string"), - default: "" - } - } -}); +function skipKey(key) { + this.skipKeys[key] = true; +} -(0, _index3.default)("LogicalExpression", { - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Binary", "Expression"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.LOGICAL_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); +function stop() { + this.shouldStop = true; + this.shouldSkip = true; +} -(0, _index3.default)("MemberExpression", { - builder: ["object", "property", "computed"], - visitor: ["object", "property"], - aliases: ["Expression", "LVal"], - fields: { - object: { - validate: (0, _index2.assertNodeType)("Expression") - }, - property: { - validate: function validate(node, key, val) { - var expectedType = node.computed ? "Expression" : "Identifier"; - (0, _index2.assertNodeType)(expectedType)(node, key, val); - } - }, - computed: { - default: false - } - } -}); +function setScope() { + if (this.opts && this.opts.noScope) return; -(0, _index3.default)("NewExpression", { - visitor: ["callee", "arguments"], - aliases: ["Expression"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) + var target = this.context && this.context.scope; + + if (!target) { + var path = this.parentPath; + while (path && !target) { + if (path.opts && path.opts.noScope) return; + + target = path.scope; + path = path.parentPath; } } -}); -(0, _index3.default)("Program", { - visitor: ["directives", "body"], - builder: ["body", "directives"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"] -}); + this.scope = this.getScope(target); + if (this.scope) this.scope.init(); +} -(0, _index3.default)("ObjectExpression", { - visitor: ["properties"], - aliases: ["Expression"], - fields: { - properties: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty"))) - } +function setContext(context) { + this.shouldSkip = false; + this.shouldStop = false; + this.removed = false; + this.skipKeys = {}; + + if (context) { + this.context = context; + this.state = context.state; + this.opts = context.opts; } -}); -(0, _index3.default)("ObjectMethod", { - builder: ["kind", "key", "params", "body", "computed"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("method", "get", "set")), - default: "method" - }, - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] -}); + this.setScope(); -(0, _index3.default)("ObjectProperty", { - builder: ["key", "value", "computed", "shorthand", "decorators"], - fields: { - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - value: { - validate: (0, _index2.assertNodeType)("Expression", "Pattern", "RestElement") - }, - shorthand: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))), - optional: true - } - }, - visitor: ["key", "value", "decorators"], - aliases: ["UserWhitespacable", "Property", "ObjectMember"] -}); + return this; +} -(0, _index3.default)("RestElement", { - visitor: ["argument", "typeAnnotation"], - aliases: ["LVal"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("LVal") - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); +function resync() { + if (this.removed) return; -(0, _index3.default)("ReturnStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - } + this._resyncParent(); + this._resyncList(); + this._resyncKey(); +} + +function _resyncParent() { + if (this.parentPath) { + this.parent = this.parentPath.node; } -}); +} -(0, _index3.default)("SequenceExpression", { - visitor: ["expressions"], - fields: { - expressions: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression"))) - } - }, - aliases: ["Expression"] -}); +function _resyncKey() { + if (!this.container) return; -(0, _index3.default)("SwitchCase", { - visitor: ["test", "consequent"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - consequent: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - } -}); + if (this.node === this.container[this.key]) return; -(0, _index3.default)("SwitchStatement", { - visitor: ["discriminant", "cases"], - aliases: ["Statement", "BlockParent", "Scopable"], - fields: { - discriminant: { - validate: (0, _index2.assertNodeType)("Expression") - }, - cases: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("SwitchCase"))) + if (Array.isArray(this.container)) { + for (var i = 0; i < this.container.length; i++) { + if (this.container[i] === this.node) { + return this.setKey(i); + } + } + } else { + for (var key in this.container) { + if (this.container[key] === this.node) { + return this.setKey(key); + } } } -}); -(0, _index3.default)("ThisExpression", { - aliases: ["Expression"] -}); + this.key = null; +} -(0, _index3.default)("ThrowStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); +function _resyncList() { + if (!this.parent || !this.inList) return; -(0, _index3.default)("TryStatement", { - visitor: ["block", "handler", "finalizer"], - aliases: ["Statement"], - fields: { - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - handler: { - optional: true, - handler: (0, _index2.assertNodeType)("BlockStatement") - }, - finalizer: { - optional: true, - validate: (0, _index2.assertNodeType)("BlockStatement") - } + var newContainer = this.parent[this.listKey]; + if (this.container === newContainer) return; + + this.container = newContainer || null; +} + +function _resyncRemoved() { + if (this.key == null || !this.container || this.container[this.key] !== this.node) { + this._markRemoved(); } -}); +} -(0, _index3.default)("UnaryExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: true - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UNARY_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["UnaryLike", "Expression"] -}); +function popContext() { + this.contexts.pop(); + this.setContext(this.contexts[this.contexts.length - 1]); +} -(0, _index3.default)("UpdateExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: false - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UPDATE_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["Expression"] -}); +function pushContext(context) { + this.contexts.push(context); + this.setContext(context); +} -(0, _index3.default)("VariableDeclaration", { - builder: ["kind", "declarations"], - visitor: ["declarations"], - aliases: ["Statement", "Declaration"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("var", "let", "const")) - }, - declarations: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("VariableDeclarator"))) +function setup(parentPath, container, listKey, key) { + this.inList = !!listKey; + this.listKey = listKey; + this.parentKey = listKey || key; + this.container = container; + + this.parentPath = parentPath || this.parentPath; + this.setKey(key); +} + +function setKey(key) { + this.key = key; + this.node = this.container[this.key]; + this.type = this.node && this.node.type; +} + +function requeue() { + var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this; + + if (pathToQueue.removed) return; + + var contexts = this.contexts; + + for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } + + var context = _ref2; + + context.maybeQueue(pathToQueue); } -}); +} -(0, _index3.default)("VariableDeclarator", { - visitor: ["id", "init"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("LVal") - }, - init: { - optional: true, - validate: (0, _index2.assertNodeType)("Expression") - } +function _getQueueContexts() { + var path = this; + var contexts = this.contexts; + while (!contexts.length) { + path = path.parentPath; + contexts = path.contexts; } -}); + return contexts; +} +},{"../index":150,"babel-runtime/core-js/get-iterator":127}],154:[function(require,module,exports){ +"use strict"; -(0, _index3.default)("WhileStatement", { - visitor: ["test", "body"], - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } +exports.__esModule = true; +exports.toComputedKey = toComputedKey; +exports.ensureBlock = ensureBlock; +exports.arrowFunctionToShadowed = arrowFunctionToShadowed; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function toComputedKey() { + var node = this.node; + + var key = void 0; + if (this.isMemberExpression()) { + key = node.property; + } else if (this.isProperty() || this.isMethod()) { + key = node.key; + } else { + throw new ReferenceError("todo"); } -}); -(0, _index3.default)("WithStatement", { - visitor: ["object", "body"], - aliases: ["Statement"], - fields: { - object: { - object: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } + if (!node.computed) { + if (t.isIdentifier(key)) key = t.stringLiteral(key.name); } -}); -},{"../constants":134,"../index":145,"./index":140}],137:[function(require,module,exports){ + + return key; +} + +function ensureBlock() { + return t.ensureBlock(this.node); +} + +function arrowFunctionToShadowed() { + if (!this.isArrowFunctionExpression()) return; + + this.ensureBlock(); + + var node = this.node; + + node.expression = false; + node.type = "FunctionExpression"; + node.shadow = node.shadow || true; +} +},{"babel-types":183}],155:[function(require,module,exports){ +(function (global){ "use strict"; -var _index = require("./index"); +exports.__esModule = true; -var _index2 = _interopRequireDefault(_index); +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _map = require("babel-runtime/core-js/map"); + +var _map2 = _interopRequireDefault(_map); + +exports.evaluateTruthy = evaluateTruthy; +exports.evaluate = evaluate; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -(0, _index2.default)("AssignmentPattern", { - visitor: ["left", "right"], - aliases: ["Pattern", "LVal"], - fields: { - left: { - validate: (0, _index.assertNodeType)("Identifier") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } +var VALID_CALLEES = ["String", "Number", "Math"]; +var INVALID_METHODS = ["random"]; + +function evaluateTruthy() { + var res = this.evaluate(); + if (res.confident) return !!res.value; +} + +function evaluate() { + var confident = true; + var deoptPath = void 0; + var seen = new _map2.default(); + + function deopt(path) { + if (!confident) return; + deoptPath = path; + confident = false; } -}); -(0, _index2.default)("ArrayPattern", { - visitor: ["elements", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - elements: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Identifier", "Pattern", "RestElement"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + var value = evaluate(this); + if (!confident) value = undefined; + return { + confident: confident, + deopt: deoptPath, + value: value + }; + + function evaluate(path) { + var node = path.node; + + + if (seen.has(node)) { + var existing = seen.get(node); + if (existing.resolved) { + return existing.value; + } else { + deopt(path); + return; + } + } else { + var item = { resolved: false }; + seen.set(node, item); + + var val = _evaluate(path); + if (confident) { + item.resolved = true; + item.value = val; + } + return val; } } -}); -(0, _index2.default)("ArrowFunctionExpression", { - builder: ["params", "body", "async"], - visitor: ["params", "body", "returnType", "typeParameters"], - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement", "Expression") - }, - async: { - validate: (0, _index.assertValueType)("boolean"), - default: false + function _evaluate(path) { + if (!confident) return; + + var node = path.node; + + + if (path.isSequenceExpression()) { + var exprs = path.get("expressions"); + return evaluate(exprs[exprs.length - 1]); } - } -}); -(0, _index2.default)("ClassBody", { - visitor: ["body"], - fields: { - body: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ClassMethod", "ClassProperty"))) + if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { + return node.value; } - } -}); -(0, _index2.default)("ClassDeclaration", { - builder: ["id", "superClass", "body", "decorators"], - visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], - aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], - fields: { - id: { - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + if (path.isNullLiteral()) { + return null; } - } -}); -(0, _index2.default)("ClassExpression", { - inherits: "ClassDeclaration", - aliases: ["Scopable", "Class", "Expression", "Pureish"], - fields: { - id: { - optional: true, - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); + if (path.isTemplateLiteral()) { + var str = ""; -(0, _index2.default)("ExportAllDeclaration", { - visitor: ["source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); + var i = 0; + var _exprs = path.get("expressions"); -(0, _index2.default)("ExportDefaultDeclaration", { - visitor: ["declaration"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("FunctionDeclaration", "ClassDeclaration", "Expression") - } - } -}); + for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -(0, _index2.default)("ExportNamedDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("Declaration"), - optional: true - }, - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ExportSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral"), - optional: true - } - } -}); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } -(0, _index2.default)("ExportSpecifier", { - visitor: ["local", "exported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + var elem = _ref; -(0, _index2.default)("ForOfStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); + if (!confident) break; -(0, _index2.default)("ImportDeclaration", { - visitor: ["specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration"], - fields: { - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); + str += elem.value.cooked; -(0, _index2.default)("ImportDefaultSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + var expr = _exprs[i++]; + if (expr) str += String(evaluate(expr)); + } -(0, _index2.default)("ImportNamespaceSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") + if (!confident) return; + return str; } - } -}); -(0, _index2.default)("ImportSpecifier", { - visitor: ["local", "imported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - imported: { - validate: (0, _index.assertNodeType)("Identifier") - }, - importKind: { - validate: (0, _index.assertOneOf)(null, "type", "typeof") + if (path.isConditionalExpression()) { + var testResult = evaluate(path.get("test")); + if (!confident) return; + if (testResult) { + return evaluate(path.get("consequent")); + } else { + return evaluate(path.get("alternate")); + } } - } -}); -(0, _index2.default)("MetaProperty", { - visitor: ["meta", "property"], - aliases: ["Expression"], - fields: { - meta: { - validate: (0, _index.assertValueType)("string") - }, - property: { - validate: (0, _index.assertValueType)("string") + if (path.isExpressionWrapper()) { + return evaluate(path.get("expression")); } - } -}); -(0, _index2.default)("ClassMethod", { - aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], - builder: ["kind", "key", "params", "body", "computed", "static"], - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - fields: { - kind: { - validate: (0, _index.chain)((0, _index.assertValueType)("string"), (0, _index.assertOneOf)("get", "set", "method", "constructor")), - default: "method" - }, - computed: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - static: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { + var property = path.get("property"); + var object = path.get("object"); + + if (object.isLiteral() && property.isIdentifier()) { + var _value = object.node.value; + var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); + if (type === "number" || type === "string") { + return _value[property.node.name]; + } } - }, - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index.assertValueType)("boolean") } - } -}); -(0, _index2.default)("ObjectPattern", { - visitor: ["properties", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - properties: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("RestProperty", "Property"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); + if (path.isReferencedIdentifier()) { + var binding = path.scope.getBinding(node.name); -(0, _index2.default)("SpreadElement", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + if (binding && binding.constantViolations.length > 0) { + return deopt(binding.path); + } -(0, _index2.default)("Super", { - aliases: ["Expression"] -}); + if (binding && path.node.start < binding.path.node.end) { + return deopt(binding.path); + } -(0, _index2.default)("TaggedTemplateExpression", { - visitor: ["tag", "quasi"], - aliases: ["Expression"], - fields: { - tag: { - validate: (0, _index.assertNodeType)("Expression") - }, - quasi: { - validate: (0, _index.assertNodeType)("TemplateLiteral") - } - } -}); + if (binding && binding.hasValue) { + return binding.value; + } else { + if (node.name === "undefined") { + return binding ? deopt(binding.path) : undefined; + } else if (node.name === "Infinity") { + return binding ? deopt(binding.path) : Infinity; + } else if (node.name === "NaN") { + return binding ? deopt(binding.path) : NaN; + } -(0, _index2.default)("TemplateElement", { - builder: ["value", "tail"], - fields: { - value: {}, - tail: { - validate: (0, _index.assertValueType)("boolean"), - default: false + var resolved = path.resolve(); + if (resolved === path) { + return deopt(path); + } else { + return evaluate(resolved); + } + } } - } -}); -(0, _index2.default)("TemplateLiteral", { - visitor: ["quasis", "expressions"], - aliases: ["Expression", "Literal"], - fields: { - quasis: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("TemplateElement"))) - }, - expressions: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) - } - } -}); + if (path.isUnaryExpression({ prefix: true })) { + if (node.operator === "void") { + return undefined; + } -(0, _index2.default)("YieldExpression", { - builder: ["argument", "delegate"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - delegate: { - validate: (0, _index.assertValueType)("boolean"), - default: false - }, - argument: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") + var argument = path.get("argument"); + if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { + return "function"; + } + + var arg = evaluate(argument); + if (!confident) return; + switch (node.operator) { + case "!": + return !arg; + case "+": + return +arg; + case "-": + return -arg; + case "~": + return ~arg; + case "typeof": + return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); + } } - } -}); -},{"./index":140}],138:[function(require,module,exports){ -"use strict"; -var _index = require("./index"); + if (path.isArrayExpression()) { + var arr = []; + var elems = path.get("elements"); + for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; -var _index2 = _interopRequireDefault(_index); + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _elem = _ref2; -(0, _index2.default)("AwaitExpression", { - builder: ["argument"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + _elem = _elem.evaluate(); -(0, _index2.default)("ForAwaitStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") + if (_elem.confident) { + arr.push(_elem.value); + } else { + return deopt(_elem); + } + } + return arr; } - } -}); -(0, _index2.default)("BindExpression", { - visitor: ["object", "callee"], - aliases: ["Expression"], - fields: {} -}); + if (path.isObjectExpression()) { + var obj = {}; + var props = path.get("properties"); + for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; -(0, _index2.default)("Import", { - aliases: ["Expression"] -}); + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } -(0, _index2.default)("Decorator", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + var prop = _ref3; -(0, _index2.default)("DoExpression", { - visitor: ["body"], - aliases: ["Expression"], - fields: { - body: { - validate: (0, _index.assertNodeType)("BlockStatement") + if (prop.isObjectMethod() || prop.isSpreadProperty()) { + return deopt(prop); + } + var keyPath = prop.get("key"); + var key = keyPath; + if (prop.node.computed) { + key = key.evaluate(); + if (!key.confident) { + return deopt(keyPath); + } + key = key.value; + } else if (key.isIdentifier()) { + key = key.node.name; + } else { + key = key.node.value; + } + var valuePath = prop.get("value"); + var _value2 = valuePath.evaluate(); + if (!_value2.confident) { + return deopt(valuePath); + } + _value2 = _value2.value; + obj[key] = _value2; + } + return obj; } - } -}); -(0, _index2.default)("ExportDefaultSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + if (path.isLogicalExpression()) { + var wasConfident = confident; + var left = evaluate(path.get("left")); + var leftConfident = confident; + confident = wasConfident; + var right = evaluate(path.get("right")); + var rightConfident = confident; + confident = leftConfident && rightConfident; -(0, _index2.default)("ExportNamespaceSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); + switch (node.operator) { + case "||": + if (left && leftConfident) { + confident = true; + return left; + } -(0, _index2.default)("RestProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("LVal") - } - } -}); + if (!confident) return; -(0, _index2.default)("SpreadProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":140}],139:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); + return left || right; + case "&&": + if (!left && leftConfident || !right && rightConfident) { + confident = true; + } -var _index2 = _interopRequireDefault(_index); + if (!confident) return; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return left && right; + } + } -(0, _index2.default)("AnyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + if (path.isBinaryExpression()) { + var _left = evaluate(path.get("left")); + if (!confident) return; + var _right = evaluate(path.get("right")); + if (!confident) return; -(0, _index2.default)("ArrayTypeAnnotation", { - visitor: ["elementType"], - aliases: ["Flow"], - fields: {} -}); + switch (node.operator) { + case "-": + return _left - _right; + case "+": + return _left + _right; + case "/": + return _left / _right; + case "*": + return _left * _right; + case "%": + return _left % _right; + case "**": + return Math.pow(_left, _right); + case "<": + return _left < _right; + case ">": + return _left > _right; + case "<=": + return _left <= _right; + case ">=": + return _left >= _right; + case "==": + return _left == _right; + case "!=": + return _left != _right; + case "===": + return _left === _right; + case "!==": + return _left !== _right; + case "|": + return _left | _right; + case "&": + return _left & _right; + case "^": + return _left ^ _right; + case "<<": + return _left << _right; + case ">>": + return _left >> _right; + case ">>>": + return _left >>> _right; + } + } -(0, _index2.default)("BooleanTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + if (path.isCallExpression()) { + var callee = path.get("callee"); + var context = void 0; + var func = void 0; -(0, _index2.default)("BooleanLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); + if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { + func = global[node.callee.name]; + } -(0, _index2.default)("NullLiteralTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + if (callee.isMemberExpression()) { + var _object = callee.get("object"); + var _property = callee.get("property"); -(0, _index2.default)("ClassImplements", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); + if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { + context = global[_object.node.name]; + func = context[_property.node.name]; + } -(0, _index2.default)("ClassProperty", { - visitor: ["key", "value", "typeAnnotation", "decorators"], - builder: ["key", "value", "typeAnnotation", "decorators", "computed"], - aliases: ["Property"], - fields: { - computed: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); + if (_object.isLiteral() && _property.isIdentifier()) { + var _type = (0, _typeof3.default)(_object.node.value); + if (_type === "string" || _type === "number") { + context = _object.node.value; + func = context[_property.node.name]; + } + } + } -(0, _index2.default)("DeclareClass", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + if (func) { + var args = path.get("arguments").map(evaluate); + if (!confident) return; -(0, _index2.default)("DeclareFunction", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + return func.apply(context, args); + } + } -(0, _index2.default)("DeclareInterface", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); + deopt(path); + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/map":129,"babel-runtime/helpers/typeof":145}],156:[function(require,module,exports){ +"use strict"; -(0, _index2.default)("DeclareModule", { - visitor: ["id", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +exports.__esModule = true; -(0, _index2.default)("DeclareModuleExports", { - visitor: ["typeAnnotation"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +var _create = require("babel-runtime/core-js/object/create"); -(0, _index2.default)("DeclareTypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +var _create2 = _interopRequireDefault(_create); -(0, _index2.default)("DeclareVariable", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -(0, _index2.default)("ExistentialTypeParam", { - aliases: ["Flow"] -}); +var _getIterator3 = _interopRequireDefault(_getIterator2); -(0, _index2.default)("FunctionTypeAnnotation", { - visitor: ["typeParameters", "params", "rest", "returnType"], - aliases: ["Flow"], - fields: {} -}); +exports.getStatementParent = getStatementParent; +exports.getOpposite = getOpposite; +exports.getCompletionRecords = getCompletionRecords; +exports.getSibling = getSibling; +exports.getPrevSibling = getPrevSibling; +exports.getNextSibling = getNextSibling; +exports.getAllNextSiblings = getAllNextSiblings; +exports.getAllPrevSiblings = getAllPrevSiblings; +exports.get = get; +exports._getKey = _getKey; +exports._getPattern = _getPattern; +exports.getBindingIdentifiers = getBindingIdentifiers; +exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; +exports.getBindingIdentifierPaths = getBindingIdentifierPaths; +exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; -(0, _index2.default)("FunctionTypeParam", { - visitor: ["name", "typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); +var _index = require("./index"); -(0, _index2.default)("GenericTypeAnnotation", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); +var _index2 = _interopRequireDefault(_index); -(0, _index2.default)("InterfaceExtends", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); +var _babelTypes = require("babel-types"); -(0, _index2.default)("InterfaceDeclaration", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +var t = _interopRequireWildcard(_babelTypes); -(0, _index2.default)("IntersectionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -(0, _index2.default)("MixedTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -(0, _index2.default)("EmptyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); +function getStatementParent() { + var path = this; -(0, _index2.default)("NullableTypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); + do { + if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { + break; + } else { + path = path.parentPath; + } + } while (path); -(0, _index2.default)("NumericLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); + if (path && (path.isProgram() || path.isFile())) { + throw new Error("File/Program node, we can't possibly find a statement parent to this"); + } -(0, _index2.default)("NumberTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + return path; +} -(0, _index2.default)("StringLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); +function getOpposite() { + if (this.key === "left") { + return this.getSibling("right"); + } else if (this.key === "right") { + return this.getSibling("left"); + } +} -(0, _index2.default)("StringTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); +function getCompletionRecords() { + var paths = []; -(0, _index2.default)("ThisTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); + var add = function add(path) { + if (path) paths = paths.concat(path.getCompletionRecords()); + }; -(0, _index2.default)("TupleTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); + if (this.isIfStatement()) { + add(this.get("consequent")); + add(this.get("alternate")); + } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { + add(this.get("body")); + } else if (this.isProgram() || this.isBlockStatement()) { + add(this.get("body").pop()); + } else if (this.isFunction()) { + return this.get("body").getCompletionRecords(); + } else if (this.isTryStatement()) { + add(this.get("block")); + add(this.get("handler")); + add(this.get("finalizer")); + } else { + paths.push(this); + } -(0, _index2.default)("TypeofTypeAnnotation", { - visitor: ["argument"], - aliases: ["Flow"], - fields: {} -}); + return paths; +} -(0, _index2.default)("TypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); +function getSibling(key) { + return _index2.default.get({ + parentPath: this.parentPath, + parent: this.parent, + container: this.container, + listKey: this.listKey, + key: key + }); +} -(0, _index2.default)("TypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); +function getPrevSibling() { + return this.getSibling(this.key - 1); +} -(0, _index2.default)("TypeCastExpression", { - visitor: ["expression", "typeAnnotation"], - aliases: ["Flow", "ExpressionWrapper", "Expression"], - fields: {} -}); +function getNextSibling() { + return this.getSibling(this.key + 1); +} -(0, _index2.default)("TypeParameter", { - visitor: ["bound"], - aliases: ["Flow"], - fields: {} -}); +function getAllNextSiblings() { + var _key = this.key; + var sibling = this.getSibling(++_key); + var siblings = []; + while (sibling.node) { + siblings.push(sibling); + sibling = this.getSibling(++_key); + } + return siblings; +} -(0, _index2.default)("TypeParameterDeclaration", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); +function getAllPrevSiblings() { + var _key = this.key; + var sibling = this.getSibling(--_key); + var siblings = []; + while (sibling.node) { + siblings.push(sibling); + sibling = this.getSibling(--_key); + } + return siblings; +} -(0, _index2.default)("TypeParameterInstantiation", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); +function get(key, context) { + if (context === true) context = this.context; + var parts = key.split("."); + if (parts.length === 1) { + return this._getKey(key, context); + } else { + return this._getPattern(parts, context); + } +} -(0, _index2.default)("ObjectTypeAnnotation", { - visitor: ["properties", "indexers", "callProperties"], - aliases: ["Flow"], - fields: {} -}); +function _getKey(key, context) { + var _this = this; -(0, _index2.default)("ObjectTypeCallProperty", { - visitor: ["value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + var node = this.node; + var container = node[key]; -(0, _index2.default)("ObjectTypeIndexer", { - visitor: ["id", "key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + if (Array.isArray(container)) { + return container.map(function (_, i) { + return _index2.default.get({ + listKey: key, + parentPath: _this, + parent: node, + container: container, + key: i + }).setContext(context); + }); + } else { + return _index2.default.get({ + parentPath: this, + parent: node, + container: node, + key: key + }).setContext(context); + } +} -(0, _index2.default)("ObjectTypeProperty", { - visitor: ["key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); +function _getPattern(parts, context) { + var path = this; + for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -(0, _index2.default)("ObjectTypeSpreadProperty", { - visitor: ["argument"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } -(0, _index2.default)("QualifiedTypeIdentifier", { - visitor: ["id", "qualification"], - aliases: ["Flow"], - fields: {} -}); + var part = _ref; -(0, _index2.default)("UnionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); + if (part === ".") { + path = path.parentPath; + } else { + if (Array.isArray(path)) { + path = path[part]; + } else { + path = path.get(part, context); + } + } + } + return path; +} -(0, _index2.default)("VoidTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -},{"./index":140}],140:[function(require,module,exports){ -"use strict"; +function getBindingIdentifiers(duplicates) { + return t.getBindingIdentifiers(this.node, duplicates); +} -exports.__esModule = true; -exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; +function getOuterBindingIdentifiers(duplicates) { + return t.getOuterBindingIdentifiers(this.node, duplicates); +} -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +function getBindingIdentifierPaths() { + var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; -var _getIterator3 = _interopRequireDefault(_getIterator2); + var path = this; + var search = [].concat(path); + var ids = (0, _create2.default)(null); -var _stringify = require("babel-runtime/core-js/json/stringify"); + while (search.length) { + var id = search.shift(); + if (!id) continue; + if (!id.node) continue; -var _stringify2 = _interopRequireDefault(_stringify); + var keys = t.getBindingIdentifiers.keys[id.node.type]; -var _typeof2 = require("babel-runtime/helpers/typeof"); + if (id.isIdentifier()) { + if (duplicates) { + var _ids = ids[id.node.name] = ids[id.node.name] || []; + _ids.push(id); + } else { + ids[id.node.name] = id; + } + continue; + } -var _typeof3 = _interopRequireDefault(_typeof2); + if (id.isExportDeclaration()) { + var declaration = id.get("declaration"); + if (declaration.isDeclaration()) { + search.push(declaration); + } + continue; + } -exports.assertEach = assertEach; -exports.assertOneOf = assertOneOf; -exports.assertNodeType = assertNodeType; -exports.assertNodeOrValueType = assertNodeOrValueType; -exports.assertValueType = assertValueType; -exports.chain = chain; -exports.default = defineType; + if (outerOnly) { + if (id.isFunctionDeclaration()) { + search.push(id.get("id")); + continue; + } + if (id.isFunctionExpression()) { + continue; + } + } -var _index = require("../index"); + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var child = id.get(key); + if (Array.isArray(child) || child.node) { + search = search.concat(child); + } + } + } + } -var t = _interopRequireWildcard(_index); + return ids; +} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function getOuterBindingIdentifierPaths(duplicates) { + return this.getBindingIdentifierPaths(duplicates, true); +} +},{"./index":157,"babel-runtime/core-js/get-iterator":127,"babel-runtime/core-js/object/create":132,"babel-types":183}],157:[function(require,module,exports){ +"use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.__esModule = true; -var VISITOR_KEYS = exports.VISITOR_KEYS = {}; -var ALIAS_KEYS = exports.ALIAS_KEYS = {}; -var NODE_FIELDS = exports.NODE_FIELDS = {}; -var BUILDER_KEYS = exports.BUILDER_KEYS = {}; -var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -function getType(val) { - if (Array.isArray(val)) { - return "array"; - } else if (val === null) { - return "null"; - } else if (val === undefined) { - return "undefined"; - } else { - return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); - } -} +var _getIterator3 = _interopRequireDefault(_getIterator2); -function assertEach(callback) { - function validator(node, key, val) { - if (!Array.isArray(val)) return; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - for (var i = 0; i < val.length; i++) { - callback(node, key + "[" + i + "]", val[i]); - } - } - validator.each = callback; - return validator; -} +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -function assertOneOf() { - for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { - vals[_key] = arguments[_key]; - } +var _virtualTypes = require("./lib/virtual-types"); - function validate(node, key, val) { - if (vals.indexOf(val) < 0) { - throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); - } - } +var virtualTypes = _interopRequireWildcard(_virtualTypes); - validate.oneOf = vals; +var _debug2 = require("debug"); - return validate; -} +var _debug3 = _interopRequireDefault(_debug2); -function assertNodeType() { - for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - types[_key2] = arguments[_key2]; - } +var _invariant = require("invariant"); - function validate(node, key, val) { - var valid = false; +var _invariant2 = _interopRequireDefault(_invariant); - for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +var _index = require("../index"); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +var _index2 = _interopRequireDefault(_index); - var type = _ref; +var _assign = require("lodash/assign"); - if (t.is(type, val)) { - valid = true; - break; - } - } +var _assign2 = _interopRequireDefault(_assign); - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); - } - } +var _scope = require("../scope"); - validate.oneOfNodeTypes = types; +var _scope2 = _interopRequireDefault(_scope); - return validate; -} +var _babelTypes = require("babel-types"); -function assertNodeOrValueType() { - for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - types[_key3] = arguments[_key3]; +var t = _interopRequireWildcard(_babelTypes); + +var _cache = require("../cache"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _debug = (0, _debug3.default)("babel"); + +var NodePath = function () { + function NodePath(hub, parent) { + (0, _classCallCheck3.default)(this, NodePath); + + this.parent = parent; + this.hub = hub; + this.contexts = []; + this.data = {}; + this.shouldSkip = false; + this.shouldStop = false; + this.removed = false; + this.state = null; + this.opts = null; + this.skipKeys = null; + this.parentPath = null; + this.context = null; + this.container = null; + this.listKey = null; + this.inList = false; + this.parentKey = null; + this.key = null; + this.node = null; + this.scope = null; + this.type = null; + this.typeAnnotation = null; } - function validate(node, key, val) { - var valid = false; + NodePath.get = function get(_ref) { + var hub = _ref.hub, + parentPath = _ref.parentPath, + parent = _ref.parent, + container = _ref.container, + listKey = _ref.listKey, + key = _ref.key; - for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (!hub && parentPath) { + hub = parentPath.hub; + } - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); - var type = _ref2; + var targetNode = container[key]; - if (getType(val) === type || t.is(type, val)) { - valid = true; + var paths = _cache.path.get(parent) || []; + if (!_cache.path.has(parent)) { + _cache.path.set(parent, paths); + } + + var path = void 0; + + for (var i = 0; i < paths.length; i++) { + var pathCheck = paths[i]; + if (pathCheck.node === targetNode) { + path = pathCheck; break; } } - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); + if (!path) { + path = new NodePath(hub, parent); + paths.push(path); } - } - validate.oneOfNodeOrValueTypes = types; + path.setup(parentPath, container, listKey, key); - return validate; -} + return path; + }; -function assertValueType(type) { - function validate(node, key, val) { - var valid = getType(val) === type; + NodePath.prototype.getScope = function getScope(scope) { + var ourScope = scope; - if (!valid) { - throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); + if (this.isScope()) { + ourScope = new _scope2.default(this, scope); } - } - validate.type = type; + return ourScope; + }; - return validate; -} + NodePath.prototype.setData = function setData(key, val) { + return this.data[key] = val; + }; -function chain() { - for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - fns[_key4] = arguments[_key4]; - } + NodePath.prototype.getData = function getData(key, def) { + var val = this.data[key]; + if (!val && def) val = this.data[key] = def; + return val; + }; - function validate() { - for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; + NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { + var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } + return this.hub.file.buildCodeFrameError(this.node, msg, Error); + }; - var fn = _ref3; + NodePath.prototype.traverse = function traverse(visitor, state) { + (0, _index2.default)(this.node, visitor, this.scope, state, this); + }; - fn.apply(undefined, arguments); - } - } - validate.chainOf = fns; - return validate; -} + NodePath.prototype.mark = function mark(type, message) { + this.hub.file.metadata.marked.push({ + type: type, + message: message, + loc: this.node.loc + }); + }; -function defineType(type) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + NodePath.prototype.set = function set(key, node) { + t.validate(this.node, key, node); + this.node[key] = node; + }; - var inherits = opts.inherits && store[opts.inherits] || {}; + NodePath.prototype.getPathLocation = function getPathLocation() { + var parts = []; + var path = this; + do { + var key = path.key; + if (path.inList) key = path.listKey + "[" + key + "]"; + parts.unshift(key); + } while (path = path.parentPath); + return parts.join("."); + }; - opts.fields = opts.fields || inherits.fields || {}; - opts.visitor = opts.visitor || inherits.visitor || []; - opts.aliases = opts.aliases || inherits.aliases || []; - opts.builder = opts.builder || inherits.builder || opts.visitor || []; + NodePath.prototype.debug = function debug(buildMessage) { + if (!_debug.enabled) return; + _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); + }; - if (opts.deprecatedAlias) { - DEPRECATED_KEYS[opts.deprecatedAlias] = type; - } + return NodePath; +}(); - for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; +exports.default = NodePath; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - var _key5 = _ref4; +(0, _assign2.default)(NodePath.prototype, require("./ancestry")); +(0, _assign2.default)(NodePath.prototype, require("./inference")); +(0, _assign2.default)(NodePath.prototype, require("./replacement")); +(0, _assign2.default)(NodePath.prototype, require("./evaluation")); +(0, _assign2.default)(NodePath.prototype, require("./conversion")); +(0, _assign2.default)(NodePath.prototype, require("./introspection")); +(0, _assign2.default)(NodePath.prototype, require("./context")); +(0, _assign2.default)(NodePath.prototype, require("./removal")); +(0, _assign2.default)(NodePath.prototype, require("./modification")); +(0, _assign2.default)(NodePath.prototype, require("./family")); +(0, _assign2.default)(NodePath.prototype, require("./comments")); - opts.fields[_key5] = opts.fields[_key5] || {}; +var _loop2 = function _loop2() { + if (_isArray) { + if (_i >= _iterator.length) return "break"; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) return "break"; + _ref2 = _i.value; } - for (var key in opts.fields) { - var field = opts.fields[key]; + var type = _ref2; - if (opts.builder.indexOf(key) === -1) { - field.optional = true; - } - if (field.default === undefined) { - field.default = null; - } else if (!field.validate) { - field.validate = assertValueType(getType(field.default)); + var typeKey = "is" + type; + NodePath.prototype[typeKey] = function (opts) { + return t[typeKey](this.node, opts); + }; + + NodePath.prototype["assert" + type] = function (opts) { + if (!this[typeKey](opts)) { + throw new TypeError("Expected node path of type " + type); } - } + }; +}; - VISITOR_KEYS[type] = opts.visitor; - BUILDER_KEYS[type] = opts.builder; - NODE_FIELDS[type] = opts.fields; - ALIAS_KEYS[type] = opts.aliases; +for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; - store[type] = opts; + var _ret2 = _loop2(); + + if (_ret2 === "break") break; } -var store = {}; -},{"../index":145,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/json/stringify":90,"babel-runtime/helpers/typeof":107}],141:[function(require,module,exports){ +var _loop = function _loop(type) { + if (type[0] === "_") return "continue"; + if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); + + var virtualType = virtualTypes[type]; + + NodePath.prototype["is" + type] = function (opts) { + return virtualType.checkPath(this, opts); + }; +}; + +for (var type in virtualTypes) { + var _ret = _loop(type); + + if (_ret === "continue") continue; +} +module.exports = exports["default"]; +},{"../cache":147,"../index":150,"../scope":169,"./ancestry":151,"./comments":152,"./context":153,"./conversion":154,"./evaluation":155,"./family":156,"./inference":158,"./introspection":161,"./lib/virtual-types":164,"./modification":165,"./removal":166,"./replacement":167,"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/classCallCheck":141,"babel-types":183,"debug":309,"invariant":322,"lodash/assign":490}],158:[function(require,module,exports){ "use strict"; -require("./index"); +exports.__esModule = true; -require("./core"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -require("./es2015"); +var _getIterator3 = _interopRequireDefault(_getIterator2); -require("./flow"); +exports.getTypeAnnotation = getTypeAnnotation; +exports._getTypeAnnotation = _getTypeAnnotation; +exports.isBaseType = isBaseType; +exports.couldBeBaseType = couldBeBaseType; +exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; +exports.isGenericType = isGenericType; -require("./jsx"); +var _inferers = require("./inferers"); -require("./misc"); +var inferers = _interopRequireWildcard(_inferers); -require("./experimental"); -},{"./core":136,"./es2015":137,"./experimental":138,"./flow":139,"./index":140,"./jsx":142,"./misc":143}],142:[function(require,module,exports){ -"use strict"; +var _babelTypes = require("babel-types"); -var _index = require("./index"); +var t = _interopRequireWildcard(_babelTypes); -var _index2 = _interopRequireDefault(_index); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -(0, _index2.default)("JSXAttribute", { - visitor: ["name", "value"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXNamespacedName") - }, - value: { - optional: true, - validate: (0, _index.assertNodeType)("JSXElement", "StringLiteral", "JSXExpressionContainer") - } - } -}); +function getTypeAnnotation() { + if (this.typeAnnotation) return this.typeAnnotation; -(0, _index2.default)("JSXClosingElement", { - visitor: ["name"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - } - } -}); + var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); + if (t.isTypeAnnotation(type)) type = type.typeAnnotation; + return this.typeAnnotation = type; +} -(0, _index2.default)("JSXElement", { - builder: ["openingElement", "closingElement", "children", "selfClosing"], - visitor: ["openingElement", "children", "closingElement"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingElement: { - validate: (0, _index.assertNodeType)("JSXOpeningElement") - }, - closingElement: { - optional: true, - validate: (0, _index.assertNodeType)("JSXClosingElement") - }, - children: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement"))) - } - } -}); +function _getTypeAnnotation() { + var node = this.node; -(0, _index2.default)("JSXEmptyExpression", { - aliases: ["JSX", "Expression"] -}); + if (!node) { + if (this.key === "init" && this.parentPath.isVariableDeclarator()) { + var declar = this.parentPath.parentPath; + var declarParent = declar.parentPath; -(0, _index2.default)("JSXExpressionContainer", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + if (declar.key === "left" && declarParent.isForInStatement()) { + return t.stringTypeAnnotation(); + } -(0, _index2.default)("JSXSpreadChild", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); + if (declar.key === "left" && declarParent.isForOfStatement()) { + return t.anyTypeAnnotation(); + } -(0, _index2.default)("JSXIdentifier", { - builder: ["name"], - aliases: ["JSX", "Expression"], - fields: { - name: { - validate: (0, _index.assertValueType)("string") + return t.voidTypeAnnotation(); + } else { + return; } } -}); -(0, _index2.default)("JSXMemberExpression", { - visitor: ["object", "property"], - aliases: ["JSX", "Expression"], - fields: { - object: { - validate: (0, _index.assertNodeType)("JSXMemberExpression", "JSXIdentifier") - }, - property: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } + if (node.typeAnnotation) { + return node.typeAnnotation; } -}); -(0, _index2.default)("JSXNamespacedName", { - visitor: ["namespace", "name"], - aliases: ["JSX"], - fields: { - namespace: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - }, - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } + var inferer = inferers[node.type]; + if (inferer) { + return inferer.call(this, node); } -}); -(0, _index2.default)("JSXOpeningElement", { - builder: ["name", "attributes", "selfClosing"], - visitor: ["name", "attributes"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - }, - selfClosing: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - attributes: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) - } + inferer = inferers[this.parentPath.type]; + if (inferer && inferer.validParent) { + return this.parentPath.getTypeAnnotation(); } -}); +} -(0, _index2.default)("JSXSpreadAttribute", { - visitor: ["argument"], - aliases: ["JSX"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); +function isBaseType(baseName, soft) { + return _isBaseType(baseName, this.getTypeAnnotation(), soft); +} -(0, _index2.default)("JSXText", { - aliases: ["JSX", "Immutable"], - builder: ["value"], - fields: { - value: { - validate: (0, _index.assertValueType)("string") +function _isBaseType(baseName, type, soft) { + if (baseName === "string") { + return t.isStringTypeAnnotation(type); + } else if (baseName === "number") { + return t.isNumberTypeAnnotation(type); + } else if (baseName === "boolean") { + return t.isBooleanTypeAnnotation(type); + } else if (baseName === "any") { + return t.isAnyTypeAnnotation(type); + } else if (baseName === "mixed") { + return t.isMixedTypeAnnotation(type); + } else if (baseName === "empty") { + return t.isEmptyTypeAnnotation(type); + } else if (baseName === "void") { + return t.isVoidTypeAnnotation(type); + } else { + if (soft) { + return false; + } else { + throw new Error("Unknown base type " + baseName); } } -}); -},{"./index":140}],143:[function(require,module,exports){ -"use strict"; +} -var _index = require("./index"); +function couldBeBaseType(name) { + var type = this.getTypeAnnotation(); + if (t.isAnyTypeAnnotation(type)) return true; -var _index2 = _interopRequireDefault(_index); + if (t.isUnionTypeAnnotation(type)) { + for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } -(0, _index2.default)("Noop", { - visitor: [] -}); + var type2 = _ref; -(0, _index2.default)("ParenthesizedExpression", { - visitor: ["expression"], - aliases: ["Expression", "ExpressionWrapper"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") + if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { + return true; + } } + return false; + } else { + return _isBaseType(name, type, true); } -}); -},{"./index":140}],144:[function(require,module,exports){ +} + +function baseTypeStrictlyMatches(right) { + var left = this.getTypeAnnotation(); + right = right.getTypeAnnotation(); + + if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { + return right.type === left.type; + } +} + +function isGenericType(genericName) { + var type = this.getTypeAnnotation(); + return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); +} +},{"./inferers":160,"babel-runtime/core-js/get-iterator":127,"babel-types":183}],159:[function(require,module,exports){ "use strict"; exports.__esModule = true; -exports.createUnionTypeAnnotation = createUnionTypeAnnotation; -exports.removeTypeDuplicates = removeTypeDuplicates; -exports.createTypeAnnotationBasedOnTypeof = createTypeAnnotationBasedOnTypeof; - -var _index = require("./index"); -var t = _interopRequireWildcard(_index); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _getIterator3 = _interopRequireDefault(_getIterator2); -function createUnionTypeAnnotation(types) { - var flattened = removeTypeDuplicates(types); +exports.default = function (node) { + if (!this.isReferenced()) return; - if (flattened.length === 1) { - return flattened[0]; - } else { - return t.unionTypeAnnotation(flattened); + var binding = this.scope.getBinding(node.name); + if (binding) { + if (binding.identifier.typeAnnotation) { + return binding.identifier.typeAnnotation; + } else { + return getTypeAnnotationBindingConstantViolations(this, node.name); + } } -} -function removeTypeDuplicates(nodes) { - var generics = {}; - var bases = {}; + if (node.name === "undefined") { + return t.voidTypeAnnotation(); + } else if (node.name === "NaN" || node.name === "Infinity") { + return t.numberTypeAnnotation(); + } else if (node.name === "arguments") {} +}; - var typeGroups = []; +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getTypeAnnotationBindingConstantViolations(path, name) { + var binding = path.scope.getBinding(name); var types = []; + path.typeAnnotation = t.unionTypeAnnotation(types); - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; + var functionConstantViolations = []; + var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); - if (types.indexOf(node) >= 0) { - continue; - } + var testType = getConditionalAnnotation(path, name); + if (testType) { + var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); - if (t.isAnyTypeAnnotation(node)) { - return [node]; - } + constantViolations = constantViolations.filter(function (path) { + return testConstantViolations.indexOf(path) < 0; + }); - if (t.isFlowBaseAnnotation(node)) { - bases[node.type] = node; - continue; - } + types.push(testType.typeAnnotation); + } - if (t.isUnionTypeAnnotation(node)) { - if (typeGroups.indexOf(node.types) < 0) { - nodes = nodes.concat(node.types); - typeGroups.push(node.types); - } - continue; - } + if (constantViolations.length) { + constantViolations = constantViolations.concat(functionConstantViolations); - if (t.isGenericTypeAnnotation(node)) { - var name = node.id.name; + for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - if (generics[name]) { - var existing = generics[name]; - if (existing.typeParameters) { - if (node.typeParameters) { - existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); - } - } else { - existing = node.typeParameters; - } + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; } else { - generics[name] = node; + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; } - continue; - } - - types.push(node); - } + var violation = _ref; - for (var type in bases) { - types.push(bases[type]); + types.push(violation.getTypeAnnotation()); + } } - for (var _name in generics) { - types.push(generics[_name]); + if (types.length) { + return t.createUnionTypeAnnotation(types); } +} - return types; +function getConstantViolationsBefore(binding, path, functions) { + var violations = binding.constantViolations.slice(); + violations.unshift(binding.path); + return violations.filter(function (violation) { + violation = violation.resolve(); + var status = violation._guessExecutionStatusRelativeTo(path); + if (functions && status === "function") functions.push(violation); + return status === "before"; + }); } -function createTypeAnnotationBasedOnTypeof(type) { - if (type === "string") { - return t.stringTypeAnnotation(); - } else if (type === "number") { - return t.numberTypeAnnotation(); - } else if (type === "undefined") { - return t.voidTypeAnnotation(); - } else if (type === "boolean") { - return t.booleanTypeAnnotation(); - } else if (type === "function") { - return t.genericTypeAnnotation(t.identifier("Function")); - } else if (type === "object") { - return t.genericTypeAnnotation(t.identifier("Object")); - } else if (type === "symbol") { - return t.genericTypeAnnotation(t.identifier("Symbol")); +function inferAnnotationFromBinaryExpression(name, path) { + var operator = path.node.operator; + + var right = path.get("right").resolve(); + var left = path.get("left").resolve(); + + var target = void 0; + if (left.isIdentifier({ name: name })) { + target = right; + } else if (right.isIdentifier({ name: name })) { + target = left; + } + if (target) { + if (operator === "===") { + return target.getTypeAnnotation(); + } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else { + return; + } } else { - throw new Error("Invalid typeof value"); + if (operator !== "===") return; } -} -},{"./index":145}],145:[function(require,module,exports){ -"use strict"; -exports.__esModule = true; -exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isNodesEquivalent = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; + var typeofPath = void 0; + var typePath = void 0; + if (left.isUnaryExpression({ operator: "typeof" })) { + typeofPath = left; + typePath = right; + } else if (right.isUnaryExpression({ operator: "typeof" })) { + typeofPath = right; + typePath = left; + } + if (!typePath && !typeofPath) return; -var _getOwnPropertySymbols = require("babel-runtime/core-js/object/get-own-property-symbols"); + typePath = typePath.resolve(); + if (!typePath.isLiteral()) return; -var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); + var typeValue = typePath.node.value; + if (typeof typeValue !== "string") return; -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + if (!typeofPath.get("argument").isIdentifier({ name: name })) return; -var _getIterator3 = _interopRequireDefault(_getIterator2); + return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); +} -var _keys = require("babel-runtime/core-js/object/keys"); +function getParentConditionalPath(path) { + var parentPath = void 0; + while (parentPath = path.parentPath) { + if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { + if (path.key === "test") { + return; + } else { + return parentPath; + } + } else { + path = parentPath; + } + } +} -var _keys2 = _interopRequireDefault(_keys); +function getConditionalAnnotation(path, name) { + var ifStatement = getParentConditionalPath(path); + if (!ifStatement) return; -var _stringify = require("babel-runtime/core-js/json/stringify"); + var test = ifStatement.get("test"); + var paths = [test]; + var types = []; -var _stringify2 = _interopRequireDefault(_stringify); + do { + var _path = paths.shift().resolve(); -var _constants = require("./constants"); + if (_path.isLogicalExpression()) { + paths.push(_path.get("left")); + paths.push(_path.get("right")); + } -Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { - enumerable: true, - get: function get() { - return _constants.STATEMENT_OR_BLOCK_KEYS; - } -}); -Object.defineProperty(exports, "FLATTENABLE_KEYS", { - enumerable: true, - get: function get() { - return _constants.FLATTENABLE_KEYS; + if (_path.isBinaryExpression()) { + var type = inferAnnotationFromBinaryExpression(name, _path); + if (type) types.push(type); + } + } while (paths.length); + + if (types.length) { + return { + typeAnnotation: t.createUnionTypeAnnotation(types), + ifStatement: ifStatement + }; + } else { + return getConditionalAnnotation(ifStatement, name); } -}); -Object.defineProperty(exports, "FOR_INIT_KEYS", { +} +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":127,"babel-types":183}],160:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined; + +var _infererReference = require("./inferer-reference"); + +Object.defineProperty(exports, "Identifier", { enumerable: true, get: function get() { - return _constants.FOR_INIT_KEYS; + return _interopRequireDefault(_infererReference).default; } }); -Object.defineProperty(exports, "COMMENT_KEYS", { - enumerable: true, - get: function get() { - return _constants.COMMENT_KEYS; +exports.VariableDeclarator = VariableDeclarator; +exports.TypeCastExpression = TypeCastExpression; +exports.NewExpression = NewExpression; +exports.TemplateLiteral = TemplateLiteral; +exports.UnaryExpression = UnaryExpression; +exports.BinaryExpression = BinaryExpression; +exports.LogicalExpression = LogicalExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.SequenceExpression = SequenceExpression; +exports.AssignmentExpression = AssignmentExpression; +exports.UpdateExpression = UpdateExpression; +exports.StringLiteral = StringLiteral; +exports.NumericLiteral = NumericLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.NullLiteral = NullLiteral; +exports.RegExpLiteral = RegExpLiteral; +exports.ObjectExpression = ObjectExpression; +exports.ArrayExpression = ArrayExpression; +exports.RestElement = RestElement; +exports.CallExpression = CallExpression; +exports.TaggedTemplateExpression = TaggedTemplateExpression; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function VariableDeclarator() { + var id = this.get("id"); + + if (id.isIdentifier()) { + return this.get("init").getTypeAnnotation(); + } else { + return; } -}); -Object.defineProperty(exports, "LOGICAL_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.LOGICAL_OPERATORS; +} + +function TypeCastExpression(node) { + return node.typeAnnotation; +} + +TypeCastExpression.validParent = true; + +function NewExpression(node) { + if (this.get("callee").isIdentifier()) { + return t.genericTypeAnnotation(node.callee); } -}); -Object.defineProperty(exports, "UPDATE_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UPDATE_OPERATORS; +} + +function TemplateLiteral() { + return t.stringTypeAnnotation(); +} + +function UnaryExpression(node) { + var operator = node.operator; + + if (operator === "void") { + return t.voidTypeAnnotation(); + } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.stringTypeAnnotation(); + } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.booleanTypeAnnotation(); } -}); -Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; +} + +function BinaryExpression(node) { + var operator = node.operator; + + if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.booleanTypeAnnotation(); + } else if (operator === "+") { + var right = this.get("right"); + var left = this.get("left"); + + if (left.isBaseType("number") && right.isBaseType("number")) { + return t.numberTypeAnnotation(); + } else if (left.isBaseType("string") || right.isBaseType("string")) { + return t.stringTypeAnnotation(); + } + + return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); } -}); -Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.EQUALITY_BINARY_OPERATORS; +} + +function LogicalExpression() { + return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); +} + +function ConditionalExpression() { + return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); +} + +function SequenceExpression() { + return this.get("expressions").pop().getTypeAnnotation(); +} + +function AssignmentExpression() { + return this.get("right").getTypeAnnotation(); +} + +function UpdateExpression(node) { + var operator = node.operator; + if (operator === "++" || operator === "--") { + return t.numberTypeAnnotation(); } -}); -Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.COMPARISON_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.STRING_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "INHERIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.INHERIT_KEYS; - } -}); -Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { - enumerable: true, - get: function get() { - return _constants.BLOCK_SCOPED_SYMBOL; - } -}); -Object.defineProperty(exports, "NOT_LOCAL_BINDING", { - enumerable: true, - get: function get() { - return _constants.NOT_LOCAL_BINDING; - } -}); -exports.is = is; -exports.isType = isType; -exports.validate = validate; -exports.shallowEqual = shallowEqual; -exports.appendToMemberExpression = appendToMemberExpression; -exports.prependToMemberExpression = prependToMemberExpression; -exports.ensureBlock = ensureBlock; -exports.clone = clone; -exports.cloneWithoutLoc = cloneWithoutLoc; -exports.cloneDeep = cloneDeep; -exports.buildMatchMemberExpression = buildMatchMemberExpression; -exports.removeComments = removeComments; -exports.inheritsComments = inheritsComments; -exports.inheritTrailingComments = inheritTrailingComments; -exports.inheritLeadingComments = inheritLeadingComments; -exports.inheritInnerComments = inheritInnerComments; -exports.inherits = inherits; -exports.assertNode = assertNode; -exports.isNode = isNode; -exports.traverseFast = traverseFast; -exports.removeProperties = removeProperties; -exports.removePropertiesDeep = removePropertiesDeep; +} -var _retrievers = require("./retrievers"); +function StringLiteral() { + return t.stringTypeAnnotation(); +} -Object.defineProperty(exports, "getBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getBindingIdentifiers; - } -}); -Object.defineProperty(exports, "getOuterBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getOuterBindingIdentifiers; - } -}); +function NumericLiteral() { + return t.numberTypeAnnotation(); +} -var _validators = require("./validators"); +function BooleanLiteral() { + return t.booleanTypeAnnotation(); +} -Object.defineProperty(exports, "isBinding", { - enumerable: true, - get: function get() { - return _validators.isBinding; - } -}); -Object.defineProperty(exports, "isReferenced", { - enumerable: true, - get: function get() { - return _validators.isReferenced; - } -}); -Object.defineProperty(exports, "isValidIdentifier", { - enumerable: true, - get: function get() { - return _validators.isValidIdentifier; - } -}); -Object.defineProperty(exports, "isLet", { - enumerable: true, - get: function get() { - return _validators.isLet; - } -}); -Object.defineProperty(exports, "isBlockScoped", { - enumerable: true, - get: function get() { - return _validators.isBlockScoped; - } -}); -Object.defineProperty(exports, "isVar", { - enumerable: true, - get: function get() { - return _validators.isVar; - } -}); -Object.defineProperty(exports, "isSpecifierDefault", { - enumerable: true, - get: function get() { - return _validators.isSpecifierDefault; - } -}); -Object.defineProperty(exports, "isScope", { - enumerable: true, - get: function get() { - return _validators.isScope; - } -}); -Object.defineProperty(exports, "isImmutable", { - enumerable: true, - get: function get() { - return _validators.isImmutable; - } -}); -Object.defineProperty(exports, "isNodesEquivalent", { - enumerable: true, - get: function get() { - return _validators.isNodesEquivalent; - } -}); +function NullLiteral() { + return t.nullLiteralTypeAnnotation(); +} -var _converters = require("./converters"); +function RegExpLiteral() { + return t.genericTypeAnnotation(t.identifier("RegExp")); +} -Object.defineProperty(exports, "toComputedKey", { - enumerable: true, - get: function get() { - return _converters.toComputedKey; - } -}); -Object.defineProperty(exports, "toSequenceExpression", { - enumerable: true, - get: function get() { - return _converters.toSequenceExpression; - } -}); -Object.defineProperty(exports, "toKeyAlias", { - enumerable: true, - get: function get() { - return _converters.toKeyAlias; - } -}); -Object.defineProperty(exports, "toIdentifier", { - enumerable: true, - get: function get() { - return _converters.toIdentifier; - } -}); -Object.defineProperty(exports, "toBindingIdentifierName", { - enumerable: true, - get: function get() { - return _converters.toBindingIdentifierName; - } -}); -Object.defineProperty(exports, "toStatement", { - enumerable: true, - get: function get() { - return _converters.toStatement; - } -}); -Object.defineProperty(exports, "toExpression", { - enumerable: true, - get: function get() { - return _converters.toExpression; - } -}); -Object.defineProperty(exports, "toBlock", { - enumerable: true, - get: function get() { - return _converters.toBlock; - } -}); -Object.defineProperty(exports, "valueToNode", { - enumerable: true, - get: function get() { - return _converters.valueToNode; - } -}); +function ObjectExpression() { + return t.genericTypeAnnotation(t.identifier("Object")); +} -var _flow = require("./flow"); +function ArrayExpression() { + return t.genericTypeAnnotation(t.identifier("Array")); +} -Object.defineProperty(exports, "createUnionTypeAnnotation", { - enumerable: true, - get: function get() { - return _flow.createUnionTypeAnnotation; - } -}); -Object.defineProperty(exports, "removeTypeDuplicates", { - enumerable: true, - get: function get() { - return _flow.removeTypeDuplicates; - } -}); -Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { - enumerable: true, - get: function get() { - return _flow.createTypeAnnotationBasedOnTypeof; - } -}); +function RestElement() { + return ArrayExpression(); +} -var _toFastProperties = require("to-fast-properties"); +RestElement.validParent = true; -var _toFastProperties2 = _interopRequireDefault(_toFastProperties); +function Func() { + return t.genericTypeAnnotation(t.identifier("Function")); +} -var _clone = require("lodash/clone"); +exports.FunctionExpression = Func; +exports.ArrowFunctionExpression = Func; +exports.FunctionDeclaration = Func; +exports.ClassExpression = Func; +exports.ClassDeclaration = Func; +function CallExpression() { + return resolveCall(this.get("callee")); +} -var _clone2 = _interopRequireDefault(_clone); +function TaggedTemplateExpression() { + return resolveCall(this.get("tag")); +} -var _uniq = require("lodash/uniq"); +function resolveCall(callee) { + callee = callee.resolve(); -var _uniq2 = _interopRequireDefault(_uniq); + if (callee.isFunction()) { + if (callee.is("async")) { + if (callee.is("generator")) { + return t.genericTypeAnnotation(t.identifier("AsyncIterator")); + } else { + return t.genericTypeAnnotation(t.identifier("Promise")); + } + } else { + if (callee.node.returnType) { + return callee.node.returnType; + } else {} + } + } +} +},{"./inferer-reference":159,"babel-types":183}],161:[function(require,module,exports){ +"use strict"; -require("./definitions/init"); +exports.__esModule = true; +exports.is = undefined; -var _definitions = require("./definitions"); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -var _react2 = require("./react"); +var _getIterator3 = _interopRequireDefault(_getIterator2); -var _react = _interopRequireWildcard(_react2); +exports.matchesPattern = matchesPattern; +exports.has = has; +exports.isStatic = isStatic; +exports.isnt = isnt; +exports.equals = equals; +exports.isNodeType = isNodeType; +exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; +exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; +exports.isCompletionRecord = isCompletionRecord; +exports.isStatementOrBlock = isStatementOrBlock; +exports.referencesImport = referencesImport; +exports.getSource = getSource; +exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; +exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; +exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; +exports.resolve = resolve; +exports._resolve = _resolve; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _includes = require("lodash/includes"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _includes2 = _interopRequireDefault(_includes); -var t = exports; +var _babelTypes = require("babel-types"); -function registerType(type) { - var is = t["is" + type]; - if (!is) { - is = t["is" + type] = function (node, opts) { - return t.is(type, node, opts); - }; - } +var t = _interopRequireWildcard(_babelTypes); - t["assert" + type] = function (node, opts) { - opts = opts || {}; - if (!is(node, opts)) { - throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); - } - }; -} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; -exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; -exports.NODE_FIELDS = _definitions.NODE_FIELDS; -exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; -exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; -exports.react = _react; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function matchesPattern(pattern, allowPartial) { + if (!this.isMemberExpression()) return false; -for (var type in t.VISITOR_KEYS) { - registerType(type); -} + var parts = pattern.split("."); + var search = [this.node]; + var i = 0; -t.FLIPPED_ALIAS_KEYS = {}; + function matches(name) { + var part = parts[i]; + return part === "*" || name === part; + } -(0, _keys2.default)(t.ALIAS_KEYS).forEach(function (type) { - t.ALIAS_KEYS[type].forEach(function (alias) { - var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; - types.push(type); - }); -}); + while (search.length) { + var node = search.shift(); -(0, _keys2.default)(t.FLIPPED_ALIAS_KEYS).forEach(function (type) { - t[type.toUpperCase() + "_TYPES"] = t.FLIPPED_ALIAS_KEYS[type]; - registerType(type); -}); + if (allowPartial && i === parts.length) { + return true; + } -var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); + if (t.isIdentifier(node)) { + if (!matches(node.name)) return false; + } else if (t.isLiteral(node)) { + if (!matches(node.value)) return false; + } else if (t.isMemberExpression(node)) { + if (node.computed && !t.isLiteral(node.property)) { + return false; + } else { + search.unshift(node.property); + search.unshift(node.object); + continue; + } + } else if (t.isThisExpression(node)) { + if (!matches("this")) return false; + } else { + return false; + } -function is(type, node, opts) { - if (!node) return false; + if (++i > parts.length) { + return false; + } + } - var matches = isType(node.type, type); - if (!matches) return false; + return i === parts.length; +} - if (typeof opts === "undefined") { - return true; +function has(key) { + var val = this.node && this.node[key]; + if (val && Array.isArray(val)) { + return !!val.length; } else { - return t.shallowEqual(node, opts); + return !!val; } } -function isType(nodeType, targetType) { - if (nodeType === targetType) return true; +function isStatic() { + return this.scope.isStatic(this.node); +} - if (t.ALIAS_KEYS[targetType]) return false; +var is = exports.is = has; - var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; - if (aliases) { - if (aliases[0] === nodeType) return true; +function isnt(key) { + return !this.has(key); +} - for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; +function equals(key, value) { + return this.node[key] === value; +} - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } +function isNodeType(type) { + return t.isType(this.type, type); +} - var alias = _ref; +function canHaveVariableDeclarationOrExpression() { + return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); +} - if (nodeType === alias) return true; - } +function canSwapBetweenExpressionAndStatement(replacement) { + if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { + return false; + } + + if (this.isExpression()) { + return t.isBlockStatement(replacement); + } else if (this.isBlockStatement()) { + return t.isExpression(replacement); } return false; } -(0, _keys2.default)(t.BUILDER_KEYS).forEach(function (type) { - var keys = t.BUILDER_KEYS[type]; +function isCompletionRecord(allowInsideFunction) { + var path = this; + var first = true; - function builder() { - if (arguments.length > keys.length) { - throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); - } + do { + var container = path.container; - var node = {}; - node.type = type; + if (path.isFunction() && !first) { + return !!allowInsideFunction; + } - var i = 0; + first = false; - for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + if (Array.isArray(container) && path.key !== container.length - 1) { + return false; + } + } while ((path = path.parentPath) && !path.isProgram()); - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } + return true; +} - var _key = _ref2; +function isStatementOrBlock() { + if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { + return false; + } else { + return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); + } +} - var field = t.NODE_FIELDS[type][_key]; +function referencesImport(moduleSource, importName) { + if (!this.isReferencedIdentifier()) return false; - var arg = arguments[i++]; - if (arg === undefined) arg = (0, _clone2.default)(field.default); + var binding = this.scope.getBinding(this.node.name); + if (!binding || binding.kind !== "module") return false; - node[_key] = arg; - } + var path = binding.path; + var parent = path.parentPath; + if (!parent.isImportDeclaration()) return false; - for (var key in node) { - validate(node, key, node[key]); - } - - return node; + if (parent.node.source.value === moduleSource) { + if (!importName) return true; + } else { + return false; } - t[type] = builder; - t[type[0].toLowerCase() + type.slice(1)] = builder; -}); - -var _loop = function _loop(_type) { - var newType = t.DEPRECATED_KEYS[_type]; + if (path.isImportDefaultSpecifier() && importName === "default") { + return true; + } - function proxy(fn) { - return function () { - console.trace("The node type " + _type + " has been renamed to " + newType); - return fn.apply(this, arguments); - }; + if (path.isImportNamespaceSpecifier() && importName === "*") { + return true; } - t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); - t["is" + _type] = proxy(t["is" + newType]); - t["assert" + _type] = proxy(t["assert" + newType]); -}; + if (path.isImportSpecifier() && path.node.imported.name === importName) { + return true; + } -for (var _type in t.DEPRECATED_KEYS) { - _loop(_type); + return false; } -function validate(node, key, val) { - if (!node) return; - - var fields = t.NODE_FIELDS[node.type]; - if (!fields) return; - - var field = fields[key]; - if (!field || !field.validate) return; - if (field.optional && val == null) return; - - field.validate(node, key, val); +function getSource() { + var node = this.node; + if (node.end) { + return this.hub.file.code.slice(node.start, node.end); + } else { + return ""; + } } -function shallowEqual(actual, expected) { - var keys = (0, _keys2.default)(expected); +function willIMaybeExecuteBefore(target) { + return this._guessExecutionStatusRelativeTo(target) !== "after"; +} - for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; +function _guessExecutionStatusRelativeTo(target) { + var targetFuncParent = target.scope.getFunctionParent(); + var selfFuncParent = this.scope.getFunctionParent(); - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; + if (targetFuncParent.node !== selfFuncParent.node) { + var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); + if (status) { + return status; } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; + target = targetFuncParent.path; } + } - var key = _ref3; + var targetPaths = target.getAncestry(); + if (targetPaths.indexOf(this) >= 0) return "after"; - if (actual[key] !== expected[key]) { - return false; + var selfPaths = this.getAncestry(); + + var commonPath = void 0; + var targetIndex = void 0; + var selfIndex = void 0; + for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { + var selfPath = selfPaths[selfIndex]; + targetIndex = targetPaths.indexOf(selfPath); + if (targetIndex >= 0) { + commonPath = selfPath; + break; } } + if (!commonPath) { + return "before"; + } - return true; -} + var targetRelationship = targetPaths[targetIndex - 1]; + var selfRelationship = selfPaths[selfIndex - 1]; + if (!targetRelationship || !selfRelationship) { + return "before"; + } -function appendToMemberExpression(member, append, computed) { - member.object = t.memberExpression(member.object, member.property, member.computed); - member.property = append; - member.computed = !!computed; - return member; -} + if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { + return targetRelationship.key > selfRelationship.key ? "before" : "after"; + } -function prependToMemberExpression(member, prepend) { - member.object = t.memberExpression(prepend, member.object); - return member; + var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); + var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); + return targetKeyPosition > selfKeyPosition ? "before" : "after"; } -function ensureBlock(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "body"; +function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { + var targetFuncPath = targetFuncParent.path; + if (!targetFuncPath.isFunctionDeclaration()) return; - return node[key] = t.toBlock(node[key], node); -} + var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); -function clone(node) { - if (!node) return node; - var newNode = {}; - for (var key in node) { - if (key[0] === "_") continue; - newNode[key] = node[key]; - } - return newNode; -} + if (!binding.references) return "before"; -function cloneWithoutLoc(node) { - var newNode = clone(node); - delete newNode.loc; - return newNode; -} + var referencePaths = binding.referencePaths; -function cloneDeep(node) { - if (!node) return node; - var newNode = {}; + for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - for (var key in node) { - if (key[0] === "_") continue; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - var val = node[key]; + var path = _ref; - if (val) { - if (val.type) { - val = t.cloneDeep(val); - } else if (Array.isArray(val)) { - val = val.map(t.cloneDeep); - } + if (path.key !== "callee" || !path.parentPath.isCallExpression()) { + return; } - - newNode[key] = val; } - return newNode; -} - -function buildMatchMemberExpression(match, allowPartial) { - var parts = match.split("."); - - return function (member) { - if (!t.isMemberExpression(member)) return false; - - var search = [member]; - var i = 0; - - while (search.length) { - var node = search.shift(); - - if (allowPartial && i === parts.length) { - return true; - } + var allStatus = void 0; - if (t.isIdentifier(node)) { - if (parts[i] !== node.name) return false; - } else if (t.isStringLiteral(node)) { - if (parts[i] !== node.value) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isStringLiteral(node.property)) { - return false; - } else { - search.push(node.object); - search.push(node.property); - continue; - } - } else { - return false; - } + for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; - if (++i > parts.length) { - return false; - } + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } - return true; - }; -} + var _path = _ref2; -function removeComments(node) { - for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; + var childOfFunction = !!_path.find(function (path) { + return path.node === targetFuncPath.node; + }); + if (childOfFunction) continue; - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; + var status = this._guessExecutionStatusRelativeTo(_path); + + if (allStatus) { + if (allStatus !== status) return; } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; + allStatus = status; } - - var key = _ref4; - - delete node[key]; } - return node; -} -function inheritsComments(child, parent) { - inheritTrailingComments(child, parent); - inheritLeadingComments(child, parent); - inheritInnerComments(child, parent); - return child; + return allStatus; } -function inheritTrailingComments(child, parent) { - _inheritComments("trailingComments", child, parent); +function resolve(dangerous, resolved) { + return this._resolve(dangerous, resolved) || this; } -function inheritLeadingComments(child, parent) { - _inheritComments("leadingComments", child, parent); -} +function _resolve(dangerous, resolved) { + if (resolved && resolved.indexOf(this) >= 0) return; -function inheritInnerComments(child, parent) { - _inheritComments("innerComments", child, parent); -} + resolved = resolved || []; + resolved.push(this); -function _inheritComments(key, child, parent) { - if (child && parent) { - child[key] = (0, _uniq2.default)([].concat(child[key], parent[key]).filter(Boolean)); - } -} + if (this.isVariableDeclarator()) { + if (this.get("id").isIdentifier()) { + return this.get("init").resolve(dangerous, resolved); + } else {} + } else if (this.isReferencedIdentifier()) { + var binding = this.scope.getBinding(this.node.name); + if (!binding) return; -function inherits(child, parent) { - if (!child || !parent) return child; + if (!binding.constant) return; - for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; + if (binding.kind === "module") return; - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; + if (binding.path !== this) { + var ret = binding.path.resolve(dangerous, resolved); + + if (this.find(function (parent) { + return parent.node === ret.node; + })) return; + return ret; } + } else if (this.isTypeCastExpression()) { + return this.get("expression").resolve(dangerous, resolved); + } else if (dangerous && this.isMemberExpression()) { - var _key2 = _ref5; + var targetKey = this.toComputedKey(); + if (!t.isLiteral(targetKey)) return; - if (child[_key2] == null) { - child[_key2] = parent[_key2]; - } - } + var targetName = targetKey.value; - for (var key in parent) { - if (key[0] === "_") child[key] = parent[key]; - } + var target = this.get("object").resolve(dangerous, resolved); - for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; + if (target.isObjectExpression()) { + var props = target.get("properties"); + for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } - var _key3 = _ref6; + var prop = _ref3; - child[_key3] = parent[_key3]; - } + if (!prop.isProperty()) continue; - t.inheritsComments(child, parent); + var key = prop.get("key"); - return child; -} + var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); -function assertNode(node) { - if (!isNode(node)) { - throw new TypeError("Not a valid node " + (node && node.type)); + match = match || key.isLiteral({ value: targetName }); + + if (match) return prop.get("value").resolve(dangerous, resolved); + } + } else if (target.isArrayExpression() && !isNaN(+targetName)) { + var elems = target.get("elements"); + var elem = elems[targetName]; + if (elem) return elem.resolve(dangerous, resolved); + } } } +},{"babel-runtime/core-js/get-iterator":127,"babel-types":183,"lodash/includes":509}],162:[function(require,module,exports){ +"use strict"; -function isNode(node) { - return !!(node && _definitions.VISITOR_KEYS[node.type]); -} +exports.__esModule = true; -(0, _toFastProperties2.default)(t); -(0, _toFastProperties2.default)(t.VISITOR_KEYS); +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -function traverseFast(node, enter, opts) { - if (!node) return; +var _getIterator3 = _interopRequireDefault(_getIterator2); - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - opts = opts || {}; - enter(node, opts); +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; +var _babelTypes = require("babel-types"); - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } +var t = _interopRequireWildcard(_babelTypes); - var key = _ref7; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var subNode = node[key]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (Array.isArray(subNode)) { - for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; +var referenceVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { + return; + } - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } + if (path.node.name === "this") { + var scope = path.scope; + do { + if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break; + } while (scope = scope.parent); + if (scope) state.breakOnScopePaths.push(scope.path); + } - var _node = _ref8; + var binding = path.scope.getBinding(path.node.name); + if (!binding) return; - traverseFast(_node, enter, opts); - } - } else { - traverseFast(subNode, enter, opts); - } - } -} + if (binding !== state.scope.getBinding(path.node.name)) return; -var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + state.bindings[path.node.name] = binding; + } +}; -var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); +var PathHoister = function () { + function PathHoister(path, scope) { + (0, _classCallCheck3.default)(this, PathHoister); -function removeProperties(node, opts) { - opts = opts || {}; - var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; + this.breakOnScopePaths = []; - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } + this.bindings = {}; - var _key4 = _ref9; + this.scopes = []; - if (node[_key4] != null) node[_key4] = undefined; - } + this.scope = scope; + this.path = path; - for (var key in node) { - if (key[0] === "_" && node[key] != null) node[key] = undefined; + this.attachAfter = false; } - var syms = (0, _getOwnPropertySymbols2.default)(node); - for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; + PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { + for (var key in this.bindings) { + var binding = this.bindings[key]; + if (!scope.bindingIdentifierEquals(key, binding.identifier)) { + return false; + } } - var sym = _ref10; + return true; + }; - node[sym] = null; - } -} + PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { + var scope = this.path.scope; + do { + if (this.isCompatibleScope(scope)) { + this.scopes.push(scope); + } else { + break; + } -function removePropertiesDeep(tree, opts) { - traverseFast(tree, removeProperties, opts); - return tree; -} -},{"./constants":134,"./converters":135,"./definitions":140,"./definitions/init":141,"./flow":144,"./react":146,"./retrievers":147,"./validators":148,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/json/stringify":90,"babel-runtime/core-js/object/get-own-property-symbols":95,"babel-runtime/core-js/object/keys":96,"lodash/clone":455,"lodash/uniq":504,"to-fast-properties":538}],146:[function(require,module,exports){ -"use strict"; + if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { + break; + } + } while (scope = scope.parent); + }; -exports.__esModule = true; -exports.isReactComponent = undefined; -exports.isCompatTag = isCompatTag; -exports.buildChildren = buildChildren; + PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { + var path = this._getAttachmentPath(); + if (!path) return; -var _index = require("./index"); + var targetScope = path.scope; -var t = _interopRequireWildcard(_index); + if (targetScope.path === path) { + targetScope = path.scope.parent; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (targetScope.path.isProgram() || targetScope.path.isFunction()) { + for (var name in this.bindings) { + if (!targetScope.hasOwnBinding(name)) continue; -var isReactComponent = exports.isReactComponent = t.buildMatchMemberExpression("React.Component"); + var binding = this.bindings[name]; -function isCompatTag(tagName) { - return !!tagName && /^[a-z]|\-/.test(tagName); -} + if (binding.kind === "param") continue; -function cleanJSXElementLiteralChild(child, args) { - var lines = child.value.split(/\r\n|\n|\r/); + if (this.getAttachmentParentForPath(binding.path).key > path.key) { + this.attachAfter = true; + path = binding.path; - var lastNonEmptyLine = 0; + for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - for (var i = 0; i < lines.length; i++) { - if (lines[i].match(/[^ \t]/)) { - lastNonEmptyLine = i; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var violationPath = _ref; + + if (this.getAttachmentParentForPath(violationPath).key > path.key) { + path = violationPath; + } + } + } + } } - } - var str = ""; + if (path.parentPath.isExportDeclaration()) { + path = path.parentPath; + } - for (var _i = 0; _i < lines.length; _i++) { - var line = lines[_i]; + return path; + }; - var isFirstLine = _i === 0; - var isLastLine = _i === lines.length - 1; - var isLastNonEmptyLine = _i === lastNonEmptyLine; + PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { + var scopes = this.scopes; - var trimmedLine = line.replace(/\t/g, " "); + var scope = scopes.pop(); - if (!isFirstLine) { - trimmedLine = trimmedLine.replace(/^[ ]+/, ""); - } + if (!scope) return; - if (!isLastLine) { - trimmedLine = trimmedLine.replace(/[ ]+$/, ""); - } + if (scope.path.isFunction()) { + if (this.hasOwnParamBindings(scope)) { + if (this.scope === scope) return; - if (trimmedLine) { - if (!isLastNonEmptyLine) { - trimmedLine += " "; + return scope.path.get("body").get("body")[0]; + } else { + return this.getNextScopeAttachmentParent(); } - - str += trimmedLine; + } else if (scope.path.isProgram()) { + return this.getNextScopeAttachmentParent(); } - } + }; - if (str) args.push(t.stringLiteral(str)); -} + PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() { + var scope = this.scopes.pop(); + if (scope) return this.getAttachmentParentForPath(scope.path); + }; -function buildChildren(node) { - var elems = []; + PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) { + do { + if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path; + } while (path = path.parentPath); + }; - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i]; + PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { + for (var name in this.bindings) { + if (!scope.hasOwnBinding(name)) continue; - if (t.isJSXText(child)) { - cleanJSXElementLiteralChild(child, elems); - continue; + var binding = this.bindings[name]; + + if (binding.kind === "param" && binding.constant) return true; } + return false; + }; - if (t.isJSXExpressionContainer(child)) child = child.expression; - if (t.isJSXEmptyExpression(child)) continue; + PathHoister.prototype.run = function run() { + var node = this.path.node; + if (node._hoisted) return; + node._hoisted = true; - elems.push(child); - } + this.path.traverse(referenceVisitor, this); - return elems; -} -},{"./index":145}],147:[function(require,module,exports){ -"use strict"; + this.getCompatibleScopes(); -exports.__esModule = true; + var attachTo = this.getAttachmentPath(); + if (!attachTo) return; -var _create = require("babel-runtime/core-js/object/create"); + if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; -var _create2 = _interopRequireDefault(_create); + var uid = attachTo.scope.generateUidIdentifier("ref"); + var declarator = t.variableDeclarator(uid, this.path.node); -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; + var insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; + attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]); -var _index = require("./index"); + var parent = this.path.parentPath; + if (parent.isJSXElement() && this.path.container === parent.node.children) { + uid = t.JSXExpressionContainer(uid); + } -var t = _interopRequireWildcard(_index); + this.path.replaceWith(uid); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return PathHoister; +}(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.default = PathHoister; +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/classCallCheck":141,"babel-types":183}],163:[function(require,module,exports){ +"use strict"; -function getBindingIdentifiers(node, duplicates, outerOnly) { - var search = [].concat(node); - var ids = (0, _create2.default)(null); +exports.__esModule = true; +var hooks = exports.hooks = [function (self, parent) { + var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); - while (search.length) { - var id = search.shift(); - if (!id) continue; + if (removeParent) { + parent.remove(); + return true; + } +}, function (self, parent) { + if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { + parent.replaceWith(parent.node.expressions[0]); + return true; + } +}, function (self, parent) { + if (parent.isBinary()) { + if (self.key === "left") { + parent.replaceWith(parent.node.right); + } else { + parent.replaceWith(parent.node.left); + } + return true; + } +}, function (self, parent) { + if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { + self.replaceWith({ + type: "BlockStatement", + body: [] + }); + return true; + } +}]; +},{}],164:[function(require,module,exports){ +"use strict"; - var keys = t.getBindingIdentifiers.keys[id.type]; +exports.__esModule = true; +exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; - if (t.isIdentifier(id)) { - if (duplicates) { - var _ids = ids[id.name] = ids[id.name] || []; - _ids.push(id); +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var ReferencedIdentifier = exports.ReferencedIdentifier = { + types: ["Identifier", "JSXIdentifier"], + checkPath: function checkPath(_ref, opts) { + var node = _ref.node, + parent = _ref.parent; + + if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { + if (t.isJSXIdentifier(node, opts)) { + if (_babelTypes.react.isCompatTag(node.name)) return false; } else { - ids[id.name] = id; + return false; } - continue; } - if (t.isExportDeclaration(id)) { - if (t.isDeclaration(id.declaration)) { - search.push(id.declaration); - } - continue; - } + return t.isReferenced(node, parent); + } +}; - if (outerOnly) { - if (t.isFunctionDeclaration(id)) { - search.push(id.id); - continue; - } +var ReferencedMemberExpression = exports.ReferencedMemberExpression = { + types: ["MemberExpression"], + checkPath: function checkPath(_ref2) { + var node = _ref2.node, + parent = _ref2.parent; - if (t.isFunctionExpression(id)) { - continue; - } - } + return t.isMemberExpression(node) && t.isReferenced(node, parent); + } +}; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (id[key]) { - search = search.concat(id[key]); - } - } - } +var BindingIdentifier = exports.BindingIdentifier = { + types: ["Identifier"], + checkPath: function checkPath(_ref3) { + var node = _ref3.node, + parent = _ref3.parent; + + return t.isIdentifier(node) && t.isBinding(node, parent); } +}; - return ids; -} +var Statement = exports.Statement = { + types: ["Statement"], + checkPath: function checkPath(_ref4) { + var node = _ref4.node, + parent = _ref4.parent; -getBindingIdentifiers.keys = { - DeclareClass: ["id"], - DeclareFunction: ["id"], - DeclareModule: ["id"], - DeclareVariable: ["id"], - InterfaceDeclaration: ["id"], - TypeAlias: ["id"], + if (t.isStatement(node)) { + if (t.isVariableDeclaration(node)) { + if (t.isForXStatement(parent, { left: node })) return false; + if (t.isForStatement(parent, { init: node })) return false; + } - CatchClause: ["param"], - LabeledStatement: ["label"], - UnaryExpression: ["argument"], - AssignmentExpression: ["left"], + return true; + } else { + return false; + } + } +}; - ImportSpecifier: ["local"], - ImportNamespaceSpecifier: ["local"], - ImportDefaultSpecifier: ["local"], - ImportDeclaration: ["specifiers"], +var Expression = exports.Expression = { + types: ["Expression"], + checkPath: function checkPath(path) { + if (path.isIdentifier()) { + return path.isReferencedIdentifier(); + } else { + return t.isExpression(path.node); + } + } +}; - ExportSpecifier: ["exported"], - ExportNamespaceSpecifier: ["exported"], - ExportDefaultSpecifier: ["exported"], +var Scope = exports.Scope = { + types: ["Scopable"], + checkPath: function checkPath(path) { + return t.isScope(path.node, path.parent); + } +}; - FunctionDeclaration: ["id", "params"], - FunctionExpression: ["id", "params"], +var Referenced = exports.Referenced = { + checkPath: function checkPath(path) { + return t.isReferenced(path.node, path.parent); + } +}; - ClassDeclaration: ["id"], - ClassExpression: ["id"], +var BlockScoped = exports.BlockScoped = { + checkPath: function checkPath(path) { + return t.isBlockScoped(path.node); + } +}; - RestElement: ["argument"], - UpdateExpression: ["argument"], +var Var = exports.Var = { + types: ["VariableDeclaration"], + checkPath: function checkPath(path) { + return t.isVar(path.node); + } +}; - RestProperty: ["argument"], - ObjectProperty: ["value"], +var User = exports.User = { + checkPath: function checkPath(path) { + return path.node && !!path.node.loc; + } +}; - AssignmentPattern: ["left"], - ArrayPattern: ["elements"], - ObjectPattern: ["properties"], +var Generated = exports.Generated = { + checkPath: function checkPath(path) { + return !path.isUser(); + } +}; - VariableDeclaration: ["declarations"], - VariableDeclarator: ["id"] +var Pure = exports.Pure = { + checkPath: function checkPath(path, opts) { + return path.scope.isPure(path.node, opts); + } }; -function getOuterBindingIdentifiers(node, duplicates) { - return getBindingIdentifiers(node, duplicates, true); -} -},{"./index":145,"babel-runtime/core-js/object/create":94}],148:[function(require,module,exports){ +var Flow = exports.Flow = { + types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], + checkPath: function checkPath(_ref5) { + var node = _ref5.node; + + if (t.isFlow(node)) { + return true; + } else if (t.isImportDeclaration(node)) { + return node.importKind === "type" || node.importKind === "typeof"; + } else if (t.isExportDeclaration(node)) { + return node.exportKind === "type"; + } else if (t.isImportSpecifier(node)) { + return node.importKind === "type" || node.importKind === "typeof"; + } else { + return false; + } + } +}; +},{"babel-types":183}],165:[function(require,module,exports){ "use strict"; exports.__esModule = true; -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - var _typeof2 = require("babel-runtime/helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); @@ -23049,47043 +24768,44811 @@ var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); -exports.isBinding = isBinding; -exports.isReferenced = isReferenced; -exports.isValidIdentifier = isValidIdentifier; -exports.isLet = isLet; -exports.isBlockScoped = isBlockScoped; -exports.isVar = isVar; -exports.isSpecifierDefault = isSpecifierDefault; -exports.isScope = isScope; -exports.isImmutable = isImmutable; -exports.isNodesEquivalent = isNodesEquivalent; +exports.insertBefore = insertBefore; +exports._containerInsert = _containerInsert; +exports._containerInsertBefore = _containerInsertBefore; +exports._containerInsertAfter = _containerInsertAfter; +exports._maybePopFromStatements = _maybePopFromStatements; +exports.insertAfter = insertAfter; +exports.updateSiblingKeys = updateSiblingKeys; +exports._verifyNodeList = _verifyNodeList; +exports.unshiftContainer = unshiftContainer; +exports.pushContainer = pushContainer; +exports.hoist = hoist; -var _retrievers = require("./retrievers"); +var _cache = require("../cache"); -var _esutils = require("esutils"); +var _hoister = require("./lib/hoister"); -var _esutils2 = _interopRequireDefault(_esutils); +var _hoister2 = _interopRequireDefault(_hoister); var _index = require("./index"); -var t = _interopRequireWildcard(_index); +var _index2 = _interopRequireDefault(_index); -var _constants = require("./constants"); +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function isBinding(node, parent) { - var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = parent[key]; - if (Array.isArray(val)) { - if (val.indexOf(node) >= 0) return true; - } else { - if (val === node) return true; - } +function insertBefore(nodes) { + this._assertUnremoved(); + + nodes = this._verifyNodeList(nodes); + + if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { + return this.parentPath.insertBefore(nodes); + } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { + if (this.node) nodes.push(this.node); + this.replaceExpressionWithStatements(nodes); + } else { + this._maybePopFromStatements(nodes); + if (Array.isArray(this.container)) { + return this._containerInsertBefore(nodes); + } else if (this.isStatementOrBlock()) { + if (this.node) nodes.push(this.node); + this._replaceWith(t.blockStatement(nodes)); + } else { + throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); } } - return false; + return [this]; } -function isReferenced(node, parent) { - switch (parent.type) { - case "BindExpression": - return parent.object === node || parent.callee === node; +function _containerInsert(from, nodes) { + this.updateSiblingKeys(from, nodes.length); - case "MemberExpression": - case "JSXMemberExpression": - if (parent.property === node && parent.computed) { - return true; - } else if (parent.object === node) { - return true; - } else { - return false; - } + var paths = []; - case "MetaProperty": - return false; + for (var i = 0; i < nodes.length; i++) { + var to = from + i; + var node = nodes[i]; + this.container.splice(to, 0, node); - case "ObjectProperty": - if (parent.key === node) { - return parent.computed; - } + if (this.context) { + var path = this.context.create(this.parent, this.container, to, this.listKey); - case "VariableDeclarator": - return parent.id !== node; + if (this.context.queue) path.pushContext(this.context); + paths.push(path); + } else { + paths.push(_index2.default.get({ + parentPath: this.parentPath, + parent: this.parent, + container: this.container, + listKey: this.listKey, + key: to + })); + } + } - case "ArrowFunctionExpression": - case "FunctionDeclaration": - case "FunctionExpression": - for (var _iterator = parent.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; + var contexts = this._getQueueContexts(); - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } + for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; - var param = _ref; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - if (param === node) return false; - } + var _path = _ref; - return parent.id !== node; + _path.setScope(); + _path.debug(function () { + return "Inserted."; + }); - case "ExportSpecifier": - if (parent.source) { - return false; + for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; } else { - return parent.local === node; + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; } - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; - - case "JSXAttribute": - return parent.name !== node; - - case "ClassProperty": - if (parent.key === node) { - return parent.computed; - } else { - return parent.value === node; - } - - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; - - case "ClassDeclaration": - case "ClassExpression": - return parent.id !== node; - - case "ClassMethod": - case "ObjectMethod": - return parent.key === node && parent.computed; - - case "LabeledStatement": - return false; - - case "CatchClause": - return parent.param !== node; - - case "RestElement": - return false; - - case "AssignmentExpression": - return parent.right === node; - - case "AssignmentPattern": - return parent.right === node; + var context = _ref2; - case "ObjectPattern": - case "ArrayPattern": - return false; + context.maybeQueue(_path, true); + } } - return true; + return paths; } -function isValidIdentifier(name) { - if (typeof name !== "string" || _esutils2.default.keyword.isReservedWordES6(name, true)) { - return false; - } else if (name === "await") { - return false; - } else { - return _esutils2.default.keyword.isIdentifierNameES6(name); - } +function _containerInsertBefore(nodes) { + return this._containerInsert(this.key, nodes); } -function isLet(node) { - return t.isVariableDeclaration(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); +function _containerInsertAfter(nodes) { + return this._containerInsert(this.key + 1, nodes); } -function isBlockScoped(node) { - return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); -} +function _maybePopFromStatements(nodes) { + var last = nodes[nodes.length - 1]; + var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; + if (isIdentifier && !this.isCompletionRecord()) { + nodes.pop(); + } } -function isSpecifierDefault(specifier) { - return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); -} +function insertAfter(nodes) { + this._assertUnremoved(); -function isScope(node, parent) { - if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { - return false; + nodes = this._verifyNodeList(nodes); + + if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { + return this.parentPath.insertAfter(nodes); + } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { + if (this.node) { + var temp = this.scope.generateDeclaredUidIdentifier(); + nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); + nodes.push(t.expressionStatement(temp)); + } + this.replaceExpressionWithStatements(nodes); + } else { + this._maybePopFromStatements(nodes); + if (Array.isArray(this.container)) { + return this._containerInsertAfter(nodes); + } else if (this.isStatementOrBlock()) { + if (this.node) nodes.unshift(this.node); + this._replaceWith(t.blockStatement(nodes)); + } else { + throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); + } } - return t.isScopable(node); + return [this]; } -function isImmutable(node) { - if (t.isType(node.type, "Immutable")) return true; +function updateSiblingKeys(fromIndex, incrementBy) { + if (!this.parent) return; - if (t.isIdentifier(node)) { - if (node.name === "undefined") { - return true; - } else { - return false; + var paths = _cache.path.get(this.parent); + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (path.key >= fromIndex) { + path.key += incrementBy; } } - - return false; } -function isNodesEquivalent(a, b) { - if ((typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || (typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || a == null || b == null) { - return a === b; +function _verifyNodeList(nodes) { + if (!nodes) { + return []; } - if (a.type !== b.type) { - return false; + if (nodes.constructor !== Array) { + nodes = [nodes]; } - var fields = (0, _keys2.default)(t.NODE_FIELDS[a.type] || a.type); - - for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + var msg = void 0; - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; + if (!node) { + msg = "has falsy node"; + } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { + msg = "contains a non-object node"; + } else if (!node.type) { + msg = "without a type"; + } else if (node instanceof _index2.default) { + msg = "has a NodePath when it expected a raw object"; } - var field = _ref2; - - if ((0, _typeof3.default)(a[field]) !== (0, _typeof3.default)(b[field])) { - return false; + if (msg) { + var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); + throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); } + } - if (Array.isArray(a[field])) { - if (!Array.isArray(b[field])) { - return false; - } - if (a[field].length !== b[field].length) { - return false; - } + return nodes; +} - for (var i = 0; i < a[field].length; i++) { - if (!isNodesEquivalent(a[field][i], b[field][i])) { - return false; - } - } - continue; - } +function unshiftContainer(listKey, nodes) { + this._assertUnremoved(); - if (!isNodesEquivalent(a[field], b[field])) { - return false; - } - } + nodes = this._verifyNodeList(nodes); - return true; + var path = _index2.default.get({ + parentPath: this, + parent: this.node, + container: this.node[listKey], + listKey: listKey, + key: 0 + }); + + return path.insertBefore(nodes); } -},{"./constants":134,"./index":145,"./retrievers":147,"babel-runtime/core-js/get-iterator":89,"babel-runtime/core-js/object/keys":96,"babel-runtime/helpers/typeof":107,"esutils":280}],149:[function(require,module,exports){ -'use strict'; -Object.defineProperty(exports, '__esModule', { value: true }); +function pushContainer(listKey, nodes) { + this._assertUnremoved(); -/* eslint max-len: 0 */ + nodes = this._verifyNodeList(nodes); -// This is a trick taken from Esprima. It turns out that, on -// non-Chrome browsers, to check whether a string is in a set, a -// predicate containing a big ugly `switch` statement is faster than -// a regular expression, and on Chrome the two are about on par. -// This function uses `eval` (non-lexical) to produce such a -// predicate from a space-separated string of words. -// -// It starts by sorting the words by length. + var container = this.node[listKey]; + var path = _index2.default.get({ + parentPath: this, + parent: this.node, + container: container, + listKey: listKey, + key: container.length + }); -function makePredicate(words) { - words = words.split(" "); - return function (str) { - return words.indexOf(str) >= 0; - }; + return path.replaceWithMultiple(nodes); } -// Reserved word lists for various dialects of the language - -var reservedWords = { - 6: makePredicate("enum await"), - strict: makePredicate("implements interface let package private protected public static yield"), - strictBind: makePredicate("eval arguments") -}; +function hoist() { + var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope; -// And the keywords + var hoister = new _hoister2.default(this, scope); + return hoister.run(); +} +},{"../cache":147,"./index":157,"./lib/hoister":162,"babel-runtime/core-js/get-iterator":127,"babel-runtime/helpers/typeof":145,"babel-types":183}],166:[function(require,module,exports){ +"use strict"; -var isKeyword = makePredicate("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 let const class extends export import yield super"); +exports.__esModule = true; -// ## Character categories +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -// Generated by `bin/generate-identifier-regex.js`. +var _getIterator3 = _interopRequireDefault(_getIterator2); -var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; -var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; +exports.remove = remove; +exports._callRemovalHooks = _callRemovalHooks; +exports._remove = _remove; +exports._markRemoved = _markRemoved; +exports._assertUnremoved = _assertUnremoved; -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +var _removalHooks = require("./lib/removal-hooks"); -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// These are a run-length and offset encoded representation of the -// >0xffff code points that are a valid part of identifiers. The -// offset starts at 0x10000, and each pair of numbers represents an -// offset to the next range, and then a size of the range. They were -// generated by `bin/generate-identifier-regex.js`. -// eslint-disable-next-line comma-spacing -var 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, 19, 35, 5, 35, 5, 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, 66, 18, 2, 1, 11, 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, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 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, 60, 67, 1213, 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, 3, 5761, 10591, 541]; -// eslint-disable-next-line comma-spacing -var 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, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 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, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239]; +function remove() { + this._assertUnremoved(); -// This has a complexity linear to the value of the code. The -// assumption is that looking up astral identifier characters is -// rare. -function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) return false; + this.resync(); - pos += set[i + 1]; - if (pos >= code) return true; + if (this._callRemovalHooks()) { + this._markRemoved(); + return; } + + this.shareCommentsWithSiblings(); + this._remove(); + this._markRemoved(); } -// Test whether a given character code starts an identifier. +function _callRemovalHooks() { + for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes); -} + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } -// Test whether a given character is part of an identifier. + var fn = _ref; -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + if (fn(this, this.parentPath)) return true; + } } -// A second optional argument can be given to further configure -var defaultOptions = { - // Source type ("script" or "module") for different semantics - sourceType: "script", - // Source filename. - sourceFilename: undefined, - // Line from which to start counting source. Useful for - // integration with other tools. - startLine: 1, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // TODO - allowSuperOutsideMethod: false, - // An array of plugins to enable - plugins: [], - // TODO - strictMode: null -}; +function _remove() { + if (Array.isArray(this.container)) { + this.container.splice(this.key, 1); + this.updateSiblingKeys(this.key, -1); + } else { + this._replaceWith(null); + } +} -// Interpret and default an options object +function _markRemoved() { + this.shouldSkip = true; + this.removed = true; + this.node = null; +} -function getOptions(opts) { - var options = {}; - for (var key in defaultOptions) { - options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; +function _assertUnremoved() { + if (this.removed) { + throw this.buildCodeFrameError("NodePath has been removed so is read-only."); } - return options; } +},{"./lib/removal-hooks":163,"babel-runtime/core-js/get-iterator":127}],167:[function(require,module,exports){ +"use strict"; -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; +exports.__esModule = true; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); +var _getIterator3 = _interopRequireDefault(_getIterator2); +exports.replaceWithMultiple = replaceWithMultiple; +exports.replaceWithSourceString = replaceWithSourceString; +exports.replaceWith = replaceWith; +exports._replaceWith = _replaceWith; +exports.replaceExpressionWithStatements = replaceExpressionWithStatements; +exports.replaceInline = replaceInline; +var _babelCodeFrame = require("babel-code-frame"); +var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); +var _index = require("../index"); +var _index2 = _interopRequireDefault(_index); +var _index3 = require("./index"); +var _index4 = _interopRequireDefault(_index3); +var _babylon = require("babylon"); -var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; +var _babelTypes = require("babel-types"); +var t = _interopRequireWildcard(_babelTypes); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var hoistVariablesVisitor = { + Function: function Function(path) { + path.skip(); + }, + VariableDeclaration: function VariableDeclaration(path) { + if (path.node.kind !== "var") return; + var bindings = path.getBindingIdentifiers(); + for (var key in bindings) { + path.scope.push({ id: bindings[key] }); + } + var exprs = []; + for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + var declar = _ref; + if (declar.init) { + exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); + } + } -var inherits = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); + path.replaceWithMultiple(exprs); } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; +function replaceWithMultiple(nodes) { + this.resync(); + nodes = this._verifyNodeList(nodes); + t.inheritLeadingComments(nodes[0], this.node); + t.inheritTrailingComments(nodes[nodes.length - 1], this.node); + this.node = this.container[this.key] = null; + this.insertAfter(nodes); + if (this.node) { + this.requeue(); + } else { + this.remove(); + } +} +function replaceWithSourceString(replacement) { + this.resync(); + try { + replacement = "(" + replacement + ")"; + replacement = (0, _babylon.parse)(replacement); + } catch (err) { + var loc = err.loc; + if (loc) { + err.message += " - make sure this is an expression."; + err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); + } + throw err; + } + replacement = replacement.program.body[0].expression; + _index2.default.removeProperties(replacement); + return this.replaceWith(replacement); +} +function replaceWith(replacement) { + this.resync(); + if (this.removed) { + throw new Error("You can't replace this node, we've already removed it"); + } + if (replacement instanceof _index4.default) { + replacement = replacement.node; + } - -var possibleConstructorReturn = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + if (!replacement) { + throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); } - return call && (typeof call === "object" || typeof call === "function") ? call : self; -}; + if (this.node === replacement) { + return; + } -// ## Token types + if (this.isProgram() && !t.isProgram(replacement)) { + throw new Error("You can only replace a Program root node with another Program node"); + } -// The assignment of fine-grained, information-carrying type objects -// allows the tokenizer to store the information it has about a -// token in a way that is very cheap for the parser to look up. + if (Array.isArray(replacement)) { + throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); + } -// All token type variables start with an underscore, to make them -// easy to recognize. + if (typeof replacement === "string") { + throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); + } -// The `beforeExpr` property is used to disambiguate between regular -// expressions and divisions. It is set on all token types that can -// be followed by an expression (thus, a slash after them would be a -// regular expression). -// -// `isLoop` marks a keyword as starting a loop, which is important -// to know when parsing a label, in order to allow or disallow -// continue jumps to that label. + if (this.isNodeType("Statement") && t.isExpression(replacement)) { + if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { + replacement = t.expressionStatement(replacement); + } + } -var beforeExpr = true; -var startsExpr = true; -var isLoop = true; -var isAssign = true; -var prefix = true; -var postfix = true; - -var TokenType = function TokenType(label) { - var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, TokenType); + if (this.isNodeType("Expression") && t.isStatement(replacement)) { + if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { + return this.replaceExpressionWithStatements([replacement]); + } + } - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; -}; + var oldNode = this.node; + if (oldNode) { + t.inheritsComments(replacement, oldNode); + t.removeComments(oldNode); + } -var KeywordTokenType = function (_TokenType) { - inherits(KeywordTokenType, _TokenType); + this._replaceWith(replacement); + this.type = replacement.type; - function KeywordTokenType(name) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, KeywordTokenType); + this.setScope(); - options.keyword = name; + this.requeue(); +} - return possibleConstructorReturn(this, _TokenType.call(this, name, options)); +function _replaceWith(node) { + if (!this.container) { + throw new ReferenceError("Container is falsy"); } - return KeywordTokenType; -}(TokenType); - -var BinopTokenType = function (_TokenType2) { - inherits(BinopTokenType, _TokenType2); - - function BinopTokenType(name, prec) { - classCallCheck(this, BinopTokenType); - return possibleConstructorReturn(this, _TokenType2.call(this, name, { beforeExpr: beforeExpr, binop: prec })); + if (this.inList) { + t.validate(this.parent, this.key, [node]); + } else { + t.validate(this.parent, this.key, node); } - return BinopTokenType; -}(TokenType); - -var types = { - num: new TokenType("num", { startsExpr: startsExpr }), - regexp: new TokenType("regexp", { startsExpr: startsExpr }), - string: new TokenType("string", { startsExpr: startsExpr }), - name: new TokenType("name", { startsExpr: startsExpr }), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - bracketR: new TokenType("]"), - braceL: new TokenType("{", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceBarL: new TokenType("{|", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceR: new TokenType("}"), - braceBarR: new TokenType("|}"), - parenL: new TokenType("(", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - parenR: new TokenType(")"), - comma: new TokenType(",", { beforeExpr: beforeExpr }), - semi: new TokenType(";", { beforeExpr: beforeExpr }), - colon: new TokenType(":", { beforeExpr: beforeExpr }), - doubleColon: new TokenType("::", { beforeExpr: beforeExpr }), - dot: new TokenType("."), - question: new TokenType("?", { beforeExpr: beforeExpr }), - arrow: new TokenType("=>", { beforeExpr: beforeExpr }), - template: new TokenType("template"), - ellipsis: new TokenType("...", { beforeExpr: beforeExpr }), - backQuote: new TokenType("`", { startsExpr: startsExpr }), - dollarBraceL: new TokenType("${", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - at: new TokenType("@"), + this.debug(function () { + return "Replace with " + (node && node.type); + }); - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. + this.node = this.container[this.key] = node; +} - eq: new TokenType("=", { beforeExpr: beforeExpr, isAssign: isAssign }), - assign: new TokenType("_=", { beforeExpr: beforeExpr, isAssign: isAssign }), - incDec: new TokenType("++/--", { prefix: prefix, postfix: postfix, startsExpr: startsExpr }), - prefix: new TokenType("prefix", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - logicalOR: new BinopTokenType("||", 1), - logicalAND: new BinopTokenType("&&", 2), - bitwiseOR: new BinopTokenType("|", 3), - bitwiseXOR: new BinopTokenType("^", 4), - bitwiseAND: new BinopTokenType("&", 5), - equality: new BinopTokenType("==/!=", 6), - relational: new BinopTokenType("", 7), - bitShift: new BinopTokenType("<>", 8), - plusMin: new TokenType("+/-", { beforeExpr: beforeExpr, binop: 9, prefix: prefix, startsExpr: startsExpr }), - modulo: new BinopTokenType("%", 10), - star: new BinopTokenType("*", 10), - slash: new BinopTokenType("/", 10), - exponent: new TokenType("**", { beforeExpr: beforeExpr, binop: 11, rightAssociative: true }) -}; +function replaceExpressionWithStatements(nodes) { + this.resync(); -var keywords = { - "break": new KeywordTokenType("break"), - "case": new KeywordTokenType("case", { beforeExpr: beforeExpr }), - "catch": new KeywordTokenType("catch"), - "continue": new KeywordTokenType("continue"), - "debugger": new KeywordTokenType("debugger"), - "default": new KeywordTokenType("default", { beforeExpr: beforeExpr }), - "do": new KeywordTokenType("do", { isLoop: isLoop, beforeExpr: beforeExpr }), - "else": new KeywordTokenType("else", { beforeExpr: beforeExpr }), - "finally": new KeywordTokenType("finally"), - "for": new KeywordTokenType("for", { isLoop: isLoop }), - "function": new KeywordTokenType("function", { startsExpr: startsExpr }), - "if": new KeywordTokenType("if"), - "return": new KeywordTokenType("return", { beforeExpr: beforeExpr }), - "switch": new KeywordTokenType("switch"), - "throw": new KeywordTokenType("throw", { beforeExpr: beforeExpr }), - "try": new KeywordTokenType("try"), - "var": new KeywordTokenType("var"), - "let": new KeywordTokenType("let"), - "const": new KeywordTokenType("const"), - "while": new KeywordTokenType("while", { isLoop: isLoop }), - "with": new KeywordTokenType("with"), - "new": new KeywordTokenType("new", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "this": new KeywordTokenType("this", { startsExpr: startsExpr }), - "super": new KeywordTokenType("super", { startsExpr: startsExpr }), - "class": new KeywordTokenType("class"), - "extends": new KeywordTokenType("extends", { beforeExpr: beforeExpr }), - "export": new KeywordTokenType("export"), - "import": new KeywordTokenType("import", { startsExpr: startsExpr }), - "yield": new KeywordTokenType("yield", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "null": new KeywordTokenType("null", { startsExpr: startsExpr }), - "true": new KeywordTokenType("true", { startsExpr: startsExpr }), - "false": new KeywordTokenType("false", { startsExpr: startsExpr }), - "in": new KeywordTokenType("in", { beforeExpr: beforeExpr, binop: 7 }), - "instanceof": new KeywordTokenType("instanceof", { beforeExpr: beforeExpr, binop: 7 }), - "typeof": new KeywordTokenType("typeof", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "void": new KeywordTokenType("void", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "delete": new KeywordTokenType("delete", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }) -}; + var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); -// Map keyword names to token types. -Object.keys(keywords).forEach(function (name) { - types["_" + name] = keywords[name]; -}); + if (t.isSequenceExpression(toSequenceExpression)) { + var exprs = toSequenceExpression.expressions; -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. + if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { + this._maybePopFromStatements(exprs); + } -var lineBreak = /\r\n?|\n|\u2028|\u2029/; -var lineBreakG = new RegExp(lineBreak.source, "g"); + if (exprs.length === 1) { + this.replaceWith(exprs[0]); + } else { + this.replaceWith(toSequenceExpression); + } + } else if (toSequenceExpression) { + this.replaceWith(toSequenceExpression); + } else { + var container = t.functionExpression(null, [], t.blockStatement(nodes)); + container.shadow = true; -function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; -} + this.replaceWith(t.callExpression(container, [])); + this.traverse(hoistVariablesVisitor); -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + var completionRecords = this.get("callee").getCompletionRecords(); + for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; -// The algorithm used to determine whether a regexp can appear at a -// given point in the program is loosely based on sweet.js' approach. -// See https://github.com/mozilla/sweet.js/wiki/design + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } -var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - classCallCheck(this, TokContext); + var path = _ref2; - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; -}; + if (!path.isExpressionStatement()) continue; -var types$1 = { - braceStatement: new TokContext("{", false), - braceExpression: new TokContext("{", true), - templateQuasi: new TokContext("${", true), - parenStatement: new TokContext("(", false), - parenExpression: new TokContext("(", true), - template: new TokContext("`", true, true, function (p) { - return p.readTmplToken(); - }), - functionExpression: new TokContext("function", true) -}; + var loop = path.findParent(function (path) { + return path.isLoop(); + }); + if (loop) { + var uid = loop.getData("expressionReplacementReturnUid"); -// Token-specific context update code + if (!uid) { + var callee = this.get("callee"); + uid = callee.scope.generateDeclaredUidIdentifier("ret"); + callee.get("body").pushContainer("body", t.returnStatement(uid)); + loop.setData("expressionReplacementReturnUid", uid); + } else { + uid = t.identifier(uid.name); + } -types.parenR.updateContext = types.braceR.updateContext = function () { - if (this.state.context.length === 1) { - this.state.exprAllowed = true; - return; - } + path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); + } else { + path.replaceWith(t.returnStatement(path.node.expression)); + } + } - var out = this.state.context.pop(); - if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) { - this.state.context.pop(); - this.state.exprAllowed = false; - } else if (out === types$1.templateQuasi) { - this.state.exprAllowed = true; - } else { - this.state.exprAllowed = !out.isExpr; + return this.node; } -}; +} -types.name.updateContext = function (prevType) { - this.state.exprAllowed = false; +function replaceInline(nodes) { + this.resync(); - if (prevType === types._let || prevType === types._const || prevType === types._var) { - if (lineBreak.test(this.input.slice(this.state.end))) { - this.state.exprAllowed = true; + if (Array.isArray(nodes)) { + if (Array.isArray(this.container)) { + nodes = this._verifyNodeList(nodes); + this._containerInsertAfter(nodes); + return this.remove(); + } else { + return this.replaceWithMultiple(nodes); } + } else { + return this.replaceWith(nodes); } -}; - -types.braceL.updateContext = function (prevType) { - this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); - this.state.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function () { - this.state.context.push(types$1.templateQuasi); - this.state.exprAllowed = true; -}; - -types.parenL.updateContext = function (prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); - this.state.exprAllowed = true; -}; - -types.incDec.updateContext = function () { - // tokExprAllowed stays unchanged -}; +} +},{"../index":150,"./index":157,"babel-code-frame":61,"babel-runtime/core-js/get-iterator":127,"babel-types":183,"babylon":187}],168:[function(require,module,exports){ +"use strict"; -types._function.updateContext = function () { - if (this.curContext() !== types$1.braceStatement) { - this.state.context.push(types$1.functionExpression); - } +exports.__esModule = true; - this.state.exprAllowed = false; -}; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); -types.backQuote.updateContext = function () { - if (this.curContext() === types$1.template) { - this.state.context.pop(); - } else { - this.state.context.push(types$1.template); - } - this.state.exprAllowed = false; -}; +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); -// These are used when `options.locations` is on, for the -// `startLoc` and `endLoc` properties. +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Position = function Position(line, col) { - classCallCheck(this, Position); +var Binding = function () { + function Binding(_ref) { + var existing = _ref.existing, + identifier = _ref.identifier, + scope = _ref.scope, + path = _ref.path, + kind = _ref.kind; + (0, _classCallCheck3.default)(this, Binding); - this.line = line; - this.column = col; -}; + this.identifier = identifier; + this.scope = scope; + this.path = path; + this.kind = kind; -var SourceLocation = function SourceLocation(start, end) { - classCallCheck(this, SourceLocation); + this.constantViolations = []; + this.constant = true; - this.start = start; - this.end = end; -}; + this.referencePaths = []; + this.referenced = false; + this.references = 0; -// The `getLineInfo` function is mostly useful when the -// `locations` option is off (for performance reasons) and you -// want to find the line/column position for a given character -// offset. `input` should be the code string that the offset refers -// into. + this.clearValue(); -function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur); + if (existing) { + this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); } } -} -var State = function () { - function State() { - classCallCheck(this, State); - } + Binding.prototype.deoptValue = function deoptValue() { + this.clearValue(); + this.hasDeoptedValue = true; + }; - State.prototype.init = function init(options, input) { - this.strict = options.strictMode === false ? false : options.sourceType === "module"; + Binding.prototype.setValue = function setValue(value) { + if (this.hasDeoptedValue) return; + this.hasValue = true; + this.value = value; + }; - this.input = input; + Binding.prototype.clearValue = function clearValue() { + this.hasDeoptedValue = false; + this.hasValue = false; + this.value = null; + }; - this.potentialArrowAt = -1; + Binding.prototype.reassign = function reassign(path) { + this.constant = false; + if (this.constantViolations.indexOf(path) !== -1) { + return; + } + this.constantViolations.push(path); + }; - this.inMethod = this.inFunction = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.inClassProperty = this.noAnonFunctionType = false; + Binding.prototype.reference = function reference(path) { + if (this.referencePaths.indexOf(path) !== -1) { + return; + } + this.referenced = true; + this.references++; + this.referencePaths.push(path); + }; - this.labels = []; + Binding.prototype.dereference = function dereference() { + this.references--; + this.referenced = !!this.references; + }; - this.decorators = []; + return Binding; +}(); - this.tokens = []; +exports.default = Binding; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":141}],169:[function(require,module,exports){ +"use strict"; - this.comments = []; +exports.__esModule = true; - this.trailingComments = []; - this.leadingComments = []; - this.commentStack = []; +var _keys = require("babel-runtime/core-js/object/keys"); - this.pos = this.lineStart = 0; - this.curLine = options.startLine; +var _keys2 = _interopRequireDefault(_keys); - this.type = types.eof; - this.value = null; - this.start = this.end = this.pos; - this.startLoc = this.endLoc = this.curPosition(); +var _create = require("babel-runtime/core-js/object/create"); - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; +var _create2 = _interopRequireDefault(_create); - this.context = [types$1.braceStatement]; - this.exprAllowed = true; +var _map = require("babel-runtime/core-js/map"); - this.containsEsc = this.containsOctal = false; - this.octalPosition = null; +var _map2 = _interopRequireDefault(_map); - this.invalidTemplateEscapePosition = null; +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - this.exportedIdentifiers = []; +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - return this; - }; +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - // TODO +var _getIterator3 = _interopRequireDefault(_getIterator2); +var _includes = require("lodash/includes"); - // TODO +var _includes2 = _interopRequireDefault(_includes); +var _repeat = require("lodash/repeat"); - // Used to signify the start of a potential arrow function +var _repeat2 = _interopRequireDefault(_repeat); +var _renamer = require("./lib/renamer"); - // Flags to track whether we are in a function, a generator. +var _renamer2 = _interopRequireDefault(_renamer); +var _index = require("../index"); - // Labels in scope. +var _index2 = _interopRequireDefault(_index); +var _defaults = require("lodash/defaults"); - // Leading decorators. +var _defaults2 = _interopRequireDefault(_defaults); +var _babelMessages = require("babel-messages"); - // Token store. +var messages = _interopRequireWildcard(_babelMessages); +var _binding2 = require("./binding"); - // Comment store. +var _binding3 = _interopRequireDefault(_binding2); +var _globals = require("globals"); - // Comment attachment store +var _globals2 = _interopRequireDefault(_globals); +var _babelTypes = require("babel-types"); - // The current position of the tokenizer in the input. +var t = _interopRequireWildcard(_babelTypes); +var _cache = require("../cache"); - // Properties of the current token: - // Its type +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // For tokens that include more information than their type, the value +var _crawlCallsCount = 0; +function getCache(path, parentScope, self) { + var scopes = _cache.scope.get(path.node) || []; - // Its start and end offset + for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref; + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } - // And, if locations are used, the {line, column} object - // corresponding to those offsets + var scope = _ref; + if (scope.parent === parentScope && scope.path === path) return scope; + } - // Position information for the previous token + scopes.push(self); + if (!_cache.scope.has(path.node)) { + _cache.scope.set(path.node, scopes); + } +} - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. +function gatherNodeParts(node, parts) { + if (t.isModuleDeclaration(node)) { + if (node.source) { + gatherNodeParts(node.source, parts); + } else if (node.specifiers && node.specifiers.length) { + for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } - // TODO + var specifier = _ref2; + gatherNodeParts(specifier, parts); + } + } else if (node.declaration) { + gatherNodeParts(node.declaration, parts); + } + } else if (t.isModuleSpecifier(node)) { + gatherNodeParts(node.local, parts); + } else if (t.isMemberExpression(node)) { + gatherNodeParts(node.object, parts); + gatherNodeParts(node.property, parts); + } else if (t.isIdentifier(node)) { + parts.push(node.name); + } else if (t.isLiteral(node)) { + parts.push(node.value); + } else if (t.isCallExpression(node)) { + gatherNodeParts(node.callee, parts); + } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { + for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; - // Names of exports store. `default` is stored as a name for both - // `export default foo;` and `export { foo as default };`. + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + var prop = _ref3; - State.prototype.curPosition = function curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); - }; + gatherNodeParts(prop.key || prop.argument, parts); + } + } +} - State.prototype.clone = function clone(skipArrays) { - var state = new State(); - for (var key in this) { - var val = this[key]; +var collectorVisitor = { + For: function For(path) { + for (var _iterator4 = t.FOR_INIT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; - if ((!skipArrays || key === "context") && Array.isArray(val)) { - val = val.slice(); + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; } - state[key] = val; + var key = _ref4; + + var declar = path.get(key); + if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); } - return state; - }; + }, + Declaration: function Declaration(path) { + if (path.isBlockScoped()) return; - return State; -}(); + if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; -// Object type used to represent tokens. Note that normally, tokens -// simply exist as properties on the parser object. This is only -// used for the onToken callback and the external tokenizer. + path.scope.getFunctionParent().registerDeclaration(path); + }, + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + state.references.push(path); + }, + ForXStatement: function ForXStatement(path, state) { + var left = path.get("left"); + if (left.isPattern() || left.isIdentifier()) { + state.constantViolations.push(left); + } + }, -var Token = function Token(state) { - classCallCheck(this, Token); - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); -}; + ExportDeclaration: { + exit: function exit(path) { + var node = path.node, + scope = path.scope; -// ## Tokenizer + var declar = node.declaration; + if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { + var _id = declar.id; + if (!_id) return; -function codePointToString(code) { - // UTF-16 Decoding - if (code <= 0xFFFF) { - return String.fromCharCode(code); - } else { - return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00); - } -} + var binding = scope.getBinding(_id.name); + if (binding) binding.reference(path); + } else if (t.isVariableDeclaration(declar)) { + for (var _iterator5 = declar.declarations, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; -var Tokenizer = function () { - function Tokenizer(options, input) { - classCallCheck(this, Tokenizer); + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } - this.state = new State(); - this.state.init(options, input); - } + var decl = _ref5; - // Move to the next token + var ids = t.getBindingIdentifiers(decl); + for (var name in ids) { + var _binding = scope.getBinding(name); + if (_binding) _binding.reference(path); + } + } + } + } + }, - Tokenizer.prototype.next = function next() { - if (!this.isLookahead) { - this.state.tokens.push(new Token(this.state)); + LabeledStatement: function LabeledStatement(path) { + path.scope.getProgramParent().addGlobal(path.node); + path.scope.getBlockParent().registerDeclaration(path); + }, + AssignmentExpression: function AssignmentExpression(path, state) { + state.assignments.push(path); + }, + UpdateExpression: function UpdateExpression(path, state) { + state.constantViolations.push(path.get("argument")); + }, + UnaryExpression: function UnaryExpression(path, state) { + if (path.node.operator === "delete") { + state.constantViolations.push(path.get("argument")); } + }, + BlockScoped: function BlockScoped(path) { + var scope = path.scope; + if (scope.path === path) scope = scope.parent; + scope.getBlockParent().registerDeclaration(path); + }, + ClassDeclaration: function ClassDeclaration(path) { + var id = path.node.id; + if (!id) return; - this.state.lastTokEnd = this.state.end; - this.state.lastTokStart = this.state.start; - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); - }; + var name = id.name; + path.scope.bindings[name] = path.scope.getBinding(name); + }, + Block: function Block(path) { + var paths = path.get("body"); + for (var _iterator6 = paths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref6; - // TODO + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } - Tokenizer.prototype.eat = function eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; + var bodyPath = _ref6; + + if (bodyPath.isFunctionDeclaration()) { + path.scope.getBlockParent().registerDeclaration(bodyPath); + } } - }; + } +}; - // TODO +var uid = 0; - Tokenizer.prototype.match = function match(type) { - return this.state.type === type; - }; +var Scope = function () { + function Scope(path, parentScope) { + (0, _classCallCheck3.default)(this, Scope); - // TODO + if (parentScope && parentScope.block === path.node) { + return parentScope; + } - Tokenizer.prototype.isKeyword = function isKeyword$$1(word) { - return isKeyword(word); - }; + var cached = getCache(path, parentScope, this); + if (cached) return cached; - // TODO + this.uid = uid++; + this.parent = parentScope; + this.hub = path.hub; - Tokenizer.prototype.lookahead = function lookahead() { - var old = this.state; - this.state = old.clone(true); + this.parentBlock = path.parent; + this.block = path.node; + this.path = path; - this.isLookahead = true; - this.next(); - this.isLookahead = false; + this.labels = new _map2.default(); + } - var curr = this.state.clone(true); - this.state = old; - return curr; + Scope.prototype.traverse = function traverse(node, opts, state) { + (0, _index2.default)(node, opts, this, state, this.path); }; - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). + Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - Tokenizer.prototype.setStrict = function setStrict(strict) { - this.state.strict = strict; - if (!this.match(types.num) && !this.match(types.string)) return; - this.state.pos = this.state.start; - while (this.state.pos < this.state.lineStart) { - this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; - --this.state.curLine; - } - this.nextToken(); + var id = this.generateUidIdentifier(name); + this.push({ id: id }); + return id; }; - Tokenizer.prototype.curContext = function curContext() { - return this.state.context[this.state.context.length - 1]; + Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + + return t.identifier(this.generateUid(name)); }; - // Read a single token, updating the parser object's token-related - // properties. + Scope.prototype.generateUid = function generateUid() { + var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - Tokenizer.prototype.nextToken = function nextToken() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) this.skipSpace(); + name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); - this.state.containsOctal = false; - this.state.octalPosition = null; - this.state.start = this.state.pos; - this.state.startLoc = this.state.curPosition(); - if (this.state.pos >= this.input.length) return this.finishToken(types.eof); + var uid = void 0; + var i = 0; + do { + uid = this._generateUid(name, i); + i++; + } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); - if (curContext.override) { - return curContext.override(this); - } else { - return this.readToken(this.fullCharCodeAtPos()); - } - }; + var program = this.getProgramParent(); + program.references[uid] = true; + program.uids[uid] = true; - Tokenizer.prototype.readToken = function readToken(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code) || code === 92 /* '\' */) { - return this.readWord(); - } else { - return this.getTokenFromCode(code); - } + return uid; }; - Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() { - var code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; - - var next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; + Scope.prototype._generateUid = function _generateUid(name, i) { + var id = name; + if (i > 1) id += i; + return "_" + id; }; - Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "CommentBlock" : "CommentLine", - value: text, - start: start, - end: end, - loc: new SourceLocation(startLoc, endLoc) - }; + Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { + var node = parent; - if (!this.isLookahead) { - this.state.tokens.push(comment); - this.state.comments.push(comment); - this.addComment(comment); + if (t.isAssignmentExpression(parent)) { + node = parent.left; + } else if (t.isVariableDeclarator(parent)) { + node = parent.id; + } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { + node = node.key; } - }; - Tokenizer.prototype.skipBlockComment = function skipBlockComment() { - var startLoc = this.state.curPosition(); - var start = this.state.pos; - var end = this.input.indexOf("*/", this.state.pos += 2); - if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); + var parts = []; + gatherNodeParts(node, parts); - this.state.pos = end + 2; - lineBreakG.lastIndex = start; - var match = void 0; - while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { - ++this.state.curLine; - this.state.lineStart = match.index + match[0].length; - } + var id = parts.join("$"); + id = id.replace(/^_/, "") || defaultName || "ref"; - this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); + return this.generateUidIdentifier(id.slice(0, 20)); }; - Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) { - var start = this.state.pos; - var startLoc = this.state.curPosition(); - var ch = this.input.charCodeAt(this.state.pos += startSkip); - while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this.state.pos; - ch = this.input.charCodeAt(this.state.pos); + Scope.prototype.isStatic = function isStatic(node) { + if (t.isThisExpression(node) || t.isSuper(node)) { + return true; } - this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - Tokenizer.prototype.skipSpace = function skipSpace() { - loop: while (this.state.pos < this.input.length) { - var ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 32:case 160: - // ' ' - ++this.state.pos; - break; + if (t.isIdentifier(node)) { + var binding = this.getBinding(node.name); + if (binding) { + return binding.constant; + } else { + return this.hasBinding(node.name); + } + } - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } + return false; + }; - case 10:case 8232:case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; + Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { + if (this.isStatic(node)) { + return null; + } else { + var _id2 = this.generateUidIdentifierBasedOnNode(node); + if (!dontPush) this.push({ id: _id2 }); + return _id2; + } + }; - case 47: - // '/' - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - // '*' - this.skipBlockComment(); - break; + Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { + if (kind === "param") return; - case 47: - this.skipLineComment(2); - break; + if (kind === "hoisted" && local.kind === "let") return; - default: - break loop; - } - break; + var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.state.pos; - } else { - break loop; - } - } + if (duplicate) { + throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); } }; - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. + Scope.prototype.rename = function rename(oldName, newName, block) { + var binding = this.getBinding(oldName); + if (binding) { + newName = newName || this.generateUidIdentifier(oldName).name; + return new _renamer2.default(binding, oldName, newName).rename(block); + } + }; - Tokenizer.prototype.finishToken = function finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - var prevType = this.state.type; - this.state.type = type; - this.state.value = val; + Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { + if (map[oldName]) { + map[newName] = value; + map[oldName] = null; + } + }; - this.updateContext(prevType); + Scope.prototype.dump = function dump() { + var sep = (0, _repeat2.default)("-", 60); + console.log(sep); + var scope = this; + do { + console.log("#", scope.block.type); + for (var name in scope.bindings) { + var binding = scope.bindings[name]; + console.log(" -", name, { + constant: binding.constant, + references: binding.references, + violations: binding.constantViolations.length, + kind: binding.kind + }); + } + } while (scope = scope.parent); + console.log(sep); }; - // ### Token reading + Scope.prototype.toArray = function toArray(node, i) { + var file = this.hub.file; - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // + if (t.isIdentifier(node)) { + var binding = this.getBinding(node.name); + if (binding && binding.constant && binding.path.isGenericType("Array")) return node; + } + if (t.isArrayExpression(node)) { + return node; + } - Tokenizer.prototype.readToken_dot = function readToken_dot() { - var next = this.input.charCodeAt(this.state.pos + 1); - if (next >= 48 && next <= 57) { - return this.readNumber(true); + if (t.isIdentifier(node, { name: "arguments" })) { + return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); } - var next2 = this.input.charCodeAt(this.state.pos + 2); - if (next === 46 && next2 === 46) { - // 46 = dot '.' - this.state.pos += 3; - return this.finishToken(types.ellipsis); - } else { - ++this.state.pos; - return this.finishToken(types.dot); + var helperName = "toArray"; + var args = [node]; + if (i === true) { + helperName = "toConsumableArray"; + } else if (i) { + args.push(t.numericLiteral(i)); + helperName = "slicedToArray"; } + return t.callExpression(file.addHelper(helperName), args); }; - Tokenizer.prototype.readToken_slash = function readToken_slash() { - // '/' - if (this.state.exprAllowed) { - ++this.state.pos; - return this.readRegexp(); - } + Scope.prototype.hasLabel = function hasLabel(name) { + return !!this.getLabel(name); + }; - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.slash, 1); - } + Scope.prototype.getLabel = function getLabel(name) { + return this.labels.get(name); }; - Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) { - // '%*' - var type = code === 42 ? types.star : types.modulo; - var width = 1; - var next = this.input.charCodeAt(this.state.pos + 1); + Scope.prototype.registerLabel = function registerLabel(path) { + this.labels.set(path.node.label.name, path); + }; - if (next === 42) { - // '*' - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = types.exponent; - } + Scope.prototype.registerDeclaration = function registerDeclaration(path) { + if (path.isLabeledStatement()) { + this.registerLabel(path); + } else if (path.isFunctionDeclaration()) { + this.registerBinding("hoisted", path.get("id"), path); + } else if (path.isVariableDeclaration()) { + var declarations = path.get("declarations"); + for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref7; - if (next === 61) { - width++; - type = types.assign; - } + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } - return this.finishOp(type, width); - }; + var declar = _ref7; - Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) { - // '|&' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); - if (next === 61) return this.finishOp(types.assign, 2); - if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(types.braceBarR, 2); - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); - }; + this.registerBinding(path.node.kind, declar); + } + } else if (path.isClassDeclaration()) { + this.registerBinding("let", path); + } else if (path.isImportDeclaration()) { + var specifiers = path.get("specifiers"); + for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { + var _ref8; - Tokenizer.prototype.readToken_caret = function readToken_caret() { - // '^' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.bitwiseXOR, 1); - } - }; + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref8 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref8 = _i8.value; + } - Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) { - // '+-' - var next = this.input.charCodeAt(this.state.pos + 1); + var specifier = _ref8; - if (next === code) { - if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken(); + this.registerBinding("module", specifier); } - return this.finishOp(types.incDec, 2); + } else if (path.isExportDeclaration()) { + var _declar = path.get("declaration"); + if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { + this.registerDeclaration(_declar); + } + } else { + this.registerBinding("unknown", path); } + }; - if (next === 61) { - return this.finishOp(types.assign, 2); + Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { + if (this.hasBinding("undefined")) { + return t.unaryExpression("void", t.numericLiteral(0), true); } else { - return this.finishOp(types.plusMin, 1); + return t.identifier("undefined"); } }; - Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { - // '<>' - var next = this.input.charCodeAt(this.state.pos + 1); - var size = 1; - - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1); - return this.finishOp(types.bitShift, size); + Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { + var ids = path.getBindingIdentifiers(); + for (var name in ids) { + var binding = this.getBinding(name); + if (binding) binding.reassign(path); } + }; - if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { - if (this.inModule) this.unexpected(); - // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken(); + } + return this.finishOp(types.incDec, 2); + } -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = require('./_dom-create')('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - require('./_html').appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); -}; + if (next === 61) { + return this.finishOp(types.assign, 2); + } else { + return this.finishOp(types.plusMin, 1); + } + }; -module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); -}; + Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { + // '<>' + var next = this.input.charCodeAt(this.state.pos + 1); + var size = 1; -},{"./_an-object":172,"./_dom-create":188,"./_enum-bug-keys":189,"./_html":197,"./_object-dps":214,"./_shared-key":232}],213:[function(require,module,exports){ -var anObject = require('./_an-object'); -var IE8_DOM_DEFINE = require('./_ie8-dom-define'); -var toPrimitive = require('./_to-primitive'); -var dP = Object.defineProperty; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1); + return this.finishOp(types.bitShift, size); + } -exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; -}; + if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { + if (this.inModule) this.unexpected(); + // `' is a single-line comment - this.index += 3; - var comment = this.skipSingleLineComment(3); - if (this.trackComment) { - comments = comments.concat(comment); - } - } - else { - break; - } - } - else if (ch === 0x3C) { - if (this.source.slice(this.index + 1, this.index + 4) === '!--') { - this.index += 4; // `' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // ` regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + ch = id.charCodeAt(0); + if (!code.isIdentifierStartES5(ch)) { + return false; + } - this.debug(this.pattern, set) + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPartES5(ch)) { + return false; + } + } + return true; + } - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } - this.debug(this.pattern, set) + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; - this.set = set -} + if (id.length === 0) { return false; } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + check = code.isIdentifierStartES6; + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + if (i >= iz) { return false; } + lowCh = id.charCodeAt(i); + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + ch = decodeUtf16(ch, lowCh); + } + if (!check(ch)) { + return false; + } + check = code.isIdentifierPartES6; + } + return true; + } - if (options.nonegate) return + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} +},{"./code":316}],318:[function(require,module,exports){ +/* + Copyright (C) 2013 Yusuke Suzuki -Minimatch.prototype.braceExpand = braceExpand + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } +(function () { + 'use strict'; - return expand(pattern) + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ + +},{"./ast":315,"./code":316,"./keyword":317}],319:[function(require,module,exports){ +module.exports={ + "builtin": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "System": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es5": { + "Array": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "propertyIsEnumerable": false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false + }, + "es6": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "System": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "browser": { + "addEventListener": false, + "alert": false, + "AnalyserNode": false, + "Animation": false, + "AnimationEffectReadOnly": false, + "AnimationEffectTiming": false, + "AnimationEffectTimingReadOnly": false, + "AnimationEvent": false, + "AnimationPlaybackEvent": false, + "AnimationTimeline": false, + "applicationCache": false, + "ApplicationCache": false, + "ApplicationCacheErrorEvent": false, + "atob": false, + "Attr": false, + "Audio": false, + "AudioBuffer": false, + "AudioBufferSourceNode": false, + "AudioContext": false, + "AudioDestinationNode": false, + "AudioListener": false, + "AudioNode": false, + "AudioParam": false, + "AudioProcessingEvent": false, + "AutocompleteErrorEvent": false, + "BarProp": false, + "BatteryManager": false, + "BeforeUnloadEvent": false, + "BiquadFilterNode": false, + "Blob": false, + "blur": false, + "btoa": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "cancelAnimationFrame": false, + "cancelIdleCallback": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "CDATASection": false, + "ChannelMergerNode": false, + "ChannelSplitterNode": false, + "CharacterData": false, + "clearInterval": false, + "clearTimeout": false, + "clientInformation": false, + "ClientRect": false, + "ClientRectList": false, + "ClipboardEvent": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "confirm": false, + "console": false, + "ConvolverNode": false, + "createImageBitmap": false, + "Credential": false, + "CredentialsContainer": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CSS": false, + "CSSAnimation": false, + "CSSFontFaceRule": false, + "CSSImportRule": false, + "CSSKeyframeRule": false, + "CSSKeyframesRule": false, + "CSSMediaRule": false, + "CSSPageRule": false, + "CSSRule": false, + "CSSRuleList": false, + "CSSStyleDeclaration": false, + "CSSStyleRule": false, + "CSSStyleSheet": false, + "CSSSupportsRule": false, + "CSSTransition": false, + "CSSUnknownRule": false, + "CSSViewportRule": false, + "customElements": false, + "CustomEvent": false, + "DataTransfer": false, + "DataTransferItem": false, + "DataTransferItemList": false, + "Debug": false, + "defaultStatus": false, + "defaultstatus": false, + "DelayNode": false, + "DeviceMotionEvent": false, + "DeviceOrientationEvent": false, + "devicePixelRatio": false, + "dispatchEvent": false, + "document": false, + "Document": false, + "DocumentFragment": false, + "DocumentTimeline": false, + "DocumentType": false, + "DOMError": false, + "DOMException": false, + "DOMImplementation": false, + "DOMParser": false, + "DOMSettableTokenList": false, + "DOMStringList": false, + "DOMStringMap": false, + "DOMTokenList": false, + "DragEvent": false, + "DynamicsCompressorNode": false, + "Element": false, + "ElementTimeControl": false, + "ErrorEvent": false, + "event": false, + "Event": false, + "EventSource": false, + "EventTarget": false, + "external": false, + "FederatedCredential": false, + "fetch": false, + "File": false, + "FileError": false, + "FileList": false, + "FileReader": false, + "find": false, + "focus": false, + "FocusEvent": false, + "FontFace": false, + "FormData": false, + "frameElement": false, + "frames": false, + "GainNode": false, + "Gamepad": false, + "GamepadButton": false, + "GamepadEvent": false, + "getComputedStyle": false, + "getSelection": false, + "HashChangeEvent": false, + "Headers": false, + "history": false, + "History": false, + "HTMLAllCollection": false, + "HTMLAnchorElement": false, + "HTMLAppletElement": false, + "HTMLAreaElement": false, + "HTMLAudioElement": false, + "HTMLBaseElement": false, + "HTMLBlockquoteElement": false, + "HTMLBodyElement": false, + "HTMLBRElement": false, + "HTMLButtonElement": false, + "HTMLCanvasElement": false, + "HTMLCollection": false, + "HTMLContentElement": false, + "HTMLDataListElement": false, + "HTMLDetailsElement": false, + "HTMLDialogElement": false, + "HTMLDirectoryElement": false, + "HTMLDivElement": false, + "HTMLDListElement": false, + "HTMLDocument": false, + "HTMLElement": false, + "HTMLEmbedElement": false, + "HTMLFieldSetElement": false, + "HTMLFontElement": false, + "HTMLFormControlsCollection": false, + "HTMLFormElement": false, + "HTMLFrameElement": false, + "HTMLFrameSetElement": false, + "HTMLHeadElement": false, + "HTMLHeadingElement": false, + "HTMLHRElement": false, + "HTMLHtmlElement": false, + "HTMLIFrameElement": false, + "HTMLImageElement": false, + "HTMLInputElement": false, + "HTMLIsIndexElement": false, + "HTMLKeygenElement": false, + "HTMLLabelElement": false, + "HTMLLayerElement": false, + "HTMLLegendElement": false, + "HTMLLIElement": false, + "HTMLLinkElement": false, + "HTMLMapElement": false, + "HTMLMarqueeElement": false, + "HTMLMediaElement": false, + "HTMLMenuElement": false, + "HTMLMetaElement": false, + "HTMLMeterElement": false, + "HTMLModElement": false, + "HTMLObjectElement": false, + "HTMLOListElement": false, + "HTMLOptGroupElement": false, + "HTMLOptionElement": false, + "HTMLOptionsCollection": false, + "HTMLOutputElement": false, + "HTMLParagraphElement": false, + "HTMLParamElement": false, + "HTMLPictureElement": false, + "HTMLPreElement": false, + "HTMLProgressElement": false, + "HTMLQuoteElement": false, + "HTMLScriptElement": false, + "HTMLSelectElement": false, + "HTMLShadowElement": false, + "HTMLSourceElement": false, + "HTMLSpanElement": false, + "HTMLStyleElement": false, + "HTMLTableCaptionElement": false, + "HTMLTableCellElement": false, + "HTMLTableColElement": false, + "HTMLTableElement": false, + "HTMLTableRowElement": false, + "HTMLTableSectionElement": false, + "HTMLTemplateElement": false, + "HTMLTextAreaElement": false, + "HTMLTitleElement": false, + "HTMLTrackElement": false, + "HTMLUListElement": false, + "HTMLUnknownElement": false, + "HTMLVideoElement": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBEnvironment": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "Image": false, + "ImageBitmap": false, + "ImageData": false, + "indexedDB": false, + "innerHeight": false, + "innerWidth": false, + "InputEvent": false, + "InputMethodContext": false, + "IntersectionObserver": false, + "IntersectionObserverEntry": false, + "Intl": false, + "KeyboardEvent": false, + "KeyframeEffect": false, + "KeyframeEffectReadOnly": false, + "length": false, + "localStorage": false, + "location": false, + "Location": false, + "locationbar": false, + "matchMedia": false, + "MediaElementAudioSourceNode": false, + "MediaEncryptedEvent": false, + "MediaError": false, + "MediaKeyError": false, + "MediaKeyEvent": false, + "MediaKeyMessageEvent": false, + "MediaKeys": false, + "MediaKeySession": false, + "MediaKeyStatusMap": false, + "MediaKeySystemAccess": false, + "MediaList": false, + "MediaQueryList": false, + "MediaQueryListEvent": false, + "MediaSource": false, + "MediaRecorder": false, + "MediaStream": false, + "MediaStreamAudioDestinationNode": false, + "MediaStreamAudioSourceNode": false, + "MediaStreamEvent": false, + "MediaStreamTrack": false, + "menubar": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "MIDIAccess": false, + "MIDIConnectionEvent": false, + "MIDIInput": false, + "MIDIInputMap": false, + "MIDIMessageEvent": false, + "MIDIOutput": false, + "MIDIOutputMap": false, + "MIDIPort": false, + "MimeType": false, + "MimeTypeArray": false, + "MouseEvent": false, + "moveBy": false, + "moveTo": false, + "MutationEvent": false, + "MutationObserver": false, + "MutationRecord": false, + "name": false, + "NamedNodeMap": false, + "navigator": false, + "Navigator": false, + "Node": false, + "NodeFilter": false, + "NodeIterator": false, + "NodeList": false, + "Notification": false, + "OfflineAudioCompletionEvent": false, + "OfflineAudioContext": false, + "offscreenBuffering": false, + "onbeforeunload": true, + "onblur": true, + "onerror": true, + "onfocus": true, + "onload": true, + "onresize": true, + "onunload": true, + "open": false, + "openDatabase": false, + "opener": false, + "opera": false, + "Option": false, + "OscillatorNode": false, + "outerHeight": false, + "outerWidth": false, + "PageTransitionEvent": false, + "pageXOffset": false, + "pageYOffset": false, + "parent": false, + "PasswordCredential": false, + "Path2D": false, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "PeriodicWave": false, + "Permissions": false, + "PermissionStatus": false, + "personalbar": false, + "Plugin": false, + "PluginArray": false, + "PopStateEvent": false, + "postMessage": false, + "print": false, + "ProcessingInstruction": false, + "ProgressEvent": false, + "PromiseRejectionEvent": false, + "prompt": false, + "PushManager": false, + "PushSubscription": false, + "RadioNodeList": false, + "Range": false, + "ReadableByteStream": false, + "ReadableStream": false, + "removeEventListener": false, + "Request": false, + "requestAnimationFrame": false, + "requestIdleCallback": false, + "resizeBy": false, + "resizeTo": false, + "Response": false, + "RTCIceCandidate": false, + "RTCSessionDescription": false, + "RTCPeerConnection": false, + "screen": false, + "Screen": false, + "screenLeft": false, + "ScreenOrientation": false, + "screenTop": false, + "screenX": false, + "screenY": false, + "ScriptProcessorNode": false, + "scroll": false, + "scrollbars": false, + "scrollBy": false, + "scrollTo": false, + "scrollX": false, + "scrollY": false, + "SecurityPolicyViolationEvent": false, + "Selection": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerRegistration": false, + "sessionStorage": false, + "setInterval": false, + "setTimeout": false, + "ShadowRoot": false, + "SharedKeyframeList": false, + "SharedWorker": false, + "showModalDialog": false, + "SiteBoundCredential": false, + "speechSynthesis": false, + "SpeechSynthesisEvent": false, + "SpeechSynthesisUtterance": false, + "status": false, + "statusbar": false, + "stop": false, + "Storage": false, + "StorageEvent": false, + "styleMedia": false, + "StyleSheet": false, + "StyleSheetList": false, + "SubtleCrypto": false, + "SVGAElement": false, + "SVGAltGlyphDefElement": false, + "SVGAltGlyphElement": false, + "SVGAltGlyphItemElement": false, + "SVGAngle": false, + "SVGAnimateColorElement": false, + "SVGAnimatedAngle": false, + "SVGAnimatedBoolean": false, + "SVGAnimatedEnumeration": false, + "SVGAnimatedInteger": false, + "SVGAnimatedLength": false, + "SVGAnimatedLengthList": false, + "SVGAnimatedNumber": false, + "SVGAnimatedNumberList": false, + "SVGAnimatedPathData": false, + "SVGAnimatedPoints": false, + "SVGAnimatedPreserveAspectRatio": false, + "SVGAnimatedRect": false, + "SVGAnimatedString": false, + "SVGAnimatedTransformList": false, + "SVGAnimateElement": false, + "SVGAnimateMotionElement": false, + "SVGAnimateTransformElement": false, + "SVGAnimationElement": false, + "SVGCircleElement": false, + "SVGClipPathElement": false, + "SVGColor": false, + "SVGColorProfileElement": false, + "SVGColorProfileRule": false, + "SVGComponentTransferFunctionElement": false, + "SVGCSSRule": false, + "SVGCursorElement": false, + "SVGDefsElement": false, + "SVGDescElement": false, + "SVGDiscardElement": false, + "SVGDocument": false, + "SVGElement": false, + "SVGElementInstance": false, + "SVGElementInstanceList": false, + "SVGEllipseElement": false, + "SVGEvent": false, + "SVGExternalResourcesRequired": false, + "SVGFEBlendElement": false, + "SVGFEColorMatrixElement": false, + "SVGFEComponentTransferElement": false, + "SVGFECompositeElement": false, + "SVGFEConvolveMatrixElement": false, + "SVGFEDiffuseLightingElement": false, + "SVGFEDisplacementMapElement": false, + "SVGFEDistantLightElement": false, + "SVGFEDropShadowElement": false, + "SVGFEFloodElement": false, + "SVGFEFuncAElement": false, + "SVGFEFuncBElement": false, + "SVGFEFuncGElement": false, + "SVGFEFuncRElement": false, + "SVGFEGaussianBlurElement": false, + "SVGFEImageElement": false, + "SVGFEMergeElement": false, + "SVGFEMergeNodeElement": false, + "SVGFEMorphologyElement": false, + "SVGFEOffsetElement": false, + "SVGFEPointLightElement": false, + "SVGFESpecularLightingElement": false, + "SVGFESpotLightElement": false, + "SVGFETileElement": false, + "SVGFETurbulenceElement": false, + "SVGFilterElement": false, + "SVGFilterPrimitiveStandardAttributes": false, + "SVGFitToViewBox": false, + "SVGFontElement": false, + "SVGFontFaceElement": false, + "SVGFontFaceFormatElement": false, + "SVGFontFaceNameElement": false, + "SVGFontFaceSrcElement": false, + "SVGFontFaceUriElement": false, + "SVGForeignObjectElement": false, + "SVGGElement": false, + "SVGGeometryElement": false, + "SVGGlyphElement": false, + "SVGGlyphRefElement": false, + "SVGGradientElement": false, + "SVGGraphicsElement": false, + "SVGHKernElement": false, + "SVGICCColor": false, + "SVGImageElement": false, + "SVGLangSpace": false, + "SVGLength": false, + "SVGLengthList": false, + "SVGLinearGradientElement": false, + "SVGLineElement": false, + "SVGLocatable": false, + "SVGMarkerElement": false, + "SVGMaskElement": false, + "SVGMatrix": false, + "SVGMetadataElement": false, + "SVGMissingGlyphElement": false, + "SVGMPathElement": false, + "SVGNumber": false, + "SVGNumberList": false, + "SVGPaint": false, + "SVGPathElement": false, + "SVGPathSeg": false, + "SVGPathSegArcAbs": false, + "SVGPathSegArcRel": false, + "SVGPathSegClosePath": false, + "SVGPathSegCurvetoCubicAbs": false, + "SVGPathSegCurvetoCubicRel": false, + "SVGPathSegCurvetoCubicSmoothAbs": false, + "SVGPathSegCurvetoCubicSmoothRel": false, + "SVGPathSegCurvetoQuadraticAbs": false, + "SVGPathSegCurvetoQuadraticRel": false, + "SVGPathSegCurvetoQuadraticSmoothAbs": false, + "SVGPathSegCurvetoQuadraticSmoothRel": false, + "SVGPathSegLinetoAbs": false, + "SVGPathSegLinetoHorizontalAbs": false, + "SVGPathSegLinetoHorizontalRel": false, + "SVGPathSegLinetoRel": false, + "SVGPathSegLinetoVerticalAbs": false, + "SVGPathSegLinetoVerticalRel": false, + "SVGPathSegList": false, + "SVGPathSegMovetoAbs": false, + "SVGPathSegMovetoRel": false, + "SVGPatternElement": false, + "SVGPoint": false, + "SVGPointList": false, + "SVGPolygonElement": false, + "SVGPolylineElement": false, + "SVGPreserveAspectRatio": false, + "SVGRadialGradientElement": false, + "SVGRect": false, + "SVGRectElement": false, + "SVGRenderingIntent": false, + "SVGScriptElement": false, + "SVGSetElement": false, + "SVGStopElement": false, + "SVGStringList": false, + "SVGStylable": false, + "SVGStyleElement": false, + "SVGSVGElement": false, + "SVGSwitchElement": false, + "SVGSymbolElement": false, + "SVGTests": false, + "SVGTextContentElement": false, + "SVGTextElement": false, + "SVGTextPathElement": false, + "SVGTextPositioningElement": false, + "SVGTitleElement": false, + "SVGTransform": false, + "SVGTransformable": false, + "SVGTransformList": false, + "SVGTRefElement": false, + "SVGTSpanElement": false, + "SVGUnitTypes": false, + "SVGURIReference": false, + "SVGUseElement": false, + "SVGViewElement": false, + "SVGViewSpec": false, + "SVGVKernElement": false, + "SVGZoomAndPan": false, + "SVGZoomEvent": false, + "Text": false, + "TextDecoder": false, + "TextEncoder": false, + "TextEvent": false, + "TextMetrics": false, + "TextTrack": false, + "TextTrackCue": false, + "TextTrackCueList": false, + "TextTrackList": false, + "TimeEvent": false, + "TimeRanges": false, + "toolbar": false, + "top": false, + "Touch": false, + "TouchEvent": false, + "TouchList": false, + "TrackEvent": false, + "TransitionEvent": false, + "TreeWalker": false, + "UIEvent": false, + "URL": false, + "URLSearchParams": false, + "ValidityState": false, + "VTTCue": false, + "WaveShaperNode": false, + "WebGLActiveInfo": false, + "WebGLBuffer": false, + "WebGLContextEvent": false, + "WebGLFramebuffer": false, + "WebGLProgram": false, + "WebGLRenderbuffer": false, + "WebGLRenderingContext": false, + "WebGLShader": false, + "WebGLShaderPrecisionFormat": false, + "WebGLTexture": false, + "WebGLUniformLocation": false, + "WebSocket": false, + "WheelEvent": false, + "window": false, + "Window": false, + "Worker": false, + "XDomainRequest": false, + "XMLDocument": false, + "XMLHttpRequest": false, + "XMLHttpRequestEventTarget": false, + "XMLHttpRequestProgressEvent": false, + "XMLHttpRequestUpload": false, + "XMLSerializer": false, + "XPathEvaluator": false, + "XPathException": false, + "XPathExpression": false, + "XPathNamespace": false, + "XPathNSResolver": false, + "XPathResult": false, + "XSLTProcessor": false + }, + "worker": { + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Cache": false, + "caches": false, + "clearInterval": false, + "clearTimeout": false, + "close": true, + "console": false, + "fetch": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": true, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onlanguagechange": true, + "onmessage": true, + "onoffline": true, + "ononline": true, + "onrejectionhandled": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "Request": false, + "Response": false, + "self": true, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "TextDecoder": false, + "TextEncoder": false, + "URL": false, + "URLSearchParams": false, + "WebSocket": false, + "Worker": false, + "XMLHttpRequest": false + }, + "node": { + "__dirname": false, + "__filename": false, + "arguments": false, + "Buffer": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "console": false, + "exports": true, + "GLOBAL": false, + "global": false, + "Intl": false, + "module": false, + "process": false, + "require": false, + "root": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false + }, + "commonjs": { + "exports": true, + "module": false, + "require": false, + "global": false + }, + "amd": { + "define": false, + "require": false + }, + "mocha": { + "after": false, + "afterEach": false, + "before": false, + "beforeEach": false, + "context": false, + "describe": false, + "it": false, + "mocha": false, + "run": false, + "setup": false, + "specify": false, + "suite": false, + "suiteSetup": false, + "suiteTeardown": false, + "teardown": false, + "test": false, + "xcontext": false, + "xdescribe": false, + "xit": false, + "xspecify": false + }, + "jasmine": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "fail": false, + "fdescribe": false, + "fit": false, + "it": false, + "jasmine": false, + "pending": false, + "runs": false, + "spyOn": false, + "spyOnProperty": false, + "waits": false, + "waitsFor": false, + "xdescribe": false, + "xit": false + }, + "jest": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "check": false, + "describe": false, + "expect": false, + "gen": false, + "it": false, + "fdescribe": false, + "fit": false, + "jest": false, + "pit": false, + "require": false, + "test": false, + "xdescribe": false, + "xit": false, + "xtest": false + }, + "qunit": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notOk": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + }, + "phantomjs": { + "console": true, + "exports": true, + "phantom": true, + "require": true, + "WebPage": true + }, + "couch": { + "emit": false, + "exports": false, + "getRow": false, + "log": false, + "module": false, + "provides": false, + "require": false, + "respond": false, + "send": false, + "start": false, + "sum": false + }, + "rhino": { + "defineClass": false, + "deserialize": false, + "gc": false, + "help": false, + "importClass": false, + "importPackage": false, + "java": false, + "load": false, + "loadClass": false, + "Packages": false, + "print": false, + "quit": false, + "readFile": false, + "readUrl": false, + "runCommand": false, + "seal": false, + "serialize": false, + "spawn": false, + "sync": false, + "toint32": false, + "version": false + }, + "nashorn": { + "__DIR__": false, + "__FILE__": false, + "__LINE__": false, + "com": false, + "edu": false, + "exit": false, + "Java": false, + "java": false, + "javafx": false, + "JavaImporter": false, + "javax": false, + "JSAdapter": false, + "load": false, + "loadWithNewGlobal": false, + "org": false, + "Packages": false, + "print": false, + "quit": false + }, + "wsh": { + "ActiveXObject": true, + "Enumerator": true, + "GetObject": true, + "ScriptEngine": true, + "ScriptEngineBuildVersion": true, + "ScriptEngineMajorVersion": true, + "ScriptEngineMinorVersion": true, + "VBArray": true, + "WScript": true, + "WSH": true, + "XDomainRequest": true + }, + "jquery": { + "$": false, + "jQuery": false + }, + "yui": { + "Y": false, + "YUI": false, + "YUI_config": false + }, + "shelljs": { + "cat": false, + "cd": false, + "chmod": false, + "config": false, + "cp": false, + "dirs": false, + "echo": false, + "env": false, + "error": false, + "exec": false, + "exit": false, + "find": false, + "grep": false, + "ls": false, + "ln": false, + "mkdir": false, + "mv": false, + "popd": false, + "pushd": false, + "pwd": false, + "rm": false, + "sed": false, + "set": false, + "target": false, + "tempdir": false, + "test": false, + "touch": false, + "which": false + }, + "prototypejs": { + "$": false, + "$$": false, + "$A": false, + "$break": false, + "$continue": false, + "$F": false, + "$H": false, + "$R": false, + "$w": false, + "Abstract": false, + "Ajax": false, + "Autocompleter": false, + "Builder": false, + "Class": false, + "Control": false, + "Draggable": false, + "Draggables": false, + "Droppables": false, + "Effect": false, + "Element": false, + "Enumerable": false, + "Event": false, + "Field": false, + "Form": false, + "Hash": false, + "Insertion": false, + "ObjectRange": false, + "PeriodicalExecuter": false, + "Position": false, + "Prototype": false, + "Scriptaculous": false, + "Selector": false, + "Sortable": false, + "SortableObserver": false, + "Sound": false, + "Template": false, + "Toggle": false, + "Try": false + }, + "meteor": { + "$": false, + "_": false, + "Accounts": false, + "AccountsClient": false, + "AccountsServer": false, + "AccountsCommon": false, + "App": false, + "Assets": false, + "Blaze": false, + "check": false, + "Cordova": false, + "DDP": false, + "DDPServer": false, + "DDPRateLimiter": false, + "Deps": false, + "EJSON": false, + "Email": false, + "HTTP": false, + "Log": false, + "Match": false, + "Meteor": false, + "Mongo": false, + "MongoInternals": false, + "Npm": false, + "Package": false, + "Plugin": false, + "process": false, + "Random": false, + "ReactiveDict": false, + "ReactiveVar": false, + "Router": false, + "ServiceConfiguration": false, + "Session": false, + "share": false, + "Spacebars": false, + "Template": false, + "Tinytest": false, + "Tracker": false, + "UI": false, + "Utils": false, + "WebApp": false, + "WebAppInternals": false + }, + "mongo": { + "_isWindows": false, + "_rand": false, + "BulkWriteResult": false, + "cat": false, + "cd": false, + "connect": false, + "db": false, + "getHostName": false, + "getMemInfo": false, + "hostname": false, + "ISODate": false, + "listFiles": false, + "load": false, + "ls": false, + "md5sumFile": false, + "mkdir": false, + "Mongo": false, + "NumberInt": false, + "NumberLong": false, + "ObjectId": false, + "PlanCache": false, + "print": false, + "printjson": false, + "pwd": false, + "quit": false, + "removeFile": false, + "rs": false, + "sh": false, + "UUID": false, + "version": false, + "WriteResult": false + }, + "applescript": { + "$": false, + "Application": false, + "Automation": false, + "console": false, + "delay": false, + "Library": false, + "ObjC": false, + "ObjectSpecifier": false, + "Path": false, + "Progress": false, + "Ref": false + }, + "serviceworker": { + "caches": false, + "Cache": false, + "CacheStorage": false, + "Client": false, + "clients": false, + "Clients": false, + "ExtendableEvent": false, + "ExtendableMessageEvent": false, + "FetchEvent": false, + "importScripts": false, + "registration": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerGlobalScope": false, + "ServiceWorkerMessageEvent": false, + "ServiceWorkerRegistration": false, + "skipWaiting": false, + "WindowClient": false + }, + "atomtest": { + "advanceClock": false, + "fakeClearInterval": false, + "fakeClearTimeout": false, + "fakeSetInterval": false, + "fakeSetTimeout": false, + "resetTimeouts": false, + "waitsForPromise": false + }, + "embertest": { + "andThen": false, + "click": false, + "currentPath": false, + "currentRouteName": false, + "currentURL": false, + "fillIn": false, + "find": false, + "findWithAssert": false, + "keyEvent": false, + "pauseTest": false, + "resumeTest": false, + "triggerEvent": false, + "visit": false + }, + "protractor": { + "$": false, + "$$": false, + "browser": false, + "By": false, + "by": false, + "DartObject": false, + "element": false, + "protractor": false + }, + "shared-node-browser": { + "clearInterval": false, + "clearTimeout": false, + "console": false, + "setInterval": false, + "setTimeout": false + }, + "webextensions": { + "browser": false, + "chrome": false, + "opr": false + }, + "greasemonkey": { + "GM_addStyle": false, + "GM_deleteValue": false, + "GM_getResourceText": false, + "GM_getResourceURL": false, + "GM_getValue": false, + "GM_info": false, + "GM_listValues": false, + "GM_log": false, + "GM_openInTab": false, + "GM_registerMenuCommand": false, + "GM_setClipboard": false, + "GM_setValue": false, + "GM_xmlhttpRequest": false, + "unsafeWindow": false + } } -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +},{}],320:[function(require,module,exports){ +module.exports = require('./globals.json'); - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } +},{"./globals.json":319}],321:[function(require,module,exports){ +'use strict'; +var ansiRegex = require('ansi-regex'); +var re = new RegExp(ansiRegex().source); // remove the `g` flag +module.exports = re.test.bind(re); - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] +},{"ansi-regex":40}],322:[function(require,module,exports){ +(function (process){ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) +'use strict'; - nlLast += nlAfter +/** + * Use invariant() to assert state which your program assumes to be true. + * + * Provide sprintf-style format (only %s is supported) and arguments + * to provide information about what broke and what you were + * expecting. + * + * The invariant message will be stripped in production, but the invariant + * will remain to ensure logic does not differ in production. + */ - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') +var invariant = function(condition, format, a, b, c, d, e, f) { + if (process.env.NODE_ENV !== 'production') { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); } - nlAfter = cleanAfter + } - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; } +}; - if (addPatternStart) { - re = patternStart + re - } +module.exports = invariant; - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } +}).call(this,require('_process')) +},{"_process":15}],323:[function(require,module,exports){ +'use strict'; +var numberIsNan = require('number-is-nan'); - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } +module.exports = Number.isFinite || function (val) { + return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity); +}; - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } +},{"number-is-nan":546}],324:[function(require,module,exports){ +// Copyright 2014, 2015, 2016, 2017 Simon Lydell +// License: MIT. (See LICENSE.) - regExp._glob = pattern - regExp._src = re +Object.defineProperty(exports, "__esModule", { + value: true +}) - return regExp -} +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0]} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token } -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +},{}],325:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/jsesc v1.3.0 by @mathias */ +;(function(root) { - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set + // Detect free variables `exports` + var freeExports = typeof exports == 'object' && exports; - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options + // Detect free variable `module` + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + // Detect free variable `global`, from Node.js or Browserified code, + // and use it as `root` + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + /*--------------------------------------------------------------------------*/ - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + var forOwn = function(object, callback) { + var key; + for (key in object) { + if (hasOwnProperty.call(object, key)) { + callback(key, object[key]); + } + } + }; - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' + var extend = function(destination, source) { + if (!source) { + return destination; + } + forOwn(source, function(key, value) { + destination[key] = value; + }); + return destination; + }; - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} + var forEach = function(array, callback) { + var length = array.length; + var index = -1; + while (++index < length) { + callback(array[index]); + } + }; -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} + var toString = object.toString; + var isArray = function(value) { + return toString.call(value) == '[object Array]'; + }; + var isObject = function(value) { + // This is a very simple check, but it’s good enough for what we need. + return toString.call(value) == '[object Object]'; + }; + var isString = function(value) { + return typeof value == 'string' || + toString.call(value) == '[object String]'; + }; + var isNumber = function(value) { + return typeof value == 'number' || + toString.call(value) == '[object Number]'; + }; + var isFunction = function(value) { + // In a perfect world, the `typeof` check would be sufficient. However, + // in Chrome 1–12, `typeof /x/ == 'object'`, and in IE 6–8 + // `typeof alert == 'object'` and similar for other host objects. + return typeof value == 'function' || + toString.call(value) == '[object Function]'; + }; + var isMap = function(value) { + return toString.call(value) == '[object Map]'; + }; + var isSet = function(value) { + return toString.call(value) == '[object Set]'; + }; -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' + /*--------------------------------------------------------------------------*/ - if (f === '/' && partial) return true + // https://mathiasbynens.be/notes/javascript-escapes#single + var singleEscapes = { + '"': '\\"', + '\'': '\\\'', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t' + // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'. + // '\v': '\\x0B' + }; + var regexSingleEscape = /["'\\\b\f\n\r\t]/; - var options = this.options + var regexDigit = /[0-9]/; + var regexWhitelist = /[ !#-&\(-\[\]-~]/; - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + var jsesc = function(argument, options) { + // Handle options + var defaults = { + 'escapeEverything': false, + 'escapeEtago': false, + 'quotes': 'single', + 'wrap': false, + 'es6': false, + 'json': false, + 'compact': true, + 'lowercaseHex': false, + 'numbers': 'decimal', + 'indent': '\t', + '__indent__': '', + '__inline1__': false, + '__inline2__': false + }; + var json = options && options.json; + if (json) { + defaults.quotes = 'double'; + defaults.wrap = true; + } + options = extend(defaults, options); + if (options.quotes != 'single' && options.quotes != 'double') { + options.quotes = 'single'; + } + var quote = options.quotes == 'double' ? '"' : '\''; + var compact = options.compact; + var indent = options.indent; + var lowercaseHex = options.lowercaseHex; + var oldIndent = ''; + var inline1 = options.__inline1__; + var inline2 = options.__inline2__; + var newLine = compact ? '' : '\n'; + var result; + var isEmpty = true; + var useBinNumbers = options.numbers == 'binary'; + var useOctNumbers = options.numbers == 'octal'; + var useDecNumbers = options.numbers == 'decimal'; + var useHexNumbers = options.numbers == 'hexadecimal'; - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) + if (json && argument && isFunction(argument.toJSON)) { + argument = argument.toJSON(); + } - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + if (!isString(argument)) { + if (isMap(argument)) { + if (argument.size == 0) { + return 'new Map()'; + } + if (!compact) { + options.__inline1__ = true; + } + return 'new Map(' + jsesc(Array.from(argument), options) + ')'; + } + if (isSet(argument)) { + if (argument.size == 0) { + return 'new Set()'; + } + return 'new Set(' + jsesc(Array.from(argument), options) + ')'; + } + if (isArray(argument)) { + result = []; + options.wrap = true; + if (inline1) { + options.__inline1__ = false; + options.__inline2__ = true; + } else { + oldIndent = options.__indent__; + indent += oldIndent; + options.__indent__ = indent; + } + forEach(argument, function(value) { + isEmpty = false; + if (inline2) { + options.__inline2__ = false; + } + result.push( + (compact || inline2 ? '' : indent) + + jsesc(value, options) + ); + }); + if (isEmpty) { + return '[]'; + } + if (inline2) { + return '[' + result.join(', ') + ']'; + } + return '[' + newLine + result.join(',' + newLine) + newLine + + (compact ? '' : oldIndent) + ']'; + } else if (isNumber(argument)) { + if (json) { + // Some number values (e.g. `Infinity`) cannot be represented in JSON. + return JSON.stringify(argument); + } + if (useDecNumbers) { + return String(argument); + } + if (useHexNumbers) { + var tmp = argument.toString(16); + if (!lowercaseHex) { + tmp = tmp.toUpperCase(); + } + return '0x' + tmp; + } + if (useBinNumbers) { + return '0b' + argument.toString(2); + } + if (useOctNumbers) { + return '0o' + argument.toString(8); + } + } else if (!isObject(argument)) { + if (json) { + // For some values (e.g. `undefined`, `function` objects), + // `JSON.stringify(value)` returns `undefined` (which isn’t valid + // JSON) instead of `'null'`. + return JSON.stringify(argument) || 'null'; + } + return String(argument); + } else { // it’s an object + result = []; + options.wrap = true; + oldIndent = options.__indent__; + indent += oldIndent; + options.__indent__ = indent; + forOwn(argument, function(key, value) { + isEmpty = false; + result.push( + (compact ? '' : indent) + + jsesc(key, options) + ':' + + (compact ? '' : ' ') + + jsesc(value, options) + ); + }); + if (isEmpty) { + return '{}'; + } + return '{' + newLine + result.join(',' + newLine) + newLine + + (compact ? '' : oldIndent) + '}'; + } + } - var set = this.set - this.debug(this.pattern, 'set', set) + var string = argument; + // Loop over each code unit in the string and escape it + var index = -1; + var length = string.length; + var first; + var second; + var codePoint; + result = ''; + while (++index < length) { + var character = string.charAt(index); + if (options.es6) { + first = string.charCodeAt(index); + if ( // check if it’s the start of a surrogate pair + first >= 0xD800 && first <= 0xDBFF && // high surrogate + length > index + 1 // there is a next code unit + ) { + second = string.charCodeAt(index + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + var hexadecimal = codePoint.toString(16); + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + result += '\\u{' + hexadecimal + '}'; + index++; + continue; + } + } + } + if (!options.escapeEverything) { + if (regexWhitelist.test(character)) { + // It’s a printable ASCII character that is not `"`, `'` or `\`, + // so don’t escape it. + result += character; + continue; + } + if (character == '"') { + result += quote == character ? '\\"' : character; + continue; + } + if (character == '\'') { + result += quote == character ? '\\\'' : character; + continue; + } + } + if ( + character == '\0' && + !json && + !regexDigit.test(string.charAt(index + 1)) + ) { + result += '\\0'; + continue; + } + if (regexSingleEscape.test(character)) { + // no need for a `hasOwnProperty` check here + result += singleEscapes[character]; + continue; + } + var charCode = character.charCodeAt(0); + var hexadecimal = charCode.toString(16); + if (!lowercaseHex) { + hexadecimal = hexadecimal.toUpperCase(); + } + var longhand = hexadecimal.length > 2 || json; + var escaped = '\\' + (longhand ? 'u' : 'x') + + ('0000' + hexadecimal).slice(longhand ? -4 : -2); + result += escaped; + continue; + } + if (options.wrap) { + result = quote + result + quote; + } + if (options.escapeEtago) { + // https://mathiasbynens.be/notes/etago + return result.replace(/<\/(script|style)/gi, '<\\/$1'); + } + return result; + }; - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + jsesc.version = '1.3.0'; - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } + /*--------------------------------------------------------------------------*/ + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return jsesc; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = jsesc; + } else { // in Narwhal or RingoJS v0.7.0- + freeExports.jsesc = jsesc; + } + } else { // in Rhino or a web browser + root.jsesc = jsesc; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],326:[function(require,module,exports){ +// json5.js +// Modern JSON. See README.md for details. +// +// This file is based directly off of Douglas Crockford's json_parse.js: +// https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js + +var JSON5 = (typeof exports === 'object' ? exports : {}); - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} +JSON5.parse = (function () { + "use strict"; -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options +// This is a function that can parse a JSON5 text, producing a JavaScript +// data structure. It is a simple, recursive descent parser. It does not use +// eval or regular expressions, so it can be used as a model for implementing +// a JSON5 parser in other languages. - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +// We are defining the function inside of another function to avoid creating +// global variables. - this.debug('matchOne', file.length, pattern.length) + var at, // The index of the current character + lineNumber, // The current line number + columnNumber, // The current column number + ch, // The current character + escapee = { + "'": "'", + '"': '"', + '\\': '\\', + '/': '/', + '\n': '', // Replace escaped newlines in strings w/ empty string + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }, + ws = [ + ' ', + '\t', + '\r', + '\n', + '\v', + '\f', + '\xA0', + '\uFEFF' + ], + text, - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] + renderChar = function (chr) { + return chr === '' ? 'EOF' : "'" + chr + "'"; + }, - this.debug(pattern, p, f) + error = function (m) { - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false +// Call error when something is wrong. - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) + var error = new SyntaxError(); + // beginning of message suffix to agree with that provided by Gecko - see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse + error.message = m + " at line " + lineNumber + " column " + columnNumber + " of the JSON5 data. Still to read: " + JSON.stringify(text.substring(at - 1, at + 19)); + error.at = at; + // These two property names have been chosen to agree with the ones in Gecko, the only popular + // environment which seems to supply this info on JSON.parse + error.lineNumber = lineNumber; + error.columnNumber = columnNumber; + throw error; + }, - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } + next = function (c) { - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] +// If a c parameter is provided, verify that it matches the current character. - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + if (c && c !== ch) { + error("Expected " + renderChar(c) + " instead of " + renderChar(ch)); + } - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } +// Get the next character. When there are no more characters, +// return the empty string. - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + ch = text.charAt(at); + at++; + columnNumber++; + if (ch === '\n' || ch === '\r' && peek() !== '\n') { + lineNumber++; + columnNumber = 0; + } + return ch; + }, - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } + peek = function () { - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } +// Get the next character without consuming it or +// assigning it to the ch varaible. - if (!hit) return false - } + return text.charAt(at); + }, - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* + identifier = function () { - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } +// Parse an identifier. Normally, reserved words are disallowed here, but we +// only use this for unquoted object keys, where reserved words are allowed, +// so we don't check for those here. References: +// - http://es5.github.com/#x7.6 +// - https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Variables +// - http://docstore.mik.ua/orelly/webprog/jscript/ch02_07.htm +// TODO Identifiers can have Unicode "letters" in them; add support for those. - // should be unreachable. - throw new Error('wtf?') -} + var key = ch; -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} + // Identifiers must start with a letter, _ or $. + if ((ch !== '_' && ch !== '$') && + (ch < 'a' || ch > 'z') && + (ch < 'A' || ch > 'Z')) { + error("Bad identifier as unquoted key"); + } -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} + // Subsequent characters can contain digits. + while (next() && ( + ch === '_' || ch === '$' || + (ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9'))) { + key += ch; + } -},{"brace-expansion":151,"path":801}],507:[function(require,module,exports){ -/** - * Helpers. - */ + return key; + }, -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; + number = function () { -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +// Parse a number value. -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; + var number, + sign = '', + string = '', + base = 10; -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + if (ch === '-' || ch === '+') { + sign = ch; + next(ch); + } -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} + // support for Infinity (could tweak to allow other words): + if (ch === 'I') { + number = word(); + if (typeof number !== 'number' || isNaN(number)) { + error('Unexpected word for number'); + } + return (sign === '-') ? -number : number; + } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + // support for NaN + if (ch === 'N' ) { + number = word(); + if (!isNaN(number)) { + error('expected word to be NaN'); + } + // ignore sign as -NaN also is NaN + return number; + } -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} + if (ch === '0') { + string += ch; + next(); + if (ch === 'x' || ch === 'X') { + string += ch; + next(); + base = 16; + } else if (ch >= '0' && ch <= '9') { + error('Octal literal'); + } + } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + switch (base) { + case 10: + while (ch >= '0' && ch <= '9' ) { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + break; + case 16: + while (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') { + string += ch; + next(); + } + break; + } -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} + if(sign === '-') { + number = -string; + } else { + number = +string; + } -/** - * Pluralization helper. - */ + if (!isFinite(number)) { + error("Bad number"); + } else { + return number; + } + }, -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + string = function () { -},{}],508:[function(require,module,exports){ -'use strict'; -module.exports = Number.isNaN || function (x) { - return x !== x; -}; +// Parse a string value. + + var hex, + i, + string = '', + delim, // double quote or single quote + uffff; + +// When parsing for string values, we must look for ' or " and \ characters. + + if (ch === '"' || ch === "'") { + delim = ch; + while (next()) { + if (ch === delim) { + next(); + return string; + } else if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (ch === '\r') { + if (peek() === '\n') { + next(); + } + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else if (ch === '\n') { + // unescaped newlines are invalid; see: + // https://github.com/aseemk/json5/issues/24 + // TODO this feels special-cased; are there other + // invalid unescaped chars? + break; + } else { + string += ch; + } + } + } + error("Bad string"); + }, -},{}],509:[function(require,module,exports){ -(function (process){ -'use strict'; + inlineComment = function () { -function posix(path) { - return path.charAt(0) === '/'; -} +// Skip an inline comment, assuming this is one. The current character should +// be the second / character in the // pair that begins this inline comment. +// To finish the inline comment, we look for a newline or the end of the text. -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); + if (ch !== '/') { + error("Not an inline comment"); + } - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} + do { + next(); + if (ch === '\n' || ch === '\r') { + next(); + return; + } + } while (ch); + }, -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; + blockComment = function () { -}).call(this,require('_process')) -},{"_process":803}],510:[function(require,module,exports){ -"use strict"; +// Skip a block comment, assuming this is one. The current character should be +// the * character in the /* pair that begins this block comment. +// To finish the block comment, we look for an ending */ pair of characters, +// but we also watch for the end of text before the comment is terminated. -var originalObject = Object; -var originalDefProp = Object.defineProperty; -var originalCreate = Object.create; + if (ch !== '*') { + error("Not a block comment"); + } -function defProp(obj, name, value) { - if (originalDefProp) try { - originalDefProp.call(originalObject, obj, name, { value: value }); - } catch (definePropertyIsBrokenInIE8) { - obj[name] = value; - } else { - obj[name] = value; - } -} + do { + next(); + while (ch === '*') { + next('*'); + if (ch === '/') { + next('/'); + return; + } + } + } while (ch); -// For functions that will be invoked using .call or .apply, we need to -// define those methods on the function objects themselves, rather than -// inheriting them from Function.prototype, so that a malicious or clumsy -// third party cannot interfere with the functionality of this module by -// redefining Function.prototype.call or .apply. -function makeSafeToCall(fun) { - if (fun) { - defProp(fun, "call", fun.call); - defProp(fun, "apply", fun.apply); - } - return fun; -} + error("Unterminated block comment"); + }, -makeSafeToCall(originalDefProp); -makeSafeToCall(originalCreate); + comment = function () { -var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); -var numToStr = makeSafeToCall(Number.prototype.toString); -var strSlice = makeSafeToCall(String.prototype.slice); +// Skip a comment, whether inline or block-level, assuming this is one. +// Comments always begin with a / character. -var cloner = function(){}; -function create(prototype) { - if (originalCreate) { - return originalCreate.call(originalObject, prototype); - } - cloner.prototype = prototype || null; - return new cloner; -} + if (ch !== '/') { + error("Not a comment"); + } -var rand = Math.random; -var uniqueKeys = create(null); + next('/'); -function makeUniqueKey() { - // Collisions are highly unlikely, but this module is in the business of - // making guarantees rather than safe bets. - do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); - while (hasOwn.call(uniqueKeys, uniqueKey)); - return uniqueKeys[uniqueKey] = uniqueKey; -} + if (ch === '/') { + inlineComment(); + } else if (ch === '*') { + blockComment(); + } else { + error("Unrecognized comment"); + } + }, -function internString(str) { - var obj = {}; - obj[str] = true; - return Object.keys(obj)[0]; -} + white = function () { -// External users might find this function useful, but it is not necessary -// for the typical use of this module. -exports.makeUniqueKey = makeUniqueKey; +// Skip whitespace and comments. +// Note that we're detecting comments by only a single / character. +// This works since regular expressions are not valid JSON(5), but this will +// break if there are other valid values that begin with a / character! -// Object.getOwnPropertyNames is the only way to enumerate non-enumerable -// properties, so if we wrap it to ignore our secret keys, there should be -// no way (except guessing) to access those properties. -var originalGetOPNs = Object.getOwnPropertyNames; -Object.getOwnPropertyNames = function getOwnPropertyNames(object) { - for (var names = originalGetOPNs(object), - src = 0, - dst = 0, - len = names.length; - src < len; - ++src) { - if (!hasOwn.call(uniqueKeys, names[src])) { - if (src > dst) { - names[dst] = names[src]; - } - ++dst; - } - } - names.length = dst; - return names; -}; + while (ch) { + if (ch === '/') { + comment(); + } else if (ws.indexOf(ch) >= 0) { + next(); + } else { + return; + } + } + }, -function defaultCreatorFn(object) { - return create(null); -} + word = function () { -function makeAccessor(secretCreatorFn) { - var brand = makeUniqueKey(); - var passkey = create(null); +// true, false, or null. - secretCreatorFn = secretCreatorFn || defaultCreatorFn; + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + case 'I': + next('I'); + next('n'); + next('f'); + next('i'); + next('n'); + next('i'); + next('t'); + next('y'); + return Infinity; + case 'N': + next( 'N' ); + next( 'a' ); + next( 'N' ); + return NaN; + } + error("Unexpected " + renderChar(ch)); + }, - function register(object) { - var secret; // Created lazily. + value, // Place holder for the value function. - function vault(key, forget) { - // Only code that has access to the passkey can retrieve (or forget) - // the secret object. - if (key === passkey) { - return forget - ? secret = null - : secret || (secret = secretCreatorFn(object)); - } - } + array = function () { - defProp(object, brand, vault); - } +// Parse an array value. - function accessor(object) { - if (!hasOwn.call(object, brand)) - register(object); - return object[brand](passkey); - } + var array = []; - accessor.forget = function(object) { - if (hasOwn.call(object, brand)) - object[brand](passkey, true); - }; + if (ch === '[') { + next('['); + white(); + while (ch) { + if (ch === ']') { + next(']'); + return array; // Potentially empty array + } + // ES5 allows omitting elements in arrays, e.g. [,] and + // [,null]. We don't allow this in JSON5. + if (ch === ',') { + error("Missing array element"); + } else { + array.push(value()); + } + white(); + // If there's no comma after this value, this needs to + // be the end of the array. + if (ch !== ',') { + next(']'); + return array; + } + next(','); + white(); + } + } + error("Bad array"); + }, - return accessor; -} + object = function () { -exports.makeAccessor = makeAccessor; +// Parse an object value. -},{}],511:[function(require,module,exports){ -var assert = require("assert"); -var types = require("./types"); -var n = types.namedTypes; -var isArray = types.builtInTypes.array; -var isObject = types.builtInTypes.object; -var linesModule = require("./lines"); -var fromString = linesModule.fromString; -var Lines = linesModule.Lines; -var concat = linesModule.concat; -var util = require("./util"); -var comparePos = util.comparePos; -var childNodesCacheKey = require("private").makeUniqueKey(); + var key, + object = {}; -// TODO Move a non-caching implementation of this function into ast-types, -// and implement a caching wrapper function here. -function getSortedChildNodes(node, lines, resultArray) { - if (!node) { - return; - } + if (ch === '{') { + next('{'); + white(); + while (ch) { + if (ch === '}') { + next('}'); + return object; // Potentially empty object + } - // The .loc checks below are sensitive to some of the problems that - // are fixed by this utility function. Specifically, if it decides to - // set node.loc to null, indicating that the node's .loc information - // is unreliable, then we don't want to add node to the resultArray. - util.fixFaultyLocations(node, lines); + // Keys can be unquoted. If they are, they need to be + // valid JS identifiers. + if (ch === '"' || ch === "'") { + key = string(); + } else { + key = identifier(); + } - if (resultArray) { - if (n.Node.check(node) && - n.SourceLocation.check(node.loc)) { - // This reverse insertion sort almost always takes constant - // time because we almost always (maybe always?) append the - // nodes in order anyway. - for (var i = resultArray.length - 1; i >= 0; --i) { - if (comparePos(resultArray[i].loc.end, - node.loc.start) <= 0) { - break; + white(); + next(':'); + object[key] = value(); + white(); + // If there's no comma after this pair, this needs to be + // the end of the object. + if (ch !== ',') { + next('}'); + return object; + } + next(','); + white(); } } - resultArray.splice(i + 1, 0, node); - return; - } - } else if (node[childNodesCacheKey]) { - return node[childNodesCacheKey]; - } - - var names; - if (isArray.check(node)) { - names = Object.keys(node); - } else if (isObject.check(node)) { - names = types.getFieldNames(node); - } else { - return; - } - - if (!resultArray) { - Object.defineProperty(node, childNodesCacheKey, { - value: resultArray = [], - enumerable: false - }); - } - - for (var i = 0, nameCount = names.length; i < nameCount; ++i) { - getSortedChildNodes(node[names[i]], lines, resultArray); - } - - return resultArray; -} + error("Bad object"); + }; -// As efficiently as possible, decorate the comment object with -// .precedingNode, .enclosingNode, and/or .followingNode properties, at -// least one of which is guaranteed to be defined. -function decorateComment(node, comment, lines) { - var childNodes = getSortedChildNodes(node, lines); + value = function () { - // Time to dust off the old binary search robes and wizard hat. - var left = 0, right = childNodes.length; - while (left < right) { - var middle = (left + right) >> 1; - var child = childNodes[middle]; +// Parse a JSON value. It could be an object, an array, a string, a number, +// or a word. - if (comparePos(child.loc.start, comment.loc.start) <= 0 && - comparePos(comment.loc.end, child.loc.end) <= 0) { - // The comment is completely contained by this child node. - decorateComment(comment.enclosingNode = child, comment, lines); - return; // Abandon the binary search at this level. + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + case "'": + return string(); + case '-': + case '+': + case '.': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); } + }; - if (comparePos(child.loc.end, comment.loc.start) <= 0) { - // This child node falls completely before the comment. - // Because we will never consider this node or any nodes - // before it again, this node must be the closest preceding - // node we have encountered so far. - var precedingNode = child; - left = middle + 1; - continue; - } +// Return the json_parse function. It will have access to all of the above +// functions and variables. - if (comparePos(comment.loc.end, child.loc.start) <= 0) { - // This child node falls completely after the comment. - // Because we will never consider this node or any nodes after - // it again, this node must be the closest following node we - // have encountered so far. - var followingNode = child; - right = middle; - continue; - } + return function (source, reviver) { + var result; - throw new Error("Comment location overlaps with node location"); - } + text = String(source); + at = 0; + lineNumber = 1; + columnNumber = 1; + ch = ' '; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } - if (precedingNode) { - comment.precedingNode = precedingNode; - } +// If there is a reviver function, we recursively walk the new structure, +// passing each name/value pair to the reviver function for possible +// transformation, starting with a temporary root object that holds the result +// in an empty key. If there is not a reviver function, we simply return the +// result. - if (followingNode) { - comment.followingNode = followingNode; - } -} + return typeof reviver === 'function' ? (function walk(holder, key) { + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + }({'': result}, '')) : result; + }; +}()); -exports.attach = function(comments, ast, lines) { - if (!isArray.check(comments)) { - return; +// JSON5 stringify will not quote keys where appropriate +JSON5.stringify = function (obj, replacer, space) { + if (replacer && (typeof(replacer) !== "function" && !isArray(replacer))) { + throw new Error('Replacer must be a function or an array'); } + var getReplacedValueOrUndefined = function(holder, key, isTopLevel) { + var value = holder[key]; - var tiesToBreak = []; - - comments.forEach(function(comment) { - comment.loc.lines = lines; - decorateComment(ast, comment, lines); - - var pn = comment.precedingNode; - var en = comment.enclosingNode; - var fn = comment.followingNode; - - if (pn && fn) { - var tieCount = tiesToBreak.length; - if (tieCount > 0) { - var lastTie = tiesToBreak[tieCount - 1]; - - assert.strictEqual( - lastTie.precedingNode === comment.precedingNode, - lastTie.followingNode === comment.followingNode - ); + // Replace the value with its toJSON value first, if possible + if (value && value.toJSON && typeof value.toJSON === "function") { + value = value.toJSON(); + } - if (lastTie.followingNode !== comment.followingNode) { - breakTies(tiesToBreak, lines); - } + // If the user-supplied replacer if a function, call it. If it's an array, check objects' string keys for + // presence in the array (removing the key/value pair from the resulting JSON if the key is missing). + if (typeof(replacer) === "function") { + return replacer.call(holder, key, value); + } else if(replacer) { + if (isTopLevel || isArray(holder) || replacer.indexOf(key) >= 0) { + return value; + } else { + return undefined; } + } else { + return value; + } + }; - tiesToBreak.push(comment); + function isWordChar(c) { + return (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c === '_' || c === '$'; + } - } else if (pn) { - // No contest: we have a trailing comment. - breakTies(tiesToBreak, lines); - addTrailingComment(pn, comment); + function isWordStart(c) { + return (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + c === '_' || c === '$'; + } - } else if (fn) { - // No contest: we have a leading comment. - breakTies(tiesToBreak, lines); - addLeadingComment(fn, comment); + function isWord(key) { + if (typeof key !== 'string') { + return false; + } + if (!isWordStart(key[0])) { + return false; + } + var i = 1, length = key.length; + while (i < length) { + if (!isWordChar(key[i])) { + return false; + } + i++; + } + return true; + } - } else if (en) { - // The enclosing node has no child nodes at all, so what we - // have here is a dangling comment, e.g. [/* crickets */]. - breakTies(tiesToBreak, lines); - addDanglingComment(en, comment); + // export for use in tests + JSON5.isWord = isWord; + // polyfills + function isArray(obj) { + if (Array.isArray) { + return Array.isArray(obj); } else { - throw new Error("AST contains no nodes at all?"); + return Object.prototype.toString.call(obj) === '[object Array]'; } - }); - - breakTies(tiesToBreak, lines); - - comments.forEach(function(comment) { - // These node references were useful for breaking ties, but we - // don't need them anymore, and they create cycles in the AST that - // may lead to infinite recursion if we don't delete them here. - delete comment.precedingNode; - delete comment.enclosingNode; - delete comment.followingNode; - }); -}; - -function breakTies(tiesToBreak, lines) { - var tieCount = tiesToBreak.length; - if (tieCount === 0) { - return; } - var pn = tiesToBreak[0].precedingNode; - var fn = tiesToBreak[0].followingNode; - var gapEndPos = fn.loc.start; + function isDate(obj) { + return Object.prototype.toString.call(obj) === '[object Date]'; + } - // Iterate backwards through tiesToBreak, examining the gaps - // between the tied comments. In order to qualify as leading, a - // comment must be separated from fn by an unbroken series of - // whitespace-only gaps (or other comments). - for (var indexOfFirstLeadingComment = tieCount; - indexOfFirstLeadingComment > 0; - --indexOfFirstLeadingComment) { - var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; - assert.strictEqual(comment.precedingNode, pn); - assert.strictEqual(comment.followingNode, fn); + var objStack = []; + function checkForCircular(obj) { + for (var i = 0; i < objStack.length; i++) { + if (objStack[i] === obj) { + throw new TypeError("Converting circular structure to JSON"); + } + } + } - var gap = lines.sliceString(comment.loc.end, gapEndPos); - if (/\S/.test(gap)) { - // The gap string contained something other than whitespace. - break; + function makeIndent(str, num, noNewLine) { + if (!str) { + return ""; + } + // indentation no more than 10 chars + if (str.length > 10) { + str = str.substring(0, 10); } - gapEndPos = comment.loc.start; - } + var indent = noNewLine ? "" : "\n"; + for (var i = 0; i < num; i++) { + indent += str; + } - while (indexOfFirstLeadingComment <= tieCount && - (comment = tiesToBreak[indexOfFirstLeadingComment]) && - // If the comment is a //-style comment and indented more - // deeply than the node itself, reconsider it as trailing. - (comment.type === "Line" || comment.type === "CommentLine") && - comment.loc.start.column > fn.loc.start.column) { - ++indexOfFirstLeadingComment; + return indent; } - tiesToBreak.forEach(function(comment, i) { - if (i < indexOfFirstLeadingComment) { - addTrailingComment(pn, comment); + var indentStr; + if (space) { + if (typeof space === "string") { + indentStr = space; + } else if (typeof space === "number" && space >= 0) { + indentStr = makeIndent(" ", space, true); } else { - addLeadingComment(fn, comment); + // ignore space parameter } - }); - - tiesToBreak.length = 0; -} + } -function addCommentHelper(node, comment) { - var comments = node.comments || (node.comments = []); - comments.push(comment); -} + // Copied from Crokford's implementation of JSON + // See https://github.com/douglascrockford/JSON-js/blob/e39db4b7e6249f04a195e7dd0840e610cc9e941e/json2.js#L195 + // Begin + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }; + function escapeString(string) { -function addLeadingComment(node, comment) { - comment.leading = true; - comment.trailing = false; - addCommentHelper(node, comment); -} +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? + c : + '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + // End -function addDanglingComment(node, comment) { - comment.leading = false; - comment.trailing = false; - addCommentHelper(node, comment); -} + function internalStringify(holder, key, isTopLevel) { + var buffer, res; -function addTrailingComment(node, comment) { - comment.leading = false; - comment.trailing = true; - addCommentHelper(node, comment); -} + // Replace the value, if necessary + var obj_part = getReplacedValueOrUndefined(holder, key, isTopLevel); -function printLeadingComment(commentPath, print) { - var comment = commentPath.getValue(); - n.Comment.assert(comment); + if (obj_part && !isDate(obj_part)) { + // unbox objects + // don't unbox dates, since will turn it into number + obj_part = obj_part.valueOf(); + } + switch(typeof obj_part) { + case "boolean": + return obj_part.toString(); - var loc = comment.loc; - var lines = loc && loc.lines; - var parts = [print(commentPath)]; + case "number": + if (isNaN(obj_part) || !isFinite(obj_part)) { + return "null"; + } + return obj_part.toString(); - if (comment.trailing) { - // When we print trailing comments as leading comments, we don't - // want to bring any trailing spaces along. - parts.push("\n"); + case "string": + return escapeString(obj_part.toString()); - } else if (lines instanceof Lines) { - var trailingSpace = lines.slice( - loc.end, - lines.skipSpaces(loc.end) - ); + case "object": + if (obj_part === null) { + return "null"; + } else if (isArray(obj_part)) { + checkForCircular(obj_part); + buffer = "["; + objStack.push(obj_part); - if (trailingSpace.length === 1) { - // If the trailing space contains no newlines, then we want to - // preserve it exactly as we found it. - parts.push(trailingSpace); - } else { - // If the trailing space contains newlines, then replace it - // with just that many newlines, with all other spaces removed. - parts.push(new Array(trailingSpace.length).join("\n")); + for (var i = 0; i < obj_part.length; i++) { + res = internalStringify(obj_part, i, false); + buffer += makeIndent(indentStr, objStack.length); + if (res === null || typeof res === "undefined") { + buffer += "null"; + } else { + buffer += res; + } + if (i < obj_part.length-1) { + buffer += ","; + } else if (indentStr) { + buffer += "\n"; + } + } + objStack.pop(); + if (obj_part.length) { + buffer += makeIndent(indentStr, objStack.length, true) + } + buffer += "]"; + } else { + checkForCircular(obj_part); + buffer = "{"; + var nonEmpty = false; + objStack.push(obj_part); + for (var prop in obj_part) { + if (obj_part.hasOwnProperty(prop)) { + var value = internalStringify(obj_part, prop, false); + isTopLevel = false; + if (typeof value !== "undefined" && value !== null) { + buffer += makeIndent(indentStr, objStack.length); + nonEmpty = true; + key = isWord(prop) ? prop : escapeString(prop); + buffer += key + ":" + (indentStr ? ' ' : '') + value + ","; + } + } + } + objStack.pop(); + if (nonEmpty) { + buffer = buffer.substring(0, buffer.length-1) + makeIndent(indentStr, objStack.length) + "}"; + } else { + buffer = '{}'; + } + } + return buffer; + default: + // functions and undefined should be ignored + return undefined; } + } - } else { - parts.push("\n"); + // special case...when undefined is used inside of + // a compound object/array, return null. + // but when top-level, return undefined + var topLevelHolder = {"":obj}; + if (obj === undefined) { + return getReplacedValueOrUndefined(topLevelHolder, '', true); } + return internalStringify(topLevelHolder, '', true); +}; - return concat(parts); -} +},{}],327:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); -function printTrailingComment(commentPath, print) { - var comment = commentPath.getValue(commentPath); - n.Comment.assert(comment); +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'); - var loc = comment.loc; - var lines = loc && loc.lines; - var parts = []; +module.exports = DataView; - if (lines instanceof Lines) { - var fromPos = lines.skipSpaces(loc.start, true) || lines.firstPos(); - var leadingSpace = lines.slice(fromPos, loc.start); +},{"./_getNative":431,"./_root":475}],328:[function(require,module,exports){ +var hashClear = require('./_hashClear'), + hashDelete = require('./_hashDelete'), + hashGet = require('./_hashGet'), + hashHas = require('./_hashHas'), + hashSet = require('./_hashSet'); - if (leadingSpace.length === 1) { - // If the leading space contains no newlines, then we want to - // preserve it exactly as we found it. - parts.push(leadingSpace); - } else { - // If the leading space contains newlines, then replace it - // with just that many newlines, sans all other spaces. - parts.push(new Array(leadingSpace.length).join("\n")); - } - } +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - parts.push(print(commentPath)); + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} - return concat(parts); +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +module.exports = Hash; + +},{"./_hashClear":439,"./_hashDelete":440,"./_hashGet":441,"./_hashHas":442,"./_hashSet":443}],329:[function(require,module,exports){ +var listCacheClear = require('./_listCacheClear'), + listCacheDelete = require('./_listCacheDelete'), + listCacheGet = require('./_listCacheGet'), + listCacheHas = require('./_listCacheHas'), + listCacheSet = require('./_listCacheSet'); + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } -exports.printComments = function(path, print) { - var value = path.getValue(); - var innerLines = print(path); - var comments = n.Node.check(value) && - types.getFieldValue(value, "comments"); +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; - if (!comments || comments.length === 0) { - return innerLines; - } +module.exports = ListCache; - var leadingParts = []; - var trailingParts = [innerLines]; +},{"./_listCacheClear":455,"./_listCacheDelete":456,"./_listCacheGet":457,"./_listCacheHas":458,"./_listCacheSet":459}],330:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); - path.each(function(commentPath) { - var comment = commentPath.getValue(); - var leading = types.getFieldValue(comment, "leading"); - var trailing = types.getFieldValue(comment, "trailing"); +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'); - if (leading || (trailing && !(n.Statement.check(value) || - comment.type === "Block" || - comment.type === "CommentBlock"))) { - leadingParts.push(printLeadingComment(commentPath, print)); - } else if (trailing) { - trailingParts.push(printTrailingComment(commentPath, print)); - } - }, "comments"); +module.exports = Map; - leadingParts.push.apply(leadingParts, trailingParts); - return concat(leadingParts); -}; +},{"./_getNative":431,"./_root":475}],331:[function(require,module,exports){ +var mapCacheClear = require('./_mapCacheClear'), + mapCacheDelete = require('./_mapCacheDelete'), + mapCacheGet = require('./_mapCacheGet'), + mapCacheHas = require('./_mapCacheHas'), + mapCacheSet = require('./_mapCacheSet'); -},{"./lines":513,"./types":519,"./util":520,"assert":791,"private":510}],512:[function(require,module,exports){ -var assert = require("assert"); -var types = require("./types"); -var n = types.namedTypes; -var Node = n.Node; -var isArray = types.builtInTypes.array; -var isNumber = types.builtInTypes.number; +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; -function FastPath(value) { - assert.ok(this instanceof FastPath); - this.stack = [value]; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } -var FPp = FastPath.prototype; -module.exports = FastPath; - -// Static convenience function for coercing a value to a FastPath. -FastPath.from = function(obj) { - if (obj instanceof FastPath) { - // Return a defensive copy of any existing FastPath instances. - return obj.copy(); - } +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; - if (obj instanceof types.NodePath) { - // For backwards compatibility, unroll NodePath instances into - // lightweight FastPath [..., name, value] stacks. - var copy = Object.create(FastPath.prototype); - var stack = [obj.value]; - for (var pp; (pp = obj.parentPath); obj = pp) - stack.push(obj.name, pp.value); - copy.stack = stack.reverse(); - return copy; - } +module.exports = MapCache; - // Otherwise use obj as the value of the new FastPath instance. - return new FastPath(obj); -}; +},{"./_mapCacheClear":460,"./_mapCacheDelete":461,"./_mapCacheGet":462,"./_mapCacheHas":463,"./_mapCacheSet":464}],332:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); -FPp.copy = function copy() { - var copy = Object.create(FastPath.prototype); - copy.stack = this.stack.slice(0); - return copy; -}; +/* Built-in method references that are verified to be native. */ +var Promise = getNative(root, 'Promise'); -// The name of the current property is always the penultimate element of -// this.stack, and always a String. -FPp.getName = function getName() { - var s = this.stack; - var len = s.length; - if (len > 1) { - return s[len - 2]; - } - // Since the name is always a string, null is a safe sentinel value to - // return if we do not know the name of the (root) value. - return null; -}; +module.exports = Promise; -// The value of the current property is always the final element of -// this.stack. -FPp.getValue = function getValue() { - var s = this.stack; - return s[s.length - 1]; -}; +},{"./_getNative":431,"./_root":475}],333:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); -function getNodeHelper(path, count) { - var s = path.stack; +/* Built-in method references that are verified to be native. */ +var Set = getNative(root, 'Set'); - for (var i = s.length - 1; i >= 0; i -= 2) { - var value = s[i]; - if (n.Node.check(value) && --count < 0) { - return value; - } - } +module.exports = Set; - return null; -} +},{"./_getNative":431,"./_root":475}],334:[function(require,module,exports){ +var MapCache = require('./_MapCache'), + setCacheAdd = require('./_setCacheAdd'), + setCacheHas = require('./_setCacheHas'); -FPp.getNode = function getNode(count) { - return getNodeHelper(this, ~~count); -}; +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; -FPp.getParentNode = function getParentNode(count) { - return getNodeHelper(this, ~~count + 1); -}; + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} -// The length of the stack can be either even or odd, depending on whether -// or not we have a name for the root value. The difference between the -// index of the root value and the index of the final value is always -// even, though, which allows us to return the root value in constant time -// (i.e. without iterating backwards through the stack). -FPp.getRootValue = function getRootValue() { - var s = this.stack; - if (s.length % 2 === 0) { - return s[1]; - } - return s[0]; -}; +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; -// Temporarily push properties named by string arguments given after the -// callback function onto this.stack, then call the callback with a -// reference to this (modified) FastPath object. Note that the stack will -// be restored to its original state after the callback is finished, so it -// is probably a mistake to retain a reference to the path. -FPp.call = function call(callback/*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } - var result = callback(this); - s.length = origLen; - return result; -}; +module.exports = SetCache; -// Similar to FastPath.prototype.call, except that the value obtained by -// accessing this.getValue()[name1][name2]... should be array-like. The -// callback will be called with a reference to this path object for each -// element of the array. -FPp.each = function each(callback/*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; +},{"./_MapCache":331,"./_setCacheAdd":476,"./_setCacheHas":477}],335:[function(require,module,exports){ +var ListCache = require('./_ListCache'), + stackClear = require('./_stackClear'), + stackDelete = require('./_stackDelete'), + stackGet = require('./_stackGet'), + stackHas = require('./_stackHas'), + stackSet = require('./_stackSet'); - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} - for (var i = 0; i < value.length; ++i) { - if (i in value) { - s.push(i, value[i]); - // If the callback needs to know the value of i, call - // path.getName(), assuming path is the parameter name. - callback(this); - s.length -= 2; - } - } +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; - s.length = origLen; -}; +module.exports = Stack; -// Similar to FastPath.prototype.each, except that the results of the -// callback function invocations are stored in an array and returned at -// the end of the iteration. -FPp.map = function map(callback/*, name1, name2, ... */) { - var s = this.stack; - var origLen = s.length; - var value = s[origLen - 1]; - var argc = arguments.length; +},{"./_ListCache":329,"./_stackClear":481,"./_stackDelete":482,"./_stackGet":483,"./_stackHas":484,"./_stackSet":485}],336:[function(require,module,exports){ +var root = require('./_root'); - for (var i = 1; i < argc; ++i) { - var name = arguments[i]; - value = value[name]; - s.push(name, value); - } +/** Built-in value references. */ +var Symbol = root.Symbol; - var result = new Array(value.length); +module.exports = Symbol; - for (var i = 0; i < value.length; ++i) { - if (i in value) { - s.push(i, value[i]); - result[i] = callback(this, i); - s.length -= 2; - } - } +},{"./_root":475}],337:[function(require,module,exports){ +var root = require('./_root'); - s.length = origLen; +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; - return result; -}; +module.exports = Uint8Array; -// Inspired by require("ast-types").NodePath.prototype.needsParens, but -// more efficient because we're iterating backwards through a stack. -FPp.needsParens = function(assumeExpressionContext) { - var parent = this.getParentNode(); - if (!parent) { - return false; - } +},{"./_root":475}],338:[function(require,module,exports){ +var getNative = require('./_getNative'), + root = require('./_root'); - var name = this.getName(); - var node = this.getNode(); +/* Built-in method references that are verified to be native. */ +var WeakMap = getNative(root, 'WeakMap'); - // If the value of this path is some child of a Node and not a Node - // itself, then it doesn't need parentheses. Only Node objects (in - // fact, only Expression nodes) need parentheses. - if (this.getValue() !== node) { - return false; - } +module.exports = WeakMap; - // Only statements don't need parentheses. - if (n.Statement.check(node)) { - return false; - } +},{"./_getNative":431,"./_root":475}],339:[function(require,module,exports){ +/** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ +function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; +} - // Identifiers never need parentheses. - if (node.type === "Identifier") { - return false; - } +module.exports = addMapEntry; - if (parent.type === "ParenthesizedExpression") { - return false; - } +},{}],340:[function(require,module,exports){ +/** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ +function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; +} - switch (node.type) { - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - return parent.type === "MemberExpression" - && name === "object" - && parent.object === node; +module.exports = addSetEntry; - case "BinaryExpression": - case "LogicalExpression": - switch (parent.type) { - case "CallExpression": - return name === "callee" - && parent.callee === node; +},{}],341:[function(require,module,exports){ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - return true; +module.exports = apply; - case "MemberExpression": - return name === "object" - && parent.object === node; +},{}],342:[function(require,module,exports){ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; - case "BinaryExpression": - case "LogicalExpression": - var po = parent.operator; - var pp = PRECEDENCE[po]; - var no = node.operator; - var np = PRECEDENCE[no]; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} - if (pp > np) { - return true; - } +module.exports = arrayEach; - if (pp === np && name === "right") { - assert.strictEqual(parent.right, node); - return true; - } +},{}],343:[function(require,module,exports){ +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; - default: - return false; - } + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} - case "SequenceExpression": - switch (parent.type) { - case "ReturnStatement": - return false; +module.exports = arrayFilter; - case "ForStatement": - // Although parentheses wouldn't hurt around sequence - // expressions in the head of for loops, traditional style - // dictates that e.g. i++, j++ should not be wrapped with - // parentheses. - return false; +},{}],344:[function(require,module,exports){ +var baseIndexOf = require('./_baseIndexOf'); - case "ExpressionStatement": - return name !== "expression"; +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; +} - default: - // Otherwise err on the side of overparenthesization, adding - // explicit exceptions above if this proves overzealous. - return true; - } +module.exports = arrayIncludes; - case "YieldExpression": - switch (parent.type) { - case "BinaryExpression": - case "LogicalExpression": - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "CallExpression": - case "MemberExpression": - case "NewExpression": - case "ConditionalExpression": - case "YieldExpression": - return true; +},{"./_baseIndexOf":370}],345:[function(require,module,exports){ +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; - default: - return false; - } + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} - case "IntersectionTypeAnnotation": - case "UnionTypeAnnotation": - return parent.type === "NullableTypeAnnotation"; +module.exports = arrayIncludesWith; - case "Literal": - return parent.type === "MemberExpression" - && isNumber.check(node.value) - && name === "object" - && parent.object === node; +},{}],346:[function(require,module,exports){ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isIndex = require('./_isIndex'), + isTypedArray = require('./isTypedArray'); - case "AssignmentExpression": - case "ConditionalExpression": - switch (parent.type) { - case "UnaryExpression": - case "SpreadElement": - case "SpreadProperty": - case "BinaryExpression": - case "LogicalExpression": - return true; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - case "CallExpression": - return name === "callee" - && parent.callee === node; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - case "ConditionalExpression": - return name === "test" - && parent.test === node; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; - case "MemberExpression": - return name === "object" - && parent.object === node; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} - default: - return false; - } +module.exports = arrayLikeKeys; - case "ArrowFunctionExpression": - if(n.CallExpression.check(parent) && name === 'callee') { - return true; - } - if(n.MemberExpression.check(parent) && name === 'object') { - return true; - } +},{"./_baseTimes":394,"./_isIndex":448,"./isArguments":510,"./isArray":511,"./isBuffer":514,"./isTypedArray":524}],347:[function(require,module,exports){ +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); - return isBinary(parent); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} - case "ObjectExpression": - if (parent.type === "ArrowFunctionExpression" && - name === "body") { - return true; - } +module.exports = arrayMap; - default: - if (parent.type === "NewExpression" && - name === "callee" && - parent.callee === node) { - return containsCallExpression(node); - } - } +},{}],348:[function(require,module,exports){ +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - if (assumeExpressionContext !== true && - !this.canBeFirstInStatement() && - this.firstInStatement()) - return true; + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} - return false; -}; +module.exports = arrayPush; + +},{}],349:[function(require,module,exports){ +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; -function isBinary(node) { - return n.BinaryExpression.check(node) - || n.LogicalExpression.check(node); + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; } -function isUnaryLike(node) { - return n.UnaryExpression.check(node) - // I considered making SpreadElement and SpreadProperty subtypes - // of UnaryExpression, but they're not really Expression nodes. - || (n.SpreadElement && n.SpreadElement.check(node)) - || (n.SpreadProperty && n.SpreadProperty.check(node)); -} +module.exports = arrayReduce; -var PRECEDENCE = {}; -[["||"], - ["&&"], - ["|"], - ["^"], - ["&"], - ["==", "===", "!=", "!=="], - ["<", ">", "<=", ">=", "in", "instanceof"], - [">>", "<<", ">>>"], - ["+", "-"], - ["*", "/", "%", "**"] -].forEach(function(tier, i) { - tier.forEach(function(op) { - PRECEDENCE[op] = i; - }); -}); +},{}],350:[function(require,module,exports){ +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; -function containsCallExpression(node) { - if (n.CallExpression.check(node)) { - return true; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; } + } + return false; +} - if (isArray.check(node)) { - return node.some(containsCallExpression); - } +module.exports = arraySome; - if (n.Node.check(node)) { - return types.someField(node, function(name, child) { - return containsCallExpression(child); - }); - } +},{}],351:[function(require,module,exports){ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); - return false; +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } } -FPp.canBeFirstInStatement = function() { - var node = this.getNode(); - return !n.FunctionExpression.check(node) - && !n.ObjectExpression.check(node); -}; +module.exports = assignMergeValue; -FPp.firstInStatement = function() { - var s = this.stack; - var parentName, parent; - var childName, child; +},{"./_baseAssignValue":356,"./eq":498}],352:[function(require,module,exports){ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); - for (var i = s.length - 1; i >= 0; i -= 2) { - if (n.Node.check(s[i])) { - childName = parentName; - child = parent; - parentName = s[i - 1]; - parent = s[i]; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (!parent || !child) { - continue; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - if (n.BlockStatement.check(parent) && - parentName === "body" && - childName === 0) { - assert.strictEqual(parent.body[0], child); - return true; - } +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} - if (n.ExpressionStatement.check(parent) && - childName === "expression") { - assert.strictEqual(parent.expression, child); - return true; - } +module.exports = assignValue; - if (n.SequenceExpression.check(parent) && - parentName === "expressions" && - childName === 0) { - assert.strictEqual(parent.expressions[0], child); - continue; - } +},{"./_baseAssignValue":356,"./eq":498}],353:[function(require,module,exports){ +var eq = require('./eq'); - if (n.CallExpression.check(parent) && - childName === "callee") { - assert.strictEqual(parent.callee, child); - continue; - } +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} - if (n.MemberExpression.check(parent) && - childName === "object") { - assert.strictEqual(parent.object, child); - continue; - } +module.exports = assocIndexOf; - if (n.ConditionalExpression.check(parent) && - childName === "test") { - assert.strictEqual(parent.test, child); - continue; - } +},{"./eq":498}],354:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + keys = require('./keys'); - if (isBinary(parent) && - childName === "left") { - assert.strictEqual(parent.left, child); - continue; - } +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} - if (n.UnaryExpression.check(parent) && - !parent.prefix && - childName === "argument") { - assert.strictEqual(parent.argument, child); - continue; - } +module.exports = baseAssign; - return false; - } +},{"./_copyObject":412,"./keys":525}],355:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + keysIn = require('./keysIn'); - return true; -}; +/** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); +} -},{"./types":519,"assert":791}],513:[function(require,module,exports){ -var assert = require("assert"); -var sourceMap = require("source-map"); -var normalizeOptions = require("./options").normalize; -var secretKey = require("private").makeUniqueKey(); -var types = require("./types"); -var isString = types.builtInTypes.string; -var comparePos = require("./util").comparePos; -var Mapping = require("./mapping"); +module.exports = baseAssignIn; -// Goals: -// 1. Minimize new string creation. -// 2. Keep (de)identation O(lines) time. -// 3. Permit negative indentations. -// 4. Enforce immutability. -// 5. No newline characters. +},{"./_copyObject":412,"./keysIn":526}],356:[function(require,module,exports){ +var defineProperty = require('./_defineProperty'); -function getSecret(lines) { - return lines[secretKey]; +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } } -function Lines(infos, sourceFileName) { - assert.ok(this instanceof Lines); - assert.ok(infos.length > 0); +module.exports = baseAssignValue; - if (sourceFileName) { - isString.assert(sourceFileName); - } else { - sourceFileName = null; +},{"./_defineProperty":422}],357:[function(require,module,exports){ +/** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ +function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; } - - Object.defineProperty(this, secretKey, { - value: { - infos: infos, - mappings: [], - name: sourceFileName, - cachedSourceMap: null - } - }); - - if (sourceFileName) { - getSecret(this).mappings.push(new Mapping(this, { - start: this.firstPos(), - end: this.lastPos() - })); + if (lower !== undefined) { + number = number >= lower ? number : lower; } + } + return number; } -// Exposed for instanceof checks. The fromString function should be used -// to create new Lines objects. -exports.Lines = Lines; -var Lp = Lines.prototype; +module.exports = baseClamp; -// These properties used to be assigned to each new object in the Lines -// constructor, but we can more efficiently stuff them into the secret and -// let these lazy accessors compute their values on-the-fly. -Object.defineProperties(Lp, { - length: { - get: function() { - return getSecret(this).infos.length; - } - }, +},{}],358:[function(require,module,exports){ +var Stack = require('./_Stack'), + arrayEach = require('./_arrayEach'), + assignValue = require('./_assignValue'), + baseAssign = require('./_baseAssign'), + baseAssignIn = require('./_baseAssignIn'), + cloneBuffer = require('./_cloneBuffer'), + copyArray = require('./_copyArray'), + copySymbols = require('./_copySymbols'), + copySymbolsIn = require('./_copySymbolsIn'), + getAllKeys = require('./_getAllKeys'), + getAllKeysIn = require('./_getAllKeysIn'), + getTag = require('./_getTag'), + initCloneArray = require('./_initCloneArray'), + initCloneByTag = require('./_initCloneByTag'), + initCloneObject = require('./_initCloneObject'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isObject = require('./isObject'), + keys = require('./keys'); - name: { - get: function() { - return getSecret(this).name; - } - } -}); +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; -function copyLineInfo(info) { - return { - line: info.line, - indent: info.indent, - locked: info.locked, - sliceStart: info.sliceStart, - sliceEnd: info.sliceEnd - }; -} +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; -var fromStringCache = {}; -var hasOwn = fromStringCache.hasOwnProperty; -var maxCacheKeyLen = 10; +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; -function countSpaces(spaces, tabWidth) { - var count = 0; - var len = spaces.length; +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag] = cloneableTags[arrayTag] = +cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = +cloneableTags[boolTag] = cloneableTags[dateTag] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag] = +cloneableTags[numberTag] = cloneableTags[objectTag] = +cloneableTags[regexpTag] = cloneableTags[setTag] = +cloneableTags[stringTag] = cloneableTags[symbolTag] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag] = cloneableTags[funcTag] = +cloneableTags[weakMapTag] = false; - for (var i = 0; i < len; ++i) { - switch (spaces.charCodeAt(i)) { - case 9: // '\t' - assert.strictEqual(typeof tabWidth, "number"); - assert.ok(tabWidth > 0); +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; - var next = Math.ceil(count / tabWidth) * tabWidth; - if (next === count) { - count += tabWidth; - } else { - count = next; - } + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; - break; + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); - case 11: // '\v' - case 12: // '\f' - case 13: // '\r' - case 0xfeff: // zero-width non-breaking space - // These characters contribute nothing to indentation. - break; + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); - case 32: // ' ' - default: // Treat all other whitespace like ' '. - count += 1; - break; - } + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; } - - return count; + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; } -exports.countSpaces = countSpaces; -var leadingSpaceExp = /^\s*/; +module.exports = baseClone; + +},{"./_Stack":335,"./_arrayEach":342,"./_assignValue":352,"./_baseAssign":354,"./_baseAssignIn":355,"./_cloneBuffer":402,"./_copyArray":411,"./_copySymbols":413,"./_copySymbolsIn":414,"./_getAllKeys":427,"./_getAllKeysIn":428,"./_getTag":436,"./_initCloneArray":444,"./_initCloneByTag":445,"./_initCloneObject":446,"./isArray":511,"./isBuffer":514,"./isObject":518,"./keys":525}],359:[function(require,module,exports){ +var isObject = require('./isObject'); -// As specified here: http://www.ecma-international.org/ecma-262/6.0/#sec-line-terminators -var lineTerminatorSeqExp = - /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/; +/** Built-in value references. */ +var objectCreate = Object.create; /** - * @param {Object} options - Options object that configures printing. + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ -function fromString(string, options) { - if (string instanceof Lines) - return string; - - string += ""; - - var tabWidth = options && options.tabWidth; - var tabless = string.indexOf("\t") < 0; - var locked = !! (options && options.locked); - var cacheable = !options && tabless && (string.length <= maxCacheKeyLen); - - assert.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string); - - if (cacheable && hasOwn.call(fromStringCache, string)) - return fromStringCache[string]; +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); - var lines = new Lines(string.split(lineTerminatorSeqExp).map(function(line) { - var spaces = leadingSpaceExp.exec(line)[0]; - return { - line: line, - indent: countSpaces(spaces, tabWidth), - // Boolean indicating whether this line can be reindented. - locked: locked, - sliceStart: spaces.length, - sliceEnd: line.length - }; - }), normalizeOptions(options).sourceFileName); +module.exports = baseCreate; - if (cacheable) - fromStringCache[string] = lines; +},{"./isObject":518}],360:[function(require,module,exports){ +var baseForOwn = require('./_baseForOwn'), + createBaseEach = require('./_createBaseEach'); - return lines; -} -exports.fromString = fromString; +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); -function isOnlyWhitespace(string) { - return !/\S/.test(string); -} +module.exports = baseEach; -Lp.toString = function(options) { - return this.sliceString(this.firstPos(), this.lastPos(), options); -}; +},{"./_baseForOwn":364,"./_createBaseEach":417}],361:[function(require,module,exports){ +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); -Lp.getSourceMap = function(sourceMapName, sourceRoot) { - if (!sourceMapName) { - // Although we could make up a name or generate an anonymous - // source map, instead we assume that any consumer who does not - // provide a name does not actually want a source map. - return null; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } + } + return -1; +} - var targetLines = this; +module.exports = baseFindIndex; - function updateJSON(json) { - json = json || {}; +},{}],362:[function(require,module,exports){ +var arrayPush = require('./_arrayPush'), + isFlattenable = require('./_isFlattenable'); - isString.assert(sourceMapName); - json.file = sourceMapName; +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - if (sourceRoot) { - isString.assert(sourceRoot); - json.sourceRoot = sourceRoot; - } + predicate || (predicate = isFlattenable); + result || (result = []); - return json; + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; } + } + return result; +} - var secret = getSecret(targetLines); - if (secret.cachedSourceMap) { - // Since Lines objects are immutable, we can reuse any source map - // that was previously generated. Nevertheless, we return a new - // JSON object here to protect the cached source map from outside - // modification. - return updateJSON(secret.cachedSourceMap.toJSON()); - } +module.exports = baseFlatten; - var smg = new sourceMap.SourceMapGenerator(updateJSON()); - var sourcesToContents = {}; +},{"./_arrayPush":348,"./_isFlattenable":447}],363:[function(require,module,exports){ +var createBaseFor = require('./_createBaseFor'); - secret.mappings.forEach(function(mapping) { - var sourceCursor = mapping.sourceLines.skipSpaces( - mapping.sourceLoc.start - ) || mapping.sourceLines.lastPos(); +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); - var targetCursor = targetLines.skipSpaces( - mapping.targetLoc.start - ) || targetLines.lastPos(); +module.exports = baseFor; - while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && - comparePos(targetCursor, mapping.targetLoc.end) < 0) { +},{"./_createBaseFor":418}],364:[function(require,module,exports){ +var baseFor = require('./_baseFor'), + keys = require('./keys'); - var sourceChar = mapping.sourceLines.charAt(sourceCursor); - var targetChar = targetLines.charAt(targetCursor); - assert.strictEqual(sourceChar, targetChar); +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} - var sourceName = mapping.sourceLines.name; +module.exports = baseForOwn; - // Add mappings one character at a time for maximum resolution. - smg.addMapping({ - source: sourceName, - original: { line: sourceCursor.line, - column: sourceCursor.column }, - generated: { line: targetCursor.line, - column: targetCursor.column } - }); +},{"./_baseFor":363,"./keys":525}],365:[function(require,module,exports){ +var castPath = require('./_castPath'), + toKey = require('./_toKey'); - if (!hasOwn.call(sourcesToContents, sourceName)) { - var sourceContent = mapping.sourceLines.toString(); - smg.setSourceContent(sourceName, sourceContent); - sourcesToContents[sourceName] = sourceContent; - } +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = castPath(path, object); - targetLines.nextPos(targetCursor, true); - mapping.sourceLines.nextPos(sourceCursor, true); - } - }); + var index = 0, + length = path.length; - secret.cachedSourceMap = smg; + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} - return smg.toJSON(); -}; +module.exports = baseGet; -Lp.bootstrapCharAt = function(pos) { - assert.strictEqual(typeof pos, "object"); - assert.strictEqual(typeof pos.line, "number"); - assert.strictEqual(typeof pos.column, "number"); +},{"./_castPath":400,"./_toKey":488}],366:[function(require,module,exports){ +var arrayPush = require('./_arrayPush'), + isArray = require('./isArray'); - var line = pos.line, - column = pos.column, - strings = this.toString().split(lineTerminatorSeqExp), - string = strings[line - 1]; +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} - if (typeof string === "undefined") - return ""; +module.exports = baseGetAllKeys; - if (column === string.length && - line < strings.length) - return "\n"; +},{"./_arrayPush":348,"./isArray":511}],367:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + getRawTag = require('./_getRawTag'), + objectToString = require('./_objectToString'); - if (column >= string.length) - return ""; +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; - return string.charAt(column); -}; +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; -Lp.charAt = function(pos) { - assert.strictEqual(typeof pos, "object"); - assert.strictEqual(typeof pos.line, "number"); - assert.strictEqual(typeof pos.column, "number"); +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} - var line = pos.line, - column = pos.column, - secret = getSecret(this), - infos = secret.infos, - info = infos[line - 1], - c = column; +module.exports = baseGetTag; - if (typeof info === "undefined" || c < 0) - return ""; +},{"./_Symbol":336,"./_getRawTag":433,"./_objectToString":472}],368:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var indent = this.getIndentAt(line); - if (c < indent) - return " "; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - c += info.sliceStart - indent; +/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); +} - if (c === info.sliceEnd && - line < this.length) - return "\n"; +module.exports = baseHas; - if (c >= info.sliceEnd) - return ""; +},{}],369:[function(require,module,exports){ +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} - return info.line.charAt(c); -}; +module.exports = baseHasIn; -Lp.stripMargin = function(width, skipFirstLine) { - if (width === 0) - return this; +},{}],370:[function(require,module,exports){ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictIndexOf = require('./_strictIndexOf'); - assert.ok(width > 0, "negative margin: " + width); +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} - if (skipFirstLine && this.length === 1) - return this; +module.exports = baseIndexOf; - var secret = getSecret(this); +},{"./_baseFindIndex":361,"./_baseIsNaN":375,"./_strictIndexOf":486}],371:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); - var lines = new Lines(secret.infos.map(function(info, i) { - if (info.line && (i > 0 || !skipFirstLine)) { - info = copyLineInfo(info); - info.indent = Math.max(0, info.indent - width); - } - return info; - })); +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; - if (secret.mappings.length > 0) { - var newMappings = getSecret(lines).mappings; - assert.strictEqual(newMappings.length, 0); - secret.mappings.forEach(function(mapping) { - newMappings.push(mapping.indent(width, skipFirstLine, true)); - }); - } +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} - return lines; -}; +module.exports = baseIsArguments; -Lp.indent = function(by) { - if (by === 0) - return this; +},{"./_baseGetTag":367,"./isObjectLike":519}],372:[function(require,module,exports){ +var baseIsEqualDeep = require('./_baseIsEqualDeep'), + isObjectLike = require('./isObjectLike'); - var secret = getSecret(this); +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} - var lines = new Lines(secret.infos.map(function(info) { - if (info.line && ! info.locked) { - info = copyLineInfo(info); - info.indent += by; - } - return info - })); +module.exports = baseIsEqual; - if (secret.mappings.length > 0) { - var newMappings = getSecret(lines).mappings; - assert.strictEqual(newMappings.length, 0); - secret.mappings.forEach(function(mapping) { - newMappings.push(mapping.indent(by)); - }); - } +},{"./_baseIsEqualDeep":373,"./isObjectLike":519}],373:[function(require,module,exports){ +var Stack = require('./_Stack'), + equalArrays = require('./_equalArrays'), + equalByTag = require('./_equalByTag'), + equalObjects = require('./_equalObjects'), + getTag = require('./_getTag'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isTypedArray = require('./isTypedArray'); - return lines; -}; +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; -Lp.indentTail = function(by) { - if (by === 0) - return this; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; - if (this.length < 2) - return this; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var secret = getSecret(this); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - var lines = new Lines(secret.infos.map(function(info, i) { - if (i > 0 && info.line && ! info.locked) { - info = copyLineInfo(info); - info.indent += by; - } +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); - return info; - })); + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; - if (secret.mappings.length > 0) { - var newMappings = getSecret(lines).mappings; - assert.strictEqual(newMappings.length, 0); - secret.mappings.forEach(function(mapping) { - newMappings.push(mapping.indent(by, true)); - }); + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - return lines; -}; + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; -Lp.lockIndentTail = function () { - if (this.length < 2) { - return this; + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} - var infos = getSecret(this).infos; +module.exports = baseIsEqualDeep; - return new Lines(infos.map(function (info, i) { - info = copyLineInfo(info); - info.locked = i > 0; - return info; - })); -}; +},{"./_Stack":335,"./_equalArrays":423,"./_equalByTag":424,"./_equalObjects":425,"./_getTag":436,"./isArray":511,"./isBuffer":514,"./isTypedArray":524}],374:[function(require,module,exports){ +var Stack = require('./_Stack'), + baseIsEqual = require('./_baseIsEqual'); -Lp.getIndentAt = function(line) { - assert.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); - var secret = getSecret(this), - info = secret.infos[line - 1]; - return Math.max(info.indent, 0); -}; +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; -Lp.guessTabWidth = function() { - var secret = getSecret(this); - if (hasOwn.call(secret, "cachedTabWidth")) { - return secret.cachedTabWidth; +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; - var counts = []; // Sparse array. - var lastIndent = 0; + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} - for (var line = 1, last = this.length; line <= last; ++line) { - var info = secret.infos[line - 1]; - var sliced = info.line.slice(info.sliceStart, info.sliceEnd); +module.exports = baseIsMatch; - // Whitespace-only lines don't tell us much about the likely tab - // width of this code. - if (isOnlyWhitespace(sliced)) { - continue; - } +},{"./_Stack":335,"./_baseIsEqual":372}],375:[function(require,module,exports){ +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} - var diff = Math.abs(info.indent - lastIndent); - counts[diff] = ~~counts[diff] + 1; - lastIndent = info.indent; - } +module.exports = baseIsNaN; - var maxCount = -1; - var result = 2; +},{}],376:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isMasked = require('./_isMasked'), + isObject = require('./isObject'), + toSource = require('./_toSource'); - for (var tabWidth = 1; - tabWidth < counts.length; - tabWidth += 1) { - if (hasOwn.call(counts, tabWidth) && - counts[tabWidth] > maxCount) { - maxCount = counts[tabWidth]; - result = tabWidth; - } - } +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - return secret.cachedTabWidth = result; -}; +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -// Determine if the list of lines has a first line that starts with a // -// or /* comment. If this is the case, the code may need to be wrapped in -// parens to avoid ASI issues. -Lp.startsWithComment = function () { - var secret = getSecret(this); - if (secret.infos.length === 0) { - return false; - } - var firstLineInfo = secret.infos[0], - sliceStart = firstLineInfo.sliceStart, - sliceEnd = firstLineInfo.sliceEnd, - firstLine = firstLineInfo.line.slice(sliceStart, sliceEnd).trim(); - return firstLine.length === 0 || - firstLine.slice(0, 2) === "//" || - firstLine.slice(0, 2) === "/*"; -}; +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; -Lp.isOnlyWhitespace = function() { - return isOnlyWhitespace(this.toString()); -}; +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; -Lp.isPrecededOnlyByWhitespace = function(pos) { - var secret = getSecret(this); - var info = secret.infos[pos.line - 1]; - var indent = Math.max(info.indent, 0); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - var diff = pos.column - indent; - if (diff <= 0) { - // If pos.column does not exceed the indentation amount, then - // there must be only whitespace before it. - return true; - } +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); - var start = info.sliceStart; - var end = Math.min(start + diff, info.sliceEnd); - var prefix = info.line.slice(start, end); +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} - return isOnlyWhitespace(prefix); -}; +module.exports = baseIsNative; -Lp.getLineLength = function(line) { - var secret = getSecret(this), - info = secret.infos[line - 1]; - return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; -}; +},{"./_isMasked":452,"./_toSource":489,"./isFunction":515,"./isObject":518}],377:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); -Lp.nextPos = function(pos, skipSpaces) { - var l = Math.max(pos.line, 0), - c = Math.max(pos.column, 0); +/** `Object#toString` result references. */ +var regexpTag = '[object RegExp]'; - if (c < this.getLineLength(l)) { - pos.column += 1; +/** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ +function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; +} - return skipSpaces - ? !!this.skipSpaces(pos, false, true) - : true; - } +module.exports = baseIsRegExp; - if (l < this.length) { - pos.line += 1; - pos.column = 0; +},{"./_baseGetTag":367,"./isObjectLike":519}],378:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isLength = require('./isLength'), + isObjectLike = require('./isObjectLike'); - return skipSpaces - ? !!this.skipSpaces(pos, false, true) - : true; - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; - return false; -}; +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; -Lp.prevPos = function(pos, skipSpaces) { - var l = pos.line, - c = pos.column; +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; - if (c < 1) { - l -= 1; +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} - if (l < 1) - return false; +module.exports = baseIsTypedArray; - c = this.getLineLength(l); +},{"./_baseGetTag":367,"./isLength":517,"./isObjectLike":519}],379:[function(require,module,exports){ +var baseMatches = require('./_baseMatches'), + baseMatchesProperty = require('./_baseMatchesProperty'), + identity = require('./identity'), + isArray = require('./isArray'), + property = require('./property'); - } else { - c = Math.min(c - 1, this.getLineLength(l)); - } +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} - pos.line = l; - pos.column = c; +module.exports = baseIteratee; - return skipSpaces - ? !!this.skipSpaces(pos, true, true) - : true; -}; +},{"./_baseMatches":383,"./_baseMatchesProperty":384,"./identity":508,"./isArray":511,"./property":531}],380:[function(require,module,exports){ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); -Lp.firstPos = function() { - // Trivial, but provided for completeness. - return { line: 1, column: 0 }; -}; +/** Used for built-in method references. */ +var objectProto = Object.prototype; -Lp.lastPos = function() { - return { - line: this.length, - column: this.getLineLength(this.length) - }; -}; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -Lp.skipSpaces = function(pos, backward, modifyInPlace) { - if (pos) { - pos = modifyInPlace ? pos : { - line: pos.line, - column: pos.column - }; - } else if (backward) { - pos = this.lastPos(); - } else { - pos = this.firstPos(); +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); } + } + return result; +} - if (backward) { - while (this.prevPos(pos)) { - if (!isOnlyWhitespace(this.charAt(pos)) && - this.nextPos(pos)) { - return pos; - } - } +module.exports = baseKeys; - return null; +},{"./_isPrototype":453,"./_nativeKeys":469}],381:[function(require,module,exports){ +var isObject = require('./isObject'), + isPrototype = require('./_isPrototype'), + nativeKeysIn = require('./_nativeKeysIn'); - } else { - while (isOnlyWhitespace(this.charAt(pos))) { - if (!this.nextPos(pos)) { - return null; - } - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - return pos; - } -}; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -Lp.trimLeft = function() { - var pos = this.skipSpaces(this.firstPos(), false, true); - return pos ? this.slice(pos) : emptyLines; -}; +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; -Lp.trimRight = function() { - var pos = this.skipSpaces(this.lastPos(), true, true); - return pos ? this.slice(this.firstPos(), pos) : emptyLines; -}; + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; +} -Lp.trim = function() { - var start = this.skipSpaces(this.firstPos(), false, true); - if (start === null) - return emptyLines; +module.exports = baseKeysIn; - var end = this.skipSpaces(this.lastPos(), true, true); - assert.notStrictEqual(end, null); +},{"./_isPrototype":453,"./_nativeKeysIn":470,"./isObject":518}],382:[function(require,module,exports){ +var baseEach = require('./_baseEach'), + isArrayLike = require('./isArrayLike'); - return this.slice(start, end); -}; +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; -Lp.eachPos = function(callback, startPos, skipSpaces) { - var pos = this.firstPos(); + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} - if (startPos) { - pos.line = startPos.line, - pos.column = startPos.column - } +module.exports = baseMap; - if (skipSpaces && !this.skipSpaces(pos, false, true)) { - return; // Encountered nothing but spaces. - } +},{"./_baseEach":360,"./isArrayLike":512}],383:[function(require,module,exports){ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'), + matchesStrictComparable = require('./_matchesStrictComparable'); - do callback.call(this, pos); - while (this.nextPos(pos, skipSpaces)); -}; +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} -Lp.bootstrapSlice = function(start, end) { - var strings = this.toString().split( - lineTerminatorSeqExp - ).slice( - start.line - 1, - end.line - ); +module.exports = baseMatches; - strings.push(strings.pop().slice(0, end.column)); - strings[0] = strings[0].slice(start.column); +},{"./_baseIsMatch":374,"./_getMatchData":430,"./_matchesStrictComparable":466}],384:[function(require,module,exports){ +var baseIsEqual = require('./_baseIsEqual'), + get = require('./get'), + hasIn = require('./hasIn'), + isKey = require('./_isKey'), + isStrictComparable = require('./_isStrictComparable'), + matchesStrictComparable = require('./_matchesStrictComparable'), + toKey = require('./_toKey'); - return fromString(strings.join("\n")); -}; +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; -Lp.slice = function(start, end) { - if (!end) { - if (!start) { - // The client seems to want a copy of this Lines object, but - // Lines objects are immutable, so it's perfectly adequate to - // return the same object. - return this; - } +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; +} - // Slice to the end if no end position was provided. - end = this.lastPos(); - } +module.exports = baseMatchesProperty; - var secret = getSecret(this); - var sliced = secret.infos.slice(start.line - 1, end.line); +},{"./_baseIsEqual":372,"./_isKey":450,"./_isStrictComparable":454,"./_matchesStrictComparable":466,"./_toKey":488,"./get":505,"./hasIn":507}],385:[function(require,module,exports){ +var Stack = require('./_Stack'), + assignMergeValue = require('./_assignMergeValue'), + baseFor = require('./_baseFor'), + baseMergeDeep = require('./_baseMergeDeep'), + isObject = require('./isObject'), + keysIn = require('./keysIn'); - if (start.line === end.line) { - sliced[0] = sliceInfo(sliced[0], start.column, end.column); - } else { - assert.ok(start.line < end.line); - sliced[0] = sliceInfo(sliced[0], start.column); - sliced.push(sliceInfo(sliced.pop(), 0, end.column)); +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } + else { + var newValue = customizer + ? customizer(object[key], srcValue, (key + ''), object, source, stack) + : undefined; - var lines = new Lines(sliced); - - if (secret.mappings.length > 0) { - var newMappings = getSecret(lines).mappings; - assert.strictEqual(newMappings.length, 0); - secret.mappings.forEach(function(mapping) { - var sliced = mapping.slice(this, start, end); - if (sliced) { - newMappings.push(sliced); - } - }, this); + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); } + }, keysIn); +} - return lines; -}; +module.exports = baseMerge; -function sliceInfo(info, startCol, endCol) { - var sliceStart = info.sliceStart; - var sliceEnd = info.sliceEnd; - var indent = Math.max(info.indent, 0); - var lineLength = indent + sliceEnd - sliceStart; +},{"./_Stack":335,"./_assignMergeValue":351,"./_baseFor":363,"./_baseMergeDeep":386,"./isObject":518,"./keysIn":526}],386:[function(require,module,exports){ +var assignMergeValue = require('./_assignMergeValue'), + cloneBuffer = require('./_cloneBuffer'), + cloneTypedArray = require('./_cloneTypedArray'), + copyArray = require('./_copyArray'), + initCloneObject = require('./_initCloneObject'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLikeObject = require('./isArrayLikeObject'), + isBuffer = require('./isBuffer'), + isFunction = require('./isFunction'), + isObject = require('./isObject'), + isPlainObject = require('./isPlainObject'), + isTypedArray = require('./isTypedArray'), + toPlainObject = require('./toPlainObject'); - if (typeof endCol === "undefined") { - endCol = lineLength; - } +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], + srcValue = source[key], + stacked = stack.get(srcValue); - startCol = Math.max(startCol, 0); - endCol = Math.min(endCol, lineLength); - endCol = Math.max(endCol, startCol); + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; - if (endCol < indent) { - indent = endCol; - sliceEnd = sliceStart; - } else { - sliceEnd -= lineLength - endCol; - } + var isCommon = newValue === undefined; - lineLength = endCol; - lineLength -= startCol; + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); - if (startCol < indent) { - indent -= startCol; - } else { - startCol -= indent; - indent = 0; - sliceStart += startCol; + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } } - - assert.ok(indent >= 0); - assert.ok(sliceStart <= sliceEnd); - assert.strictEqual(lineLength, indent + sliceEnd - sliceStart); - - if (info.indent === indent && - info.sliceStart === sliceStart && - info.sliceEnd === sliceEnd) { - return info; + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } } - - return { - line: info.line, - indent: indent, - // A destructive slice always unlocks indentation. - locked: false, - sliceStart: sliceStart, - sliceEnd: sliceEnd - }; + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); } -Lp.bootstrapSliceString = function(start, end, options) { - return this.slice(start, end).toString(options); -}; +module.exports = baseMergeDeep; -Lp.sliceString = function(start, end, options) { - if (!end) { - if (!start) { - // The client seems to want a copy of this Lines object, but - // Lines objects are immutable, so it's perfectly adequate to - // return the same object. - return this; - } +},{"./_assignMergeValue":351,"./_cloneBuffer":402,"./_cloneTypedArray":408,"./_copyArray":411,"./_initCloneObject":446,"./isArguments":510,"./isArray":511,"./isArrayLikeObject":513,"./isBuffer":514,"./isFunction":515,"./isObject":518,"./isPlainObject":520,"./isTypedArray":524,"./toPlainObject":540}],387:[function(require,module,exports){ +var arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseMap = require('./_baseMap'), + baseSortBy = require('./_baseSortBy'), + baseUnary = require('./_baseUnary'), + compareMultiple = require('./_compareMultiple'), + identity = require('./identity'); - // Slice to the end if no end position was provided. - end = this.lastPos(); - } +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); - options = normalizeOptions(options); + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); - var infos = getSecret(this).infos; - var parts = []; - var tabWidth = options.tabWidth; + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} - for (var line = start.line; line <= end.line; ++line) { - var info = infos[line - 1]; +module.exports = baseOrderBy; - if (line === start.line) { - if (line === end.line) { - info = sliceInfo(info, start.column, end.column); - } else { - info = sliceInfo(info, start.column); - } - } else if (line === end.line) { - info = sliceInfo(info, 0, end.column); - } +},{"./_arrayMap":347,"./_baseIteratee":379,"./_baseMap":382,"./_baseSortBy":393,"./_baseUnary":396,"./_compareMultiple":410,"./identity":508}],388:[function(require,module,exports){ +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} - var indent = Math.max(info.indent, 0); +module.exports = baseProperty; - var before = info.line.slice(0, info.sliceStart); - if (options.reuseWhitespace && - isOnlyWhitespace(before) && - countSpaces(before, options.tabWidth) === indent) { - // Reuse original spaces if the indentation is correct. - parts.push(info.line.slice(0, info.sliceEnd)); - continue; - } +},{}],389:[function(require,module,exports){ +var baseGet = require('./_baseGet'); - var tabs = 0; - var spaces = indent; +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} - if (options.useTabs) { - tabs = Math.floor(indent / tabWidth); - spaces -= tabs * tabWidth; - } +module.exports = basePropertyDeep; - var result = ""; +},{"./_baseGet":365}],390:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - if (tabs > 0) { - result += new Array(tabs + 1).join("\t"); - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor; - if (spaces > 0) { - result += new Array(spaces + 1).join(" "); - } +/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ +function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); - result += info.line.slice(info.sliceStart, info.sliceEnd); + return result; +} - parts.push(result); - } +module.exports = baseRepeat; - return parts.join(options.lineTerminator); -}; +},{}],391:[function(require,module,exports){ +var identity = require('./identity'), + overRest = require('./_overRest'), + setToString = require('./_setToString'); -Lp.isEmpty = function() { - return this.length < 2 && this.getLineLength(1) < 1; -}; +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} -Lp.join = function(elements) { - var separator = this; - var separatorSecret = getSecret(separator); - var infos = []; - var mappings = []; - var prevInfo; +module.exports = baseRest; - function appendSecret(secret) { - if (secret === null) - return; +},{"./_overRest":474,"./_setToString":479,"./identity":508}],392:[function(require,module,exports){ +var constant = require('./constant'), + defineProperty = require('./_defineProperty'), + identity = require('./identity'); - if (prevInfo) { - var info = secret.infos[0]; - var indent = new Array(info.indent + 1).join(" "); - var prevLine = infos.length; - var prevColumn = Math.max(prevInfo.indent, 0) + - prevInfo.sliceEnd - prevInfo.sliceStart; +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; - prevInfo.line = prevInfo.line.slice( - 0, prevInfo.sliceEnd) + indent + info.line.slice( - info.sliceStart, info.sliceEnd); +module.exports = baseSetToString; - // If any part of a line is indentation-locked, the whole line - // will be indentation-locked. - prevInfo.locked = prevInfo.locked || info.locked; +},{"./_defineProperty":422,"./constant":496,"./identity":508}],393:[function(require,module,exports){ +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; - prevInfo.sliceEnd = prevInfo.line.length; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} - if (secret.mappings.length > 0) { - secret.mappings.forEach(function(mapping) { - mappings.push(mapping.add(prevLine, prevColumn)); - }); - } +module.exports = baseSortBy; - } else if (secret.mappings.length > 0) { - mappings.push.apply(mappings, secret.mappings); - } +},{}],394:[function(require,module,exports){ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - secret.infos.forEach(function(info, i) { - if (!prevInfo || i > 0) { - prevInfo = copyLineInfo(info); - infos.push(prevInfo); - } - }); - } + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - function appendWithSeparator(secret, i) { - if (i > 0) - appendSecret(separatorSecret); - appendSecret(secret); - } +module.exports = baseTimes; - elements.map(function(elem) { - var lines = fromString(elem); - if (lines.isEmpty()) - return null; - return getSecret(lines); - }).forEach(separator.isEmpty() - ? appendSecret - : appendWithSeparator); +},{}],395:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + arrayMap = require('./_arrayMap'), + isArray = require('./isArray'), + isSymbol = require('./isSymbol'); - if (infos.length < 1) - return emptyLines; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; - var lines = new Lines(infos); +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; - getSecret(lines).mappings = mappings; +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} - return lines; -}; +module.exports = baseToString; -exports.concat = function(elements) { - return emptyLines.join(elements); -}; +},{"./_Symbol":336,"./_arrayMap":347,"./isArray":511,"./isSymbol":523}],396:[function(require,module,exports){ +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} -Lp.concat = function(other) { - var args = arguments, - list = [this]; - list.push.apply(list, args); - assert.strictEqual(list.length, args.length + 1); - return emptyLines.join(list); -}; +module.exports = baseUnary; -// The emptyLines object needs to be created all the way down here so that -// Lines.prototype will be fully populated. -var emptyLines = fromString(""); +},{}],397:[function(require,module,exports){ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + cacheHas = require('./_cacheHas'), + createSet = require('./_createSet'), + setToArray = require('./_setToArray'); -},{"./mapping":514,"./options":515,"./types":519,"./util":520,"assert":791,"private":510,"source-map":534}],514:[function(require,module,exports){ -var assert = require("assert"); -var types = require("./types"); -var isString = types.builtInTypes.string; -var isNumber = types.builtInTypes.number; -var SourceLocation = types.namedTypes.SourceLocation; -var Position = types.namedTypes.Position; -var linesModule = require("./lines"); -var comparePos = require("./util").comparePos; +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; -function Mapping(sourceLines, sourceLoc, targetLoc) { - assert.ok(this instanceof Mapping); - assert.ok(sourceLines instanceof linesModule.Lines); - SourceLocation.assert(sourceLoc); +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; - if (targetLoc) { - // In certain cases it's possible for targetLoc.{start,end}.column - // values to be negative, which technically makes them no longer - // valid SourceLocation nodes, so we need to be more forgiving. - assert.ok( - isNumber.check(targetLoc.start.line) && - isNumber.check(targetLoc.start.column) && - isNumber.check(targetLoc.end.line) && - isNumber.check(targetLoc.end.column) - ); - } else { - // Assume identity mapping if no targetLoc specified. - targetLoc = sourceLoc; + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; - Object.defineProperties(this, { - sourceLines: { value: sourceLines }, - sourceLoc: { value: sourceLoc }, - targetLoc: { value: targetLoc } - }); + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } -var Mp = Mapping.prototype; -module.exports = Mapping; +module.exports = baseUniq; -Mp.slice = function(lines, start, end) { - assert.ok(lines instanceof linesModule.Lines); - Position.assert(start); +},{"./_SetCache":334,"./_arrayIncludes":344,"./_arrayIncludesWith":345,"./_cacheHas":399,"./_createSet":420,"./_setToArray":478}],398:[function(require,module,exports){ +var arrayMap = require('./_arrayMap'); - if (end) { - Position.assert(end); - } else { - end = lines.lastPos(); - } +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} - var sourceLines = this.sourceLines; - var sourceLoc = this.sourceLoc; - var targetLoc = this.targetLoc; +module.exports = baseValues; - function skip(name) { - var sourceFromPos = sourceLoc[name]; - var targetFromPos = targetLoc[name]; - var targetToPos = start; +},{"./_arrayMap":347}],399:[function(require,module,exports){ +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} - if (name === "end") { - targetToPos = end; - } else { - assert.strictEqual(name, "start"); - } +module.exports = cacheHas; - return skipChars( - sourceLines, sourceFromPos, - lines, targetFromPos, targetToPos - ); - } +},{}],400:[function(require,module,exports){ +var isArray = require('./isArray'), + isKey = require('./_isKey'), + stringToPath = require('./_stringToPath'), + toString = require('./toString'); - if (comparePos(start, targetLoc.start) <= 0) { - if (comparePos(targetLoc.end, end) <= 0) { - targetLoc = { - start: subtractPos(targetLoc.start, start.line, start.column), - end: subtractPos(targetLoc.end, start.line, start.column) - }; +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); +} - // The sourceLoc can stay the same because the contents of the - // targetLoc have not changed. +module.exports = castPath; - } else if (comparePos(end, targetLoc.start) <= 0) { - return null; +},{"./_isKey":450,"./_stringToPath":487,"./isArray":511,"./toString":541}],401:[function(require,module,exports){ +var Uint8Array = require('./_Uint8Array'); - } else { - sourceLoc = { - start: sourceLoc.start, - end: skip("end") - }; +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} - targetLoc = { - start: subtractPos(targetLoc.start, start.line, start.column), - end: subtractPos(end, start.line, start.column) - }; - } +module.exports = cloneArrayBuffer; - } else { - if (comparePos(targetLoc.end, start) <= 0) { - return null; - } +},{"./_Uint8Array":337}],402:[function(require,module,exports){ +var root = require('./_root'); - if (comparePos(targetLoc.end, end) <= 0) { - sourceLoc = { - start: skip("start"), - end: sourceLoc.end - }; +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - targetLoc = { - // Same as subtractPos(start, start.line, start.column): - start: { line: 1, column: 0 }, - end: subtractPos(targetLoc.end, start.line, start.column) - }; +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - } else { - sourceLoc = { - start: skip("start"), - end: skip("end") - }; +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; - targetLoc = { - // Same as subtractPos(start, start.line, start.column): - start: { line: 1, column: 0 }, - end: subtractPos(end, start.line, start.column) - }; - } - } +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; - return new Mapping(this.sourceLines, sourceLoc, targetLoc); -}; +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); -Mp.add = function(line, column) { - return new Mapping(this.sourceLines, this.sourceLoc, { - start: addPos(this.targetLoc.start, line, column), - end: addPos(this.targetLoc.end, line, column) - }); -}; + buffer.copy(result); + return result; +} -function addPos(toPos, line, column) { - return { - line: toPos.line + line - 1, - column: (toPos.line === 1) - ? toPos.column + column - : toPos.column - }; +module.exports = cloneBuffer; + +},{"./_root":475}],403:[function(require,module,exports){ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } -Mp.subtract = function(line, column) { - return new Mapping(this.sourceLines, this.sourceLoc, { - start: subtractPos(this.targetLoc.start, line, column), - end: subtractPos(this.targetLoc.end, line, column) - }); -}; +module.exports = cloneDataView; -function subtractPos(fromPos, line, column) { - return { - line: fromPos.line - line + 1, - column: (fromPos.line === line) - ? fromPos.column - column - : fromPos.column - }; +},{"./_cloneArrayBuffer":401}],404:[function(require,module,exports){ +var addMapEntry = require('./_addMapEntry'), + arrayReduce = require('./_arrayReduce'), + mapToArray = require('./_mapToArray'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * Creates a clone of `map`. + * + * @private + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. + */ +function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); } -Mp.indent = function(by, skipFirstLine, noNegativeColumns) { - if (by === 0) { - return this; - } +module.exports = cloneMap; - var targetLoc = this.targetLoc; - var startLine = targetLoc.start.line; - var endLine = targetLoc.end.line; +},{"./_addMapEntry":339,"./_arrayReduce":349,"./_mapToArray":465}],405:[function(require,module,exports){ +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags = /\w*$/; - if (skipFirstLine && startLine === 1 && endLine === 1) { - return this; - } +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} - targetLoc = { - start: targetLoc.start, - end: targetLoc.end - }; +module.exports = cloneRegExp; - if (!skipFirstLine || startLine > 1) { - var startColumn = targetLoc.start.column + by; - targetLoc.start = { - line: startLine, - column: noNegativeColumns - ? Math.max(0, startColumn) - : startColumn - }; - } +},{}],406:[function(require,module,exports){ +var addSetEntry = require('./_addSetEntry'), + arrayReduce = require('./_arrayReduce'), + setToArray = require('./_setToArray'); - if (!skipFirstLine || endLine > 1) { - var endColumn = targetLoc.end.column + by; - targetLoc.end = { - line: endLine, - column: noNegativeColumns - ? Math.max(0, endColumn) - : endColumn - }; - } +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; - return new Mapping(this.sourceLines, this.sourceLoc, targetLoc); -}; +/** + * Creates a clone of `set`. + * + * @private + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ +function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); +} -function skipChars( - sourceLines, sourceFromPos, - targetLines, targetFromPos, targetToPos -) { - assert.ok(sourceLines instanceof linesModule.Lines); - assert.ok(targetLines instanceof linesModule.Lines); - Position.assert(sourceFromPos); - Position.assert(targetFromPos); - Position.assert(targetToPos); +module.exports = cloneSet; - var targetComparison = comparePos(targetFromPos, targetToPos); - if (targetComparison === 0) { - // Trivial case: no characters to skip. - return sourceFromPos; - } +},{"./_addSetEntry":340,"./_arrayReduce":349,"./_setToArray":478}],407:[function(require,module,exports){ +var Symbol = require('./_Symbol'); - if (targetComparison < 0) { - // Skipping forward. +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - var sourceCursor = sourceLines.skipSpaces(sourceFromPos); - var targetCursor = targetLines.skipSpaces(targetFromPos); +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; +} - var lineDiff = targetToPos.line - targetCursor.line; - sourceCursor.line += lineDiff; - targetCursor.line += lineDiff; +module.exports = cloneSymbol; - if (lineDiff > 0) { - // If jumping to later lines, reset columns to the beginnings - // of those lines. - sourceCursor.column = 0; - targetCursor.column = 0; - } else { - assert.strictEqual(lineDiff, 0); - } +},{"./_Symbol":336}],408:[function(require,module,exports){ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); - while (comparePos(targetCursor, targetToPos) < 0 && - targetLines.nextPos(targetCursor, true)) { - assert.ok(sourceLines.nextPos(sourceCursor, true)); - assert.strictEqual( - sourceLines.charAt(sourceCursor), - targetLines.charAt(targetCursor) - ); - } +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} - } else { - // Skipping backward. +module.exports = cloneTypedArray; - var sourceCursor = sourceLines.skipSpaces(sourceFromPos, true); - var targetCursor = targetLines.skipSpaces(targetFromPos, true); +},{"./_cloneArrayBuffer":401}],409:[function(require,module,exports){ +var isSymbol = require('./isSymbol'); - var lineDiff = targetToPos.line - targetCursor.line; - sourceCursor.line += lineDiff; - targetCursor.line += lineDiff; +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); - if (lineDiff < 0) { - // If jumping to earlier lines, reset columns to the ends of - // those lines. - sourceCursor.column = sourceLines.getLineLength(sourceCursor.line); - targetCursor.column = targetLines.getLineLength(targetCursor.line); - } else { - assert.strictEqual(lineDiff, 0); - } + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); - while (comparePos(targetToPos, targetCursor) < 0 && - targetLines.prevPos(targetCursor, true)) { - assert.ok(sourceLines.prevPos(sourceCursor, true)); - assert.strictEqual( - sourceLines.charAt(sourceCursor), - targetLines.charAt(targetCursor) - ); - } + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; } - - return sourceCursor; + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; } -},{"./lines":513,"./types":519,"./util":520,"assert":791}],515:[function(require,module,exports){ -var defaults = { - // If you want to use a different branch of esprima, or any other - // module that supports a .parse function, pass that module object to - // recast.parse as options.parser (legacy synonym: options.esprima). - parser: require("esprima"), +module.exports = compareAscending; - // Number of spaces the pretty-printer should use per tab for - // indentation. If you do not pass this option explicitly, it will be - // (quite reliably!) inferred from the original code. - tabWidth: 4, +},{"./isSymbol":523}],410:[function(require,module,exports){ +var compareAscending = require('./_compareAscending'); - // If you really want the pretty-printer to use tabs instead of - // spaces, make this option true. - useTabs: false, +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; - // The reprinting code leaves leading whitespace untouched unless it - // has to reindent a line, or you pass false for this option. - reuseWhitespace: true, + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} - // Override this option to use a different line terminator, e.g. \r\n. - lineTerminator: require("os").EOL, +module.exports = compareMultiple; - // Some of the pretty-printer code (such as that for printing function - // parameter lists) makes a valiant attempt to prevent really long - // lines. You can adjust the limit by changing this option; however, - // there is no guarantee that line length will fit inside this limit. - wrapColumn: 74, // Aspirational for now. +},{"./_compareAscending":409}],411:[function(require,module,exports){ +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; - // Pass a string as options.sourceFileName to recast.parse to tell the - // reprinter to keep track of reused code so that it can construct a - // source map automatically. - sourceFileName: null, + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} - // Pass a string as options.sourceMapName to recast.print, and - // (provided you passed options.sourceFileName earlier) the - // PrintResult of recast.print will have a .map property for the - // generated source map. - sourceMapName: null, +module.exports = copyArray; - // If provided, this option will be passed along to the source map - // generator as a root directory for relative source file paths. - sourceRoot: null, +},{}],412:[function(require,module,exports){ +var assignValue = require('./_assignValue'), + baseAssignValue = require('./_baseAssignValue'); - // If you provide a source map that was generated from a previous call - // to recast.print as options.inputSourceMap, the old source map will - // be composed with the new source map. - inputSourceMap: null, +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); - // If you want esprima to generate .range information (recast only - // uses .loc internally), pass true for this option. - range: false, + var index = -1, + length = props.length; - // If you want esprima not to throw exceptions when it encounters - // non-fatal errors, keep this option true. - tolerant: true, + while (++index < length) { + var key = props[index]; - // If you want to override the quotes used in string literals, specify - // either "single", "double", or "auto" here ("auto" will select the one - // which results in the shorter literal) - // Otherwise, double quotes are used. - quote: null, + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - // Controls the printing of trailing commas in object literals, - // array expressions and function parameters. - // - // This option could either be: - // * Boolean - enable/disable in all contexts (objects, arrays and function params). - // * Object - enable/disable per context. - // - // Example: - // trailingComma: { - // objects: true, - // arrays: true, - // parameters: false, - // } - trailingComma: false, + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} - // Controls the printing of spaces inside array brackets. - // See: http://eslint.org/docs/rules/array-bracket-spacing - arrayBracketSpacing: false, +module.exports = copyObject; - // Controls the printing of spaces inside object literals, - // destructuring assignments, and import/export specifiers. - // See: http://eslint.org/docs/rules/object-curly-spacing - objectCurlySpacing: true, +},{"./_assignValue":352,"./_baseAssignValue":356}],413:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + getSymbols = require('./_getSymbols'); - // If you want parenthesis to wrap single-argument arrow function parameter - // lists, pass true for this option. - arrowParensAlways: false, +/** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} - // There are 2 supported syntaxes (`,` and `;`) in Flow Object Types; - // The use of commas is in line with the more popular style and matches - // how objects are defined in JS, making it a bit more natural to write. - flowObjectCommas: true, -}, hasOwn = defaults.hasOwnProperty; +module.exports = copySymbols; -// Copy options and fill in default values. -exports.normalize = function(options) { - options = options || defaults; +},{"./_copyObject":412,"./_getSymbols":434}],414:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + getSymbolsIn = require('./_getSymbolsIn'); - function get(key) { - return hasOwn.call(options, key) - ? options[key] - : defaults[key]; - } +/** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); +} - return { - tabWidth: +get("tabWidth"), - useTabs: !!get("useTabs"), - reuseWhitespace: !!get("reuseWhitespace"), - lineTerminator: get("lineTerminator"), - wrapColumn: Math.max(get("wrapColumn"), 0), - sourceFileName: get("sourceFileName"), - sourceMapName: get("sourceMapName"), - sourceRoot: get("sourceRoot"), - inputSourceMap: get("inputSourceMap"), - parser: get("esprima") || get("parser"), - range: get("range"), - tolerant: get("tolerant"), - quote: get("quote"), - trailingComma: get("trailingComma"), - arrayBracketSpacing: get("arrayBracketSpacing"), - objectCurlySpacing: get("objectCurlySpacing"), - arrowParensAlways: get("arrowParensAlways"), - flowObjectCommas: get("flowObjectCommas"), - }; -}; +module.exports = copySymbolsIn; -},{"esprima":276,"os":800}],516:[function(require,module,exports){ -var assert = require("assert"); -var types = require("./types"); -var n = types.namedTypes; -var b = types.builders; -var isObject = types.builtInTypes.object; -var isArray = types.builtInTypes.array; -var isFunction = types.builtInTypes.function; -var Patcher = require("./patcher").Patcher; -var normalizeOptions = require("./options").normalize; -var fromString = require("./lines").fromString; -var attachComments = require("./comments").attach; -var util = require("./util"); +},{"./_copyObject":412,"./_getSymbolsIn":435}],415:[function(require,module,exports){ +var root = require('./_root'); -exports.parse = function parse(source, options) { - options = normalizeOptions(options); +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; - var lines = fromString(source, options); +module.exports = coreJsData; - var sourceWithoutTabs = lines.toString({ - tabWidth: options.tabWidth, - reuseWhitespace: false, - useTabs: false - }); +},{"./_root":475}],416:[function(require,module,exports){ +var baseRest = require('./_baseRest'), + isIterateeCall = require('./_isIterateeCall'); - var comments = []; - var program = options.parser.parse(sourceWithoutTabs, { - jsx: true, - loc: true, - locations: true, - range: options.range, - comment: true, - onComment: comments, - tolerant: options.tolerant, - ecmaVersion: 6, - sourceType: 'module' +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; }); +} - // If the source was empty, some parsers give loc.{start,end}.line - // values of 0, instead of the minimum of 1. - util.fixFaultyLocations(program, lines); +module.exports = createAssigner; - program.loc = program.loc || { - start: lines.firstPos(), - end: lines.lastPos() - }; +},{"./_baseRest":391,"./_isIterateeCall":449}],417:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'); - program.loc.lines = lines; - program.loc.indent = 0; +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); - // Expand the Program node's .loc to include all comments, since - // typically its .loc.start and .loc.end will coincide with those of the - // first and last statements, respectively, excluding any comments that - // fall outside that region. - var trueProgramLoc = util.getTrueLoc(program, lines); - program.loc.start = trueProgramLoc.start; - program.loc.end = trueProgramLoc.end; + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} - if (program.comments) { - comments = program.comments; - delete program.comments; - } +module.exports = createBaseEach; - // In order to ensure we reprint leading and trailing program comments, - // wrap the original Program node with a File node. - var file = program; - if (file.type === "Program") { - var file = b.file(program, options.sourceFileName || null); - file.loc = { - lines: lines, - indent: 0, - start: lines.firstPos(), - end: lines.lastPos() - }; - } else if (file.type === "File") { - program = file.program; - } +},{"./isArrayLike":512}],418:[function(require,module,exports){ +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; - // Passing file.program here instead of just file means that initial - // comments will be attached to program.body[0] instead of program. - attachComments( - comments, - program.body.length ? file.program : file, - lines - ); + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} - // Return a copy of the original AST so that any changes made may be - // compared to the original. - return new TreeCopier(lines).copy(file); -}; +module.exports = createBaseFor; -function TreeCopier(lines) { - assert.ok(this instanceof TreeCopier); - this.lines = lines; - this.indent = 0; +},{}],419:[function(require,module,exports){ +var baseIteratee = require('./_baseIteratee'), + isArrayLike = require('./isArrayLike'), + keys = require('./keys'); + +/** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ +function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; } -var TCp = TreeCopier.prototype; +module.exports = createFind; -TCp.copy = function(node) { - if (isArray.check(node)) { - return node.map(this.copy, this); - } +},{"./_baseIteratee":379,"./isArrayLike":512,"./keys":525}],420:[function(require,module,exports){ +var Set = require('./_Set'), + noop = require('./noop'), + setToArray = require('./_setToArray'); - if (!isObject.check(node)) { - return node; - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; - util.fixFaultyLocations(node, this.lines); +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); +}; - var copy = Object.create(Object.getPrototypeOf(node), { - original: { // Provide a link from the copy to the original. - value: node, - configurable: false, - enumerable: false, - writable: true - } - }); +module.exports = createSet; - var loc = node.loc; - var oldIndent = this.indent; - var newIndent = oldIndent; +},{"./_Set":333,"./_setToArray":478,"./noop":530}],421:[function(require,module,exports){ +var eq = require('./eq'); - if (loc) { - // When node is a comment, we set node.loc.indent to - // node.loc.start.column so that, when/if we print the comment by - // itself, we can strip that much whitespace from the left margin of - // the comment. This only really matters for multiline Block comments, - // but it doesn't hurt for Line comments. - if (node.type === "Block" || node.type === "Line" || - node.type === "CommentBlock" || node.type === "CommentLine" || - this.lines.isPrecededOnlyByWhitespace(loc.start)) { - newIndent = this.indent = loc.start.column; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - loc.lines = this.lines; - loc.indent = newIndent; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - var keys = Object.keys(node); - var keyCount = keys.length; - for (var i = 0; i < keyCount; ++i) { - var key = keys[i]; - if (key === "loc") { - copy[key] = node[key]; - } else if (key === "tokens" && - node.type === "File") { - // Preserve file.tokens (uncopied) in case client code cares about - // it, even though Recast ignores it when reprinting. - copy[key] = node[key]; - } else { - copy[key] = this.copy(node[key]); - } +/** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; } + return objValue; +} - this.indent = oldIndent; +module.exports = customDefaultsAssignIn; - return copy; -}; +},{"./eq":498}],422:[function(require,module,exports){ +var getNative = require('./_getNative'); -},{"./comments":511,"./lines":513,"./options":515,"./patcher":517,"./types":519,"./util":520,"assert":791}],517:[function(require,module,exports){ -var assert = require("assert"); -var linesModule = require("./lines"); -var types = require("./types"); -var getFieldValue = types.getFieldValue; -var Printable = types.namedTypes.Printable; -var Expression = types.namedTypes.Expression; -var ReturnStatement = types.namedTypes.ReturnStatement; -var SourceLocation = types.namedTypes.SourceLocation; -var util = require("./util"); -var comparePos = util.comparePos; -var FastPath = require("./fast-path"); -var isObject = types.builtInTypes.object; -var isArray = types.builtInTypes.array; -var isString = types.builtInTypes.string; -var riskyAdjoiningCharExp = /[0-9a-z_$]/i; +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); -function Patcher(lines) { - assert.ok(this instanceof Patcher); - assert.ok(lines instanceof linesModule.Lines); +module.exports = defineProperty; - var self = this, - replacements = []; +},{"./_getNative":431}],423:[function(require,module,exports){ +var SetCache = require('./_SetCache'), + arraySome = require('./_arraySome'), + cacheHas = require('./_cacheHas'); - self.replace = function(loc, lines) { - if (isString.check(lines)) - lines = linesModule.fromString(lines); +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - replacements.push({ - lines: lines, - start: loc.start, - end: loc.end - }); - }; +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; - self.get = function(loc) { - // If no location is provided, return the complete Lines object. - loc = loc || { - start: { line: 1, column: 0 }, - end: { line: lines.length, - column: lines.getLineLength(lines.length) } - }; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - var sliceFrom = loc.start, - toConcat = []; + stack.set(array, other); + stack.set(other, array); - function pushSlice(from, to) { - assert.ok(comparePos(from, to) <= 0); - toConcat.push(lines.slice(from, to)); - } + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; - replacements.sort(function(a, b) { - return comparePos(a.start, b.start); - }).forEach(function(rep) { - if (comparePos(sliceFrom, rep.start) > 0) { - // Ignore nested replacement ranges. - } else { - pushSlice(sliceFrom, rep.start); - toConcat.push(rep.lines); - sliceFrom = rep.end; + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); } - }); + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} - pushSlice(sliceFrom, loc.end); +module.exports = equalArrays; - return linesModule.concat(toConcat); - }; -} -exports.Patcher = Patcher; +},{"./_SetCache":334,"./_arraySome":350,"./_cacheHas":399}],424:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + Uint8Array = require('./_Uint8Array'), + eq = require('./eq'), + equalArrays = require('./_equalArrays'), + mapToArray = require('./_mapToArray'), + setToArray = require('./_setToArray'); -var Pp = Patcher.prototype; +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; -Pp.tryToReprintComments = function(newNode, oldNode, print) { - var patcher = this; +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; - if (!newNode.comments && - !oldNode.comments) { - // We were (vacuously) able to reprint all the comments! - return true; - } +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; - var newPath = FastPath.from(newNode); - var oldPath = FastPath.from(oldNode); +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - newPath.stack.push("comments", getSurroundingComments(newNode)); - oldPath.stack.push("comments", getSurroundingComments(oldNode)); +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; - var reprints = []; - var ableToReprintComments = - findArrayReprints(newPath, oldPath, reprints); + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; - // No need to pop anything from newPath.stack or oldPath.stack, since - // newPath and oldPath are fresh local variables. + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); - if (ableToReprintComments && reprints.length > 0) { - reprints.forEach(function(reprint) { - var oldComment = reprint.oldPath.getValue(); - assert.ok(oldComment.leading || oldComment.trailing); - patcher.replace( - oldComment.loc, - // Comments can't have .comments, so it doesn't matter - // whether we print with comments or without. - print(reprint.newPath).indentTail(oldComment.loc.indent) - ); - }); - } + case errorTag: + return object.name == other.name && object.message == other.message; - return ableToReprintComments; -}; + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); -// Get all comments that are either leading or trailing, ignoring any -// comments that occur inside node.loc. Returns an empty array for nodes -// with no leading or trailing comments. -function getSurroundingComments(node) { - var result = []; - if (node.comments && - node.comments.length > 0) { - node.comments.forEach(function(comment) { - if (comment.leading || comment.trailing) { - result.push(comment); - } - }); - } - return result; -} + case mapTag: + var convert = mapToArray; -Pp.deleteComments = function(node) { - if (!node.comments) { - return; - } + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); - var patcher = this; + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; - node.comments.forEach(function(comment) { - if (comment.leading) { - // Delete leading comments along with any trailing whitespace - // they might have. - patcher.replace({ - start: comment.loc.start, - end: node.loc.lines.skipSpaces( - comment.loc.end, false, false) - }, ""); + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; - } else if (comment.trailing) { - // Delete trailing comments along with any leading whitespace - // they might have. - patcher.replace({ - start: node.loc.lines.skipSpaces( - comment.loc.start, true, false), - end: comment.loc.end - }, ""); - } - }); -}; + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} -exports.getReprinter = function(path) { - assert.ok(path instanceof FastPath); +module.exports = equalByTag; - // Make sure that this path refers specifically to a Node, rather than - // some non-Node subproperty of a Node. - var node = path.getValue(); - if (!Printable.check(node)) - return; +},{"./_Symbol":336,"./_Uint8Array":337,"./_equalArrays":423,"./_mapToArray":465,"./_setToArray":478,"./eq":498}],425:[function(require,module,exports){ +var getAllKeys = require('./_getAllKeys'); - var orig = node.original; - var origLoc = orig && orig.loc; - var lines = origLoc && origLoc.lines; - var reprints = []; +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; - if (!lines || !findReprints(path, reprints)) - return; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - return function(print) { - var patcher = new Patcher(lines); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - reprints.forEach(function(reprint) { - var newNode = reprint.newPath.getValue(); - var oldNode = reprint.oldPath.getValue(); +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; - SourceLocation.assert(oldNode.loc, true); + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); - var needToPrintNewPathWithComments = - !patcher.tryToReprintComments(newNode, oldNode, print) + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; - if (needToPrintNewPathWithComments) { - // Since we were not able to preserve all leading/trailing - // comments, we delete oldNode's comments, print newPath - // with comments, and then patch the resulting lines where - // oldNode used to be. - patcher.deleteComments(oldNode); - } + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; - var newLines = print( - reprint.newPath, - needToPrintNewPathWithComments - ).indentTail(oldNode.loc.indent); + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} - var nls = needsLeadingSpace(lines, oldNode.loc, newLines); - var nts = needsTrailingSpace(lines, oldNode.loc, newLines); +module.exports = equalObjects; - // If we try to replace the argument of a ReturnStatement like - // return"asdf" with e.g. a literal null expression, we run - // the risk of ending up with returnnull, so we need to add an - // extra leading space in situations where that might - // happen. Likewise for "asdf"in obj. See #170. - if (nls || nts) { - var newParts = []; - nls && newParts.push(" "); - newParts.push(newLines); - nts && newParts.push(" "); - newLines = linesModule.concat(newParts); - } +},{"./_getAllKeys":427}],426:[function(require,module,exports){ +(function (global){ +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +module.exports = freeGlobal; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],427:[function(require,module,exports){ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbols = require('./_getSymbols'), + keys = require('./keys'); - patcher.replace(oldNode.loc, newLines); - }); +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} - // Recall that origLoc is the .loc of an ancestor node that is - // guaranteed to contain all the reprinted nodes and comments. - return patcher.get(origLoc).indentTail(-orig.loc.indent); - }; -}; +module.exports = getAllKeys; -// If the last character before oldLoc and the first character of newLines -// are both identifier characters, they must be separated by a space, -// otherwise they will most likely get fused together into a single token. -function needsLeadingSpace(oldLines, oldLoc, newLines) { - var posBeforeOldLoc = util.copyPos(oldLoc.start); +},{"./_baseGetAllKeys":366,"./_getSymbols":434,"./keys":525}],428:[function(require,module,exports){ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbolsIn = require('./_getSymbolsIn'), + keysIn = require('./keysIn'); - // The character just before the location occupied by oldNode. - var charBeforeOldLoc = - oldLines.prevPos(posBeforeOldLoc) && - oldLines.charAt(posBeforeOldLoc); +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); +} - // First character of the reprinted node. - var newFirstChar = newLines.charAt(newLines.firstPos()); +module.exports = getAllKeysIn; - return charBeforeOldLoc && - riskyAdjoiningCharExp.test(charBeforeOldLoc) && - newFirstChar && - riskyAdjoiningCharExp.test(newFirstChar); +},{"./_baseGetAllKeys":366,"./_getSymbolsIn":435,"./keysIn":526}],429:[function(require,module,exports){ +var isKeyable = require('./_isKeyable'); + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } -// If the last character of newLines and the first character after oldLoc -// are both identifier characters, they must be separated by a space, -// otherwise they will most likely get fused together into a single token. -function needsTrailingSpace(oldLines, oldLoc, newLines) { - // The character just after the location occupied by oldNode. - var charAfterOldLoc = oldLines.charAt(oldLoc.end); +module.exports = getMapData; - var newLastPos = newLines.lastPos(); +},{"./_isKeyable":451}],430:[function(require,module,exports){ +var isStrictComparable = require('./_isStrictComparable'), + keys = require('./keys'); - // Last character of the reprinted node. - var newLastChar = newLines.prevPos(newLastPos) && - newLines.charAt(newLastPos); +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; - return newLastChar && - riskyAdjoiningCharExp.test(newLastChar) && - charAfterOldLoc && - riskyAdjoiningCharExp.test(charAfterOldLoc); + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; } -function findReprints(newPath, reprints) { - var newNode = newPath.getValue(); - Printable.assert(newNode); +module.exports = getMatchData; - var oldNode = newNode.original; - Printable.assert(oldNode); +},{"./_isStrictComparable":454,"./keys":525}],431:[function(require,module,exports){ +var baseIsNative = require('./_baseIsNative'), + getValue = require('./_getValue'); - assert.deepEqual(reprints, []); +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} - if (newNode.type !== oldNode.type) { - return false; - } +module.exports = getNative; - var oldPath = new FastPath(oldNode); - var canReprint = findChildReprints(newPath, oldPath, reprints); +},{"./_baseIsNative":376,"./_getValue":437}],432:[function(require,module,exports){ +var overArg = require('./_overArg'); - if (!canReprint) { - // Make absolutely sure the calling code does not attempt to reprint - // any nodes. - reprints.length = 0; - } +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); - return canReprint; -} +module.exports = getPrototype; -function findAnyReprints(newPath, oldPath, reprints) { - var newNode = newPath.getValue(); - var oldNode = oldPath.getValue(); +},{"./_overArg":473}],433:[function(require,module,exports){ +var Symbol = require('./_Symbol'); - if (newNode === oldNode) - return true; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (isArray.check(newNode)) - return findArrayReprints(newPath, oldPath, reprints); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - if (isObject.check(newNode)) - return findObjectReprints(newPath, oldPath, reprints); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; - return false; -} +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; -function findArrayReprints(newPath, oldPath, reprints) { - var newNode = newPath.getValue(); - var oldNode = oldPath.getValue(); - isArray.assert(newNode); - var len = newNode.length; +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; - if (!(isArray.check(oldNode) && - oldNode.length === len)) - return false; + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} - for (var i = 0; i < len; ++i) { - newPath.stack.push(i, newNode[i]); - oldPath.stack.push(i, oldNode[i]); - var canReprint = findAnyReprints(newPath, oldPath, reprints); - newPath.stack.length -= 2; - oldPath.stack.length -= 2; - if (!canReprint) { - return false; - } + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; } - - return true; + } + return result; } -function findObjectReprints(newPath, oldPath, reprints) { - var newNode = newPath.getValue(); - isObject.assert(newNode); - - if (newNode.original === null) { - // If newNode.original node was set to null, reprint the node. - return false; - } +module.exports = getRawTag; - var oldNode = oldPath.getValue(); - if (!isObject.check(oldNode)) - return false; +},{"./_Symbol":336}],434:[function(require,module,exports){ +var arrayFilter = require('./_arrayFilter'), + stubArray = require('./stubArray'); - if (Printable.check(newNode)) { - if (!Printable.check(oldNode)) { - return false; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - // Here we need to decide whether the reprinted code for newNode - // is appropriate for patching into the location of oldNode. +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - if (newNode.type === oldNode.type) { - var childReprints = []; +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; - if (findChildReprints(newPath, oldPath, childReprints)) { - reprints.push.apply(reprints, childReprints); - } else if (oldNode.loc) { - // If we have no .loc information for oldNode, then we - // won't be able to reprint it. - reprints.push({ - oldPath: oldPath.copy(), - newPath: newPath.copy() - }); - } else { - return false; - } +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; - return true; - } +module.exports = getSymbols; - if (Expression.check(newNode) && - Expression.check(oldNode) && - // If we have no .loc information for oldNode, then we won't - // be able to reprint it. - oldNode.loc) { +},{"./_arrayFilter":343,"./stubArray":535}],435:[function(require,module,exports){ +var arrayPush = require('./_arrayPush'), + getPrototype = require('./_getPrototype'), + getSymbols = require('./_getSymbols'), + stubArray = require('./stubArray'); - // If both nodes are subtypes of Expression, then we should be - // able to fill the location occupied by the old node with - // code printed for the new node with no ill consequences. - reprints.push({ - oldPath: oldPath.copy(), - newPath: newPath.copy() - }); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; - return true; - } +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; +}; - // The nodes have different types, and at least one of the types - // is not a subtype of the Expression type, so we cannot safely - // assume the nodes are syntactically interchangeable. - return false; - } +module.exports = getSymbolsIn; - return findChildReprints(newPath, oldPath, reprints); -} +},{"./_arrayPush":348,"./_getPrototype":432,"./_getSymbols":434,"./stubArray":535}],436:[function(require,module,exports){ +var DataView = require('./_DataView'), + Map = require('./_Map'), + Promise = require('./_Promise'), + Set = require('./_Set'), + WeakMap = require('./_WeakMap'), + baseGetTag = require('./_baseGetTag'), + toSource = require('./_toSource'); -// This object is reused in hasOpeningParen and hasClosingParen to avoid -// having to allocate a temporary object. -var reusablePos = { line: 1, column: 0 }; -var nonSpaceExp = /\S/; +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]'; -function hasOpeningParen(oldPath) { - var oldNode = oldPath.getValue(); - var loc = oldNode.loc; - var lines = loc && loc.lines; +var dataViewTag = '[object DataView]'; - if (lines) { - var pos = reusablePos; - pos.line = loc.start.line; - pos.column = loc.start.column; +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); - while (lines.prevPos(pos)) { - var ch = lines.charAt(pos); +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; - if (ch === "(") { - // If we found an opening parenthesis but it occurred before - // the start of the original subtree for this reprinting, then - // we must not return true for hasOpeningParen(oldPath). - return comparePos(oldPath.getRootValue().loc.start, pos) <= 0; - } +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; - if (nonSpaceExp.test(ch)) { - return false; - } - } + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } } - - return false; + return result; + }; } -function hasClosingParen(oldPath) { - var oldNode = oldPath.getValue(); - var loc = oldNode.loc; - var lines = loc && loc.lines; +module.exports = getTag; - if (lines) { - var pos = reusablePos; - pos.line = loc.end.line; - pos.column = loc.end.column; +},{"./_DataView":327,"./_Map":330,"./_Promise":332,"./_Set":333,"./_WeakMap":338,"./_baseGetTag":367,"./_toSource":489}],437:[function(require,module,exports){ +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} - do { - var ch = lines.charAt(pos); +module.exports = getValue; - if (ch === ")") { - // If we found a closing parenthesis but it occurred after the - // end of the original subtree for this reprinting, then we - // must not return true for hasClosingParen(oldPath). - return comparePos(pos, oldPath.getRootValue().loc.end) <= 0; - } +},{}],438:[function(require,module,exports){ +var castPath = require('./_castPath'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'), + isLength = require('./isLength'), + toKey = require('./_toKey'); - if (nonSpaceExp.test(ch)) { - return false; - } +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = castPath(path, object); - } while (lines.nextPos(pos)); - } + var index = -1, + length = path.length, + result = false; - return false; + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); } -function hasParens(oldPath) { - // This logic can technically be fooled if the node has parentheses - // but there are comments intervening between the parentheses and the - // node. In such cases the node will be harmlessly wrapped in an - // additional layer of parentheses. - return hasOpeningParen(oldPath) && hasClosingParen(oldPath); -} +module.exports = hasPath; -function findChildReprints(newPath, oldPath, reprints) { - var newNode = newPath.getValue(); - var oldNode = oldPath.getValue(); +},{"./_castPath":400,"./_isIndex":448,"./_toKey":488,"./isArguments":510,"./isArray":511,"./isLength":517}],439:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); - isObject.assert(newNode); - isObject.assert(oldNode); +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} - if (newNode.original === null) { - // If newNode.original node was set to null, reprint the node. - return false; - } +module.exports = hashClear; - // If this type of node cannot come lexically first in its enclosing - // statement (e.g. a function expression or object literal), and it - // seems to be doing so, then the only way we can ignore this problem - // and save ourselves from falling back to the pretty printer is if an - // opening parenthesis happens to precede the node. For example, - // (function(){ ... }()); does not need to be reprinted, even though - // the FunctionExpression comes lexically first in the enclosing - // ExpressionStatement and fails the hasParens test, because the - // parent CallExpression passes the hasParens test. If we relied on - // the path.needsParens() && !hasParens(oldNode) check below, the - // absence of a closing parenthesis after the FunctionExpression would - // trigger pretty-printing unnecessarily. - if (!newPath.canBeFirstInStatement() && - newPath.firstInStatement() && - !hasOpeningParen(oldPath)) - return false; +},{"./_nativeCreate":468}],440:[function(require,module,exports){ +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} - // If this node needs parentheses and will not be wrapped with - // parentheses when reprinted, then return false to skip reprinting - // and let it be printed generically. - if (newPath.needsParens(true) && !hasParens(oldPath)) { - return false; - } +module.exports = hashDelete; - var keys = util.getUnionOfKeys(oldNode, newNode); +},{}],441:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); - if (oldNode.type === "File" || - newNode.type === "File") { - // Don't bother traversing file.tokens, an often very large array - // returned by Babylon, and useless for our purposes. - delete keys.tokens; - } +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - // Don't bother traversing .loc objects looking for reprintable nodes. - delete keys.loc; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var originalReprintCount = reprints.length; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - for (var k in keys) { - newPath.stack.push(k, types.getFieldValue(newNode, k)); - oldPath.stack.push(k, types.getFieldValue(oldNode, k)); - var canReprint = findAnyReprints(newPath, oldPath, reprints); - newPath.stack.length -= 2; - oldPath.stack.length -= 2; +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} - if (!canReprint) { - return false; - } - } +module.exports = hashGet; - // Return statements might end up running into ASI issues due to comments - // inserted deep within the tree, so reprint them if anything changed - // within them. - if (ReturnStatement.check(newPath.getNode()) && - reprints.length > originalReprintCount) { - return false; - } +},{"./_nativeCreate":468}],442:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); - return true; +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } -},{"./fast-path":512,"./lines":513,"./types":519,"./util":520,"assert":791}],518:[function(require,module,exports){ -var assert = require("assert"); -var sourceMap = require("source-map"); -var printComments = require("./comments").printComments; -var linesModule = require("./lines"); -var fromString = linesModule.fromString; -var concat = linesModule.concat; -var normalizeOptions = require("./options").normalize; -var getReprinter = require("./patcher").getReprinter; -var types = require("./types"); -var namedTypes = types.namedTypes; -var isString = types.builtInTypes.string; -var isObject = types.builtInTypes.object; -var FastPath = require("./fast-path"); -var util = require("./util"); +module.exports = hashHas; -function PrintResult(code, sourceMap) { - assert.ok(this instanceof PrintResult); +},{"./_nativeCreate":468}],443:[function(require,module,exports){ +var nativeCreate = require('./_nativeCreate'); - isString.assert(code); - this.code = code; +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - if (sourceMap) { - isObject.assert(sourceMap); - this.map = sourceMap; - } +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } -var PRp = PrintResult.prototype; -var warnedAboutToString = false; +module.exports = hashSet; -PRp.toString = function() { - if (!warnedAboutToString) { - console.warn( - "Deprecation warning: recast.print now returns an object with " + - "a .code property. You appear to be treating the object as a " + - "string, which might still work but is strongly discouraged." - ); +},{"./_nativeCreate":468}],444:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; - warnedAboutToString = true; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - return this.code; -}; +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); -var emptyPrintResult = new PrintResult(""); + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} -function Printer(originalOptions) { - assert.ok(this instanceof Printer); +module.exports = initCloneArray; - var explicitTabWidth = originalOptions && originalOptions.tabWidth; - var options = normalizeOptions(originalOptions); - assert.notStrictEqual(options, originalOptions); +},{}],445:[function(require,module,exports){ +var cloneArrayBuffer = require('./_cloneArrayBuffer'), + cloneDataView = require('./_cloneDataView'), + cloneMap = require('./_cloneMap'), + cloneRegExp = require('./_cloneRegExp'), + cloneSet = require('./_cloneSet'), + cloneSymbol = require('./_cloneSymbol'), + cloneTypedArray = require('./_cloneTypedArray'); - // It's common for client code to pass the same options into both - // recast.parse and recast.print, but the Printer doesn't need (and - // can be confused by) options.sourceFileName, so we null it out. - options.sourceFileName = null; +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; - function printWithComments(path) { - assert.ok(path instanceof FastPath); - return printComments(path, print); - } +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; - function print(path, includeComments) { - if (includeComments) - return printWithComments(path); +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); - assert.ok(path instanceof FastPath); + case boolTag: + case dateTag: + return new Ctor(+object); - if (!explicitTabWidth) { - var oldTabWidth = options.tabWidth; - var loc = path.getNode().loc; - if (loc && loc.lines && loc.lines.guessTabWidth) { - options.tabWidth = loc.lines.guessTabWidth(); - var lines = maybeReprint(path); - options.tabWidth = oldTabWidth; - return lines; - } - } + case dataViewTag: + return cloneDataView(object, isDeep); - return maybeReprint(path); - } + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); - function maybeReprint(path) { - var reprinter = getReprinter(path); - if (reprinter) { - // Since the print function that we pass to the reprinter will - // be used to print "new" nodes, it's tempting to think we - // should pass printRootGenerically instead of print, to avoid - // calling maybeReprint again, but that would be a mistake - // because the new nodes might not be entirely new, but merely - // moved from elsewhere in the AST. The print function is the - // right choice because it gives us the opportunity to reprint - // such nodes using their original source. - return maybeAddParens(path, reprinter(print)); - } - return printRootGenerically(path); - } + case mapTag: + return cloneMap(object, isDeep, cloneFunc); - // Print the root node generically, but then resume reprinting its - // children non-generically. - function printRootGenerically(path, includeComments) { - return includeComments - ? printComments(path, printRootGenerically) - : genericPrint(path, options, printWithComments); - } + case numberTag: + case stringTag: + return new Ctor(object); - // Print the entire AST generically. - function printGenerically(path) { - return genericPrint(path, options, printGenerically); - } + case regexpTag: + return cloneRegExp(object); - this.print = function(ast) { - if (!ast) { - return emptyPrintResult; - } + case setTag: + return cloneSet(object, isDeep, cloneFunc); - var lines = print(FastPath.from(ast), true); + case symbolTag: + return cloneSymbol(object); + } +} - return new PrintResult( - lines.toString(options), - util.composeSourceMaps( - options.inputSourceMap, - lines.getSourceMap( - options.sourceMapName, - options.sourceRoot - ) - ) - ); - }; +module.exports = initCloneByTag; - this.printGenerically = function(ast) { - if (!ast) { - return emptyPrintResult; - } +},{"./_cloneArrayBuffer":401,"./_cloneDataView":403,"./_cloneMap":404,"./_cloneRegExp":405,"./_cloneSet":406,"./_cloneSymbol":407,"./_cloneTypedArray":408}],446:[function(require,module,exports){ +var baseCreate = require('./_baseCreate'), + getPrototype = require('./_getPrototype'), + isPrototype = require('./_isPrototype'); - var path = FastPath.from(ast); - var oldReuseWhitespace = options.reuseWhitespace; +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} - // Do not reuse whitespace (or anything else, for that matter) - // when printing generically. - options.reuseWhitespace = false; +module.exports = initCloneObject; - // TODO Allow printing of comments? - var pr = new PrintResult(printGenerically(path).toString(options)); - options.reuseWhitespace = oldReuseWhitespace; - return pr; - }; +},{"./_baseCreate":359,"./_getPrototype":432,"./_isPrototype":453}],447:[function(require,module,exports){ +var Symbol = require('./_Symbol'), + isArguments = require('./isArguments'), + isArray = require('./isArray'); + +/** Built-in value references. */ +var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } -exports.Printer = Printer; +module.exports = isFlattenable; -function maybeAddParens(path, lines) { - return path.needsParens() ? concat(["(", lines, ")"]) : lines; +},{"./_Symbol":336,"./isArguments":510,"./isArray":511}],448:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); } -function genericPrint(path, options, printPath) { - assert.ok(path instanceof FastPath); +module.exports = isIndex; - var node = path.getValue(); - var parts = []; - var needsParens = false; - var linesWithoutParens = - genericPrintNoParens(path, options, printPath); +},{}],449:[function(require,module,exports){ +var eq = require('./eq'), + isArrayLike = require('./isArrayLike'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'); - if (! node || linesWithoutParens.isEmpty()) { - return linesWithoutParens; - } +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} - if (node.decorators && - node.decorators.length > 0 && - // If the parent node is an export declaration, it will be - // responsible for printing node.decorators. - ! util.getParentExportDeclaration(path)) { +module.exports = isIterateeCall; - path.each(function(decoratorPath) { - parts.push(printPath(decoratorPath), "\n"); - }, "decorators"); +},{"./_isIndex":448,"./eq":498,"./isArrayLike":512,"./isObject":518}],450:[function(require,module,exports){ +var isArray = require('./isArray'), + isSymbol = require('./isSymbol'); - } else if (util.isExportDeclaration(node) && - node.declaration && - node.declaration.decorators) { - // Export declarations are responsible for printing any decorators - // that logically apply to node.declaration. - path.each(function(decoratorPath) { - parts.push(printPath(decoratorPath), "\n"); - }, "declaration", "decorators"); +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; - } else { - // Nodes with decorators can't have parentheses, so we can avoid - // computing path.needsParens() except in this case. - needsParens = path.needsParens(); - } +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} - if (needsParens) { - parts.unshift("("); - } +module.exports = isKey; - parts.push(linesWithoutParens); +},{"./isArray":511,"./isSymbol":523}],451:[function(require,module,exports){ +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} - if (needsParens) { - parts.push(")"); - } +module.exports = isKeyable; - return concat(parts); +},{}],452:[function(require,module,exports){ +var coreJsData = require('./_coreJsData'); + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); } -function genericPrintNoParens(path, options, print) { - var n = path.getValue(); +module.exports = isMasked; - if (!n) { - return fromString(""); - } +},{"./_coreJsData":415}],453:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (typeof n === "string") { - return fromString(n, options); - } +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - namedTypes.Printable.assert(n); + return value === proto; +} - var parts = []; +module.exports = isPrototype; - switch (n.type) { - case "File": - return path.call(print, "program"); +},{}],454:[function(require,module,exports){ +var isObject = require('./isObject'); - case "Program": - // Babel 6 - if (n.directives) { - path.each(function(childPath) { - parts.push(print(childPath), ";\n"); - }, "directives"); - } +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} - parts.push(path.call(function(bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body")); +module.exports = isStrictComparable; - return concat(parts); +},{"./isObject":518}],455:[function(require,module,exports){ +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} - case "Noop": // Babel extension. - case "EmptyStatement": - return fromString(""); +module.exports = listCacheClear; - case "ExpressionStatement": - return concat([path.call(print, "expression"), ";"]); +},{}],456:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); - case "ParenthesizedExpression": // Babel extension. - return concat(["(", path.call(print, "expression"), ")"]); +/** Used for built-in method references. */ +var arrayProto = Array.prototype; - case "BinaryExpression": - case "LogicalExpression": - case "AssignmentExpression": - return fromString(" ").join([ - path.call(print, "left"), - n.operator, - path.call(print, "right") - ]); +/** Built-in value references. */ +var splice = arrayProto.splice; - case "AssignmentPattern": - return concat([ - path.call(print, "left"), - " = ", - path.call(print, "right") - ]); +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - case "MemberExpression": - parts.push(path.call(print, "object")); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} - var property = path.call(print, "property"); - if (n.computed) { - parts.push("[", property, "]"); - } else { - parts.push(".", property); - } +module.exports = listCacheDelete; - return concat(parts); +},{"./_assocIndexOf":353}],457:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); - case "MetaProperty": - return concat([ - path.call(print, "meta"), - ".", - path.call(print, "property") - ]); +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - case "BindExpression": - if (n.object) { - parts.push(path.call(print, "object")); - } + return index < 0 ? undefined : data[index][1]; +} - parts.push("::", path.call(print, "callee")); +module.exports = listCacheGet; - return concat(parts); +},{"./_assocIndexOf":353}],458:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); - case "Path": - return fromString(".").join(n.body); +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} - case "Identifier": - return concat([ - fromString(n.name, options), - path.call(print, "typeAnnotation") - ]); +module.exports = listCacheHas; - case "SpreadElement": - case "SpreadElementPattern": - case "RestProperty": // Babel 6 for ObjectPattern - case "SpreadProperty": - case "SpreadPropertyPattern": - case "RestElement": - return concat(["...", path.call(print, "argument")]); +},{"./_assocIndexOf":353}],459:[function(require,module,exports){ +var assocIndexOf = require('./_assocIndexOf'); - case "FunctionDeclaration": - case "FunctionExpression": - if (n.async) - parts.push("async "); +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - parts.push("function"); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} - if (n.generator) - parts.push("*"); +module.exports = listCacheSet; - if (n.id) { - parts.push( - " ", - path.call(print, "id"), - path.call(print, "typeParameters") - ); - } +},{"./_assocIndexOf":353}],460:[function(require,module,exports){ +var Hash = require('./_Hash'), + ListCache = require('./_ListCache'), + Map = require('./_Map'); - parts.push( - "(", - printFunctionParams(path, options, print), - ")", - path.call(print, "returnType"), - " ", - path.call(print, "body") - ); +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} - return concat(parts); +module.exports = mapCacheClear; - case "ArrowFunctionExpression": - if (n.async) - parts.push("async "); +},{"./_Hash":328,"./_ListCache":329,"./_Map":330}],461:[function(require,module,exports){ +var getMapData = require('./_getMapData'); - if (n.typeParameters) { - parts.push(path.call(print, "typeParameters")); - } +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} - if ( - !options.arrowParensAlways && - n.params.length === 1 && - !n.rest && - n.params[0].type === 'Identifier' && - !n.params[0].typeAnnotation && - !n.returnType - ) { - parts.push(path.call(print, "params", 0)); - } else { - parts.push( - "(", - printFunctionParams(path, options, print), - ")", - path.call(print, "returnType") - ); - } +module.exports = mapCacheDelete; - parts.push(" => ", path.call(print, "body")); +},{"./_getMapData":429}],462:[function(require,module,exports){ +var getMapData = require('./_getMapData'); - return concat(parts); +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} - case "MethodDefinition": - if (n.static) { - parts.push("static "); - } +module.exports = mapCacheGet; - parts.push(printMethod(path, options, print)); +},{"./_getMapData":429}],463:[function(require,module,exports){ +var getMapData = require('./_getMapData'); - return concat(parts); +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} - case "YieldExpression": - parts.push("yield"); +module.exports = mapCacheHas; - if (n.delegate) - parts.push("*"); +},{"./_getMapData":429}],464:[function(require,module,exports){ +var getMapData = require('./_getMapData'); - if (n.argument) - parts.push(" ", path.call(print, "argument")); +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; - return concat(parts); + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} - case "AwaitExpression": - parts.push("await"); +module.exports = mapCacheSet; - if (n.all) - parts.push("*"); +},{"./_getMapData":429}],465:[function(require,module,exports){ +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); - if (n.argument) - parts.push(" ", path.call(print, "argument")); + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} - return concat(parts); +module.exports = mapToArray; - case "ModuleDeclaration": - parts.push("module", path.call(print, "id")); +},{}],466:[function(require,module,exports){ +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} - if (n.source) { - assert.ok(!n.body); - parts.push("from", path.call(print, "source")); - } else { - parts.push(path.call(print, "body")); - } +module.exports = matchesStrictComparable; - return fromString(" ").join(parts); +},{}],467:[function(require,module,exports){ +var memoize = require('./memoize'); - case "ImportSpecifier": - if (n.imported) { - parts.push(path.call(print, "imported")); - if (n.local && - n.local.name !== n.imported.name) { - parts.push(" as ", path.call(print, "local")); - } - } else if (n.id) { - parts.push(path.call(print, "id")); - if (n.name) { - parts.push(" as ", path.call(print, "name")); - } - } +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; - return concat(parts); +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); - case "ExportSpecifier": - if (n.local) { - parts.push(path.call(print, "local")); - if (n.exported && - n.exported.name !== n.local.name) { - parts.push(" as ", path.call(print, "exported")); - } - } else if (n.id) { - parts.push(path.call(print, "id")); - if (n.name) { - parts.push(" as ", path.call(print, "name")); - } - } + var cache = result.cache; + return result; +} - return concat(parts); +module.exports = memoizeCapped; - case "ExportBatchSpecifier": - return fromString("*"); +},{"./memoize":528}],468:[function(require,module,exports){ +var getNative = require('./_getNative'); - case "ImportNamespaceSpecifier": - parts.push("* as "); - if (n.local) { - parts.push(path.call(print, "local")); - } else if (n.id) { - parts.push(path.call(print, "id")); - } - return concat(parts); +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); - case "ImportDefaultSpecifier": - if (n.local) { - return path.call(print, "local"); - } - return path.call(print, "id"); +module.exports = nativeCreate; - case "ExportDeclaration": - case "ExportDefaultDeclaration": - case "ExportNamedDeclaration": - return printExportDeclaration(path, options, print); +},{"./_getNative":431}],469:[function(require,module,exports){ +var overArg = require('./_overArg'); - case "ExportAllDeclaration": - parts.push("export *"); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); - if (n.exported) { - parts.push(" as ", path.call(print, "exported")); - } +module.exports = nativeKeys; - parts.push( - " from ", - path.call(print, "source") - ); +},{"./_overArg":473}],470:[function(require,module,exports){ +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} - return concat(parts); +module.exports = nativeKeysIn; - case "ExportNamespaceSpecifier": - return concat(["* as ", path.call(print, "exported")]); +},{}],471:[function(require,module,exports){ +var freeGlobal = require('./_freeGlobal'); - case "ExportDefaultSpecifier": - return path.call(print, "exported"); +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - case "Import": - return fromString("import", options); +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - case "ImportDeclaration": - parts.push("import "); +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; - if (n.importKind && n.importKind !== "value") { - parts.push(n.importKind + " "); - } +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; - if (n.specifiers && - n.specifiers.length > 0) { +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); - var foundImportSpecifier = false; +module.exports = nodeUtil; - path.each(function(specifierPath) { - var i = specifierPath.getName(); - if (i > 0) { - parts.push(", "); - } +},{"./_freeGlobal":426}],472:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var value = specifierPath.getValue(); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; - if (namedTypes.ImportDefaultSpecifier.check(value) || - namedTypes.ImportNamespaceSpecifier.check(value)) { - assert.strictEqual(foundImportSpecifier, false); - } else { - namedTypes.ImportSpecifier.assert(value); - if (!foundImportSpecifier) { - foundImportSpecifier = true; - parts.push( - options.objectCurlySpacing ? "{ " : "{" - ); - } - } +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} - parts.push(print(specifierPath)); - }, "specifiers"); +module.exports = objectToString; - if (foundImportSpecifier) { - parts.push( - options.objectCurlySpacing ? " }" : "}" - ); - } +},{}],473:[function(require,module,exports){ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - parts.push(" from "); - } +module.exports = overArg; - parts.push(path.call(print, "source"), ";"); +},{}],474:[function(require,module,exports){ +var apply = require('./_apply'); - return concat(parts); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - case "BlockStatement": - var naked = path.call(function(bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body"); +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} - if (naked.isEmpty()) { - if (!n.directives || n.directives.length === 0) { - return fromString("{}"); - } - } +module.exports = overRest; - parts.push("{\n"); - // Babel 6 - if (n.directives) { - path.each(function(childPath) { - parts.push( - print(childPath).indent(options.tabWidth), - ";", - n.directives.length > 1 || !naked.isEmpty() ? "\n" : "" - ); - }, "directives"); - } - parts.push(naked.indent(options.tabWidth)); - parts.push("\n}"); +},{"./_apply":341}],475:[function(require,module,exports){ +var freeGlobal = require('./_freeGlobal'); - return concat(parts); +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - case "ReturnStatement": - parts.push("return"); +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - if (n.argument) { - var argLines = path.call(print, "argument"); - if (argLines.startsWithComment() || - (argLines.length > 1 && - namedTypes.JSXElement && - namedTypes.JSXElement.check(n.argument) - )) { - parts.push( - " (\n", - argLines.indent(options.tabWidth), - "\n)" - ); - } else { - parts.push(" ", argLines); - } - } +module.exports = root; - parts.push(";"); +},{"./_freeGlobal":426}],476:[function(require,module,exports){ +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - return concat(parts); +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} - case "CallExpression": - return concat([ - path.call(print, "callee"), - printArgumentsList(path, options, print) - ]); +module.exports = setCacheAdd; - case "ObjectExpression": - case "ObjectPattern": - case "ObjectTypeAnnotation": - var allowBreak = false; - var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; - var separator = options.flowObjectCommas ? "," : (isTypeAnnotation ? ";" : ","); - var fields = []; +},{}],477:[function(require,module,exports){ +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} - if (isTypeAnnotation) { - fields.push("indexers", "callProperties"); - } +module.exports = setCacheHas; - fields.push("properties"); +},{}],478:[function(require,module,exports){ +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); - var len = 0; - fields.forEach(function(field) { - len += n[field].length; - }); + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} - var oneLine = (isTypeAnnotation && len === 1) || len === 0; - var leftBrace = n.exact ? "{|" : "{"; - var rightBrace = n.exact ? "|}" : "}"; - parts.push(oneLine ? leftBrace : leftBrace + "\n"); - var leftBraceIndex = parts.length - 1; +module.exports = setToArray; - var i = 0; - fields.forEach(function(field) { - path.each(function(childPath) { - var lines = print(childPath); +},{}],479:[function(require,module,exports){ +var baseSetToString = require('./_baseSetToString'), + shortOut = require('./_shortOut'); - if (!oneLine) { - lines = lines.indent(options.tabWidth); - } +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); - var multiLine = !isTypeAnnotation && lines.length > 1; - if (multiLine && allowBreak) { - // Similar to the logic for BlockStatement. - parts.push("\n"); - } +module.exports = setToString; - parts.push(lines); +},{"./_baseSetToString":392,"./_shortOut":480}],480:[function(require,module,exports){ +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; - if (i < len - 1) { - // Add an extra line break if the previous object property - // had a multi-line value. - parts.push(separator + (multiLine ? "\n\n" : "\n")); - allowBreak = !multiLine; - } else if (len !== 1 && isTypeAnnotation) { - parts.push(separator); - } else if (!oneLine && util.isTrailingCommaEnabled(options, "objects")) { - parts.push(separator); - } - i++; - }, field); - }); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; - parts.push(oneLine ? rightBrace : "\n" + rightBrace); +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; - if (i !== 0 && oneLine && options.objectCurlySpacing) { - parts[leftBraceIndex] = leftBrace + " "; - parts[parts.length - 1] = " " + rightBrace; - } + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); - return concat(parts); + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} - case "PropertyPattern": - return concat([ - path.call(print, "key"), - ": ", - path.call(print, "pattern") - ]); +module.exports = shortOut; - case "ObjectProperty": // Babel 6 - case "Property": // Non-standard AST node type. - if (n.method || n.kind === "get" || n.kind === "set") { - return printMethod(path, options, print); - } +},{}],481:[function(require,module,exports){ +var ListCache = require('./_ListCache'); - var key = path.call(print, "key"); - if (n.computed) { - parts.push("[", key, "]"); - } else { - parts.push(key); - } +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} - if (! n.shorthand) { - parts.push(": ", path.call(print, "value")); - } +module.exports = stackClear; - return concat(parts); +},{"./_ListCache":329}],482:[function(require,module,exports){ +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); - case "ClassMethod": // Babel 6 - if (n.static) { - parts.push("static "); - } + this.size = data.size; + return result; +} - return concat([parts, printObjectMethod(path, options, print)]); +module.exports = stackDelete; - case "ObjectMethod": // Babel 6 - return printObjectMethod(path, options, print); +},{}],483:[function(require,module,exports){ +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} - case "Decorator": - return concat(["@", path.call(print, "expression")]); +module.exports = stackGet; - case "ArrayExpression": - case "ArrayPattern": - var elems = n.elements, - len = elems.length; +},{}],484:[function(require,module,exports){ +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} - var printed = path.map(print, "elements"); - var joined = fromString(", ").join(printed); - var oneLine = joined.getLineLength(1) <= options.wrapColumn; - if (oneLine) { - if (options.arrayBracketSpacing) { - parts.push("[ "); - } else { - parts.push("["); - } - } else { - parts.push("[\n"); - } +module.exports = stackHas; - path.each(function(elemPath) { - var i = elemPath.getName(); - var elem = elemPath.getValue(); - if (!elem) { - // If the array expression ends with a hole, that hole - // will be ignored by the interpreter, but if it ends with - // two (or more) holes, we need to write out two (or more) - // commas so that the resulting code is interpreted with - // both (all) of the holes. - parts.push(","); - } else { - var lines = printed[i]; - if (oneLine) { - if (i > 0) - parts.push(" "); - } else { - lines = lines.indent(options.tabWidth); - } - parts.push(lines); - if (i < len - 1 || (!oneLine && util.isTrailingCommaEnabled(options, "arrays"))) - parts.push(","); - if (!oneLine) - parts.push("\n"); - } - }, "elements"); +},{}],485:[function(require,module,exports){ +var ListCache = require('./_ListCache'), + Map = require('./_Map'), + MapCache = require('./_MapCache'); - if (oneLine && options.arrayBracketSpacing) { - parts.push(" ]"); - } else { - parts.push("]"); - } +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; - return concat(parts); +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} - case "SequenceExpression": - return fromString(", ").join(path.map(print, "expressions")); +module.exports = stackSet; - case "ThisExpression": - return fromString("this"); +},{"./_ListCache":329,"./_Map":330,"./_MapCache":331}],486:[function(require,module,exports){ +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; - case "Super": - return fromString("super"); + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} - case "NullLiteral": // Babel 6 Literal split - return fromString("null"); +module.exports = strictIndexOf; - case "RegExpLiteral": // Babel 6 Literal split - return fromString(n.extra.raw); +},{}],487:[function(require,module,exports){ +var memoizeCapped = require('./_memoizeCapped'); - case "BooleanLiteral": // Babel 6 Literal split - case "NumericLiteral": // Babel 6 Literal split - case "StringLiteral": // Babel 6 Literal split - case "Literal": - if (typeof n.value !== "string") - return fromString(n.value, options); +/** Used to match property names within property paths. */ +var reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - return fromString(nodeStr(n.value, options), options); +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; - case "Directive": // Babel 6 - return path.call(print, "value"); +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoizeCapped(function(string) { + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); - case "DirectiveLiteral": // Babel 6 - return fromString(nodeStr(n.value, options)); +module.exports = stringToPath; - case "ModuleSpecifier": - if (n.local) { - throw new Error( - "The ESTree ModuleSpecifier type should be abstract" - ); - } +},{"./_memoizeCapped":467}],488:[function(require,module,exports){ +var isSymbol = require('./isSymbol'); - // The Esprima ModuleSpecifier type is just a string-valued - // Literal identifying the imported-from module. - return fromString(nodeStr(n.value, options), options); +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; - case "UnaryExpression": - parts.push(n.operator); - if (/[a-z]$/.test(n.operator)) - parts.push(" "); - parts.push(path.call(print, "argument")); - return concat(parts); +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} - case "UpdateExpression": - parts.push( - path.call(print, "argument"), - n.operator - ); +module.exports = toKey; - if (n.prefix) - parts.reverse(); +},{"./isSymbol":523}],489:[function(require,module,exports){ +/** Used for built-in method references. */ +var funcProto = Function.prototype; - return concat(parts); +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - case "ConditionalExpression": - return concat([ - "(", path.call(print, "test"), - " ? ", path.call(print, "consequent"), - " : ", path.call(print, "alternate"), ")" - ]); +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} - case "NewExpression": - parts.push("new ", path.call(print, "callee")); - var args = n.arguments; - if (args) { - parts.push(printArgumentsList(path, options, print)); - } +module.exports = toSource; - return concat(parts); +},{}],490:[function(require,module,exports){ +var assignValue = require('./_assignValue'), + copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + isArrayLike = require('./isArrayLike'), + isPrototype = require('./_isPrototype'), + keys = require('./keys'); - case "VariableDeclaration": - parts.push(n.kind, " "); - var maxLen = 0; - var printed = path.map(function(childPath) { - var lines = print(childPath); - maxLen = Math.max(lines.length, maxLen); - return lines; - }, "declarations"); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (maxLen === 1) { - parts.push(fromString(", ").join(printed)); - } else if (printed.length > 1 ) { - parts.push( - fromString(",\n").join(printed) - .indentTail(n.kind.length + 1) - ); - } else { - parts.push(printed[0]); - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - // We generally want to terminate all variable declarations with a - // semicolon, except when they are children of for loops. - var parentNode = path.getParentNode(); - if (!namedTypes.ForStatement.check(parentNode) && - !namedTypes.ForInStatement.check(parentNode) && - !(namedTypes.ForOfStatement && - namedTypes.ForOfStatement.check(parentNode)) && - !(namedTypes.ForAwaitStatement && - namedTypes.ForAwaitStatement.check(parentNode))) { - parts.push(";"); - } +/** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ +var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } +}); - return concat(parts); +module.exports = assign; - case "VariableDeclarator": - return n.init ? fromString(" = ").join([ - path.call(print, "id"), - path.call(print, "init") - ]) : path.call(print, "id"); +},{"./_assignValue":352,"./_copyObject":412,"./_createAssigner":416,"./_isPrototype":453,"./isArrayLike":512,"./keys":525}],491:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); - case "WithStatement": - return concat([ - "with (", - path.call(print, "object"), - ") ", - path.call(print, "body") - ]); +/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ +var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); +}); - case "IfStatement": - var con = adjustClause(path.call(print, "consequent"), options), - parts = ["if (", path.call(print, "test"), ")", con]; +module.exports = assignIn; - if (n.alternate) - parts.push( - endsWithBrace(con) ? " else" : "\nelse", - adjustClause(path.call(print, "alternate"), options)); +},{"./_copyObject":412,"./_createAssigner":416,"./keysIn":526}],492:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); - return concat(parts); +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); - case "ForStatement": - // TODO Get the for (;;) case right. - var init = path.call(print, "init"), - sep = init.length > 1 ? ";\n" : "; ", - forParen = "for (", - indented = fromString(sep).join([ - init, - path.call(print, "test"), - path.call(print, "update") - ]).indentTail(forParen.length), - head = concat([forParen, indented, ")"]), - clause = adjustClause(path.call(print, "body"), options), - parts = [head]; +module.exports = assignInWith; - if (head.length > 1) { - parts.push("\n"); - clause = clause.trimLeft(); - } +},{"./_copyObject":412,"./_createAssigner":416,"./keysIn":526}],493:[function(require,module,exports){ +var baseClone = require('./_baseClone'); - parts.push(clause); +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG = 4; - return concat(parts); +/** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ +function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); +} - case "WhileStatement": - return concat([ - "while (", - path.call(print, "test"), - ")", - adjustClause(path.call(print, "body"), options) - ]); +module.exports = clone; - case "ForInStatement": - // Note: esprima can't actually parse "for each (". - return concat([ - n.each ? "for each (" : "for (", - path.call(print, "left"), - " in ", - path.call(print, "right"), - ")", - adjustClause(path.call(print, "body"), options) - ]); +},{"./_baseClone":358}],494:[function(require,module,exports){ +var baseClone = require('./_baseClone'); - case "ForOfStatement": - return concat([ - "for (", - path.call(print, "left"), - " of ", - path.call(print, "right"), - ")", - adjustClause(path.call(print, "body"), options) - ]); +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; - case "ForAwaitStatement": - return concat([ - "for await (", - path.call(print, "left"), - " of ", - path.call(print, "right"), - ")", - adjustClause(path.call(print, "body"), options) - ]); +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); +} - case "DoWhileStatement": - var doBody = concat([ - "do", - adjustClause(path.call(print, "body"), options) - ]), parts = [doBody]; +module.exports = cloneDeep; - if (endsWithBrace(doBody)) - parts.push(" while"); - else - parts.push("\nwhile"); +},{"./_baseClone":358}],495:[function(require,module,exports){ +var baseClone = require('./_baseClone'); - parts.push(" (", path.call(print, "test"), ");"); +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; - return concat(parts); +/** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ +function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); +} - case "DoExpression": - var statements = path.call(function(bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body"); +module.exports = cloneDeepWith; - return concat([ - "do {\n", - statements.indent(options.tabWidth), - "\n}" - ]); +},{"./_baseClone":358}],496:[function(require,module,exports){ +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} - case "BreakStatement": - parts.push("break"); - if (n.label) - parts.push(" ", path.call(print, "label")); - parts.push(";"); - return concat(parts); +module.exports = constant; - case "ContinueStatement": - parts.push("continue"); - if (n.label) - parts.push(" ", path.call(print, "label")); - parts.push(";"); - return concat(parts); +},{}],497:[function(require,module,exports){ +var apply = require('./_apply'), + assignInWith = require('./assignInWith'), + baseRest = require('./_baseRest'), + customDefaultsAssignIn = require('./_customDefaultsAssignIn'); - case "LabeledStatement": - return concat([ - path.call(print, "label"), - ":\n", - path.call(print, "body") - ]); +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(args) { + args.push(undefined, customDefaultsAssignIn); + return apply(assignInWith, undefined, args); +}); - case "TryStatement": - parts.push( - "try ", - path.call(print, "block") - ); +module.exports = defaults; - if (n.handler) { - parts.push(" ", path.call(print, "handler")); - } else if (n.handlers) { - path.each(function(handlerPath) { - parts.push(" ", print(handlerPath)); - }, "handlers"); - } +},{"./_apply":341,"./_baseRest":391,"./_customDefaultsAssignIn":421,"./assignInWith":492}],498:[function(require,module,exports){ +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - if (n.finalizer) { - parts.push(" finally ", path.call(print, "finalizer")); - } +module.exports = eq; - return concat(parts); +},{}],499:[function(require,module,exports){ +var toString = require('./toString'); - case "CatchClause": - parts.push("catch (", path.call(print, "param")); +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - if (n.guard) - // Note: esprima does not recognize conditional catch clauses. - parts.push(" if ", path.call(print, "guard")); +/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ +function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; +} - parts.push(") ", path.call(print, "body")); +module.exports = escapeRegExp; - return concat(parts); +},{"./toString":541}],500:[function(require,module,exports){ +module.exports = require('./assignIn'); - case "ThrowStatement": - return concat(["throw ", path.call(print, "argument"), ";"]); +},{"./assignIn":491}],501:[function(require,module,exports){ +var createFind = require('./_createFind'), + findIndex = require('./findIndex'); - case "SwitchStatement": - return concat([ - "switch (", - path.call(print, "discriminant"), - ") {\n", - fromString("\n").join(path.map(print, "cases")), - "\n}" - ]); +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ +var find = createFind(findIndex); - // Note: ignoring n.lexical because it has no printing consequences. +module.exports = find; - case "SwitchCase": - if (n.test) - parts.push("case ", path.call(print, "test"), ":"); - else - parts.push("default:"); +},{"./_createFind":419,"./findIndex":502}],502:[function(require,module,exports){ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); - if (n.consequent.length > 0) { - parts.push("\n", path.call(function(consequentPath) { - return printStatementSequence(consequentPath, options, print); - }, "consequent").indent(options.tabWidth)); - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - return concat(parts); +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ +function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); +} - case "DebuggerStatement": - return fromString("debugger;"); +module.exports = findIndex; - // JSX extensions below. +},{"./_baseFindIndex":361,"./_baseIteratee":379,"./toInteger":538}],503:[function(require,module,exports){ +var createFind = require('./_createFind'), + findLastIndex = require('./findLastIndex'); - case "JSXAttribute": - parts.push(path.call(print, "name")); - if (n.value) - parts.push("=", path.call(print, "value")); - return concat(parts); +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(findLastIndex); - case "JSXIdentifier": - return fromString(n.name, options); +module.exports = findLast; - case "JSXNamespacedName": - return fromString(":").join([ - path.call(print, "namespace"), - path.call(print, "name") - ]); +},{"./_createFind":419,"./findLastIndex":504}],504:[function(require,module,exports){ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); - case "JSXMemberExpression": - return fromString(".").join([ - path.call(print, "object"), - path.call(print, "property") - ]); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; - case "JSXSpreadAttribute": - return concat(["{...", path.call(print, "argument"), "}"]); +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ +function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index, true); +} - case "JSXExpressionContainer": - return concat(["{", path.call(print, "expression"), "}"]); +module.exports = findLastIndex; - case "JSXElement": - var openingLines = path.call(print, "openingElement"); +},{"./_baseFindIndex":361,"./_baseIteratee":379,"./toInteger":538}],505:[function(require,module,exports){ +var baseGet = require('./_baseGet'); - if (n.openingElement.selfClosing) { - assert.ok(!n.closingElement); - return openingLines; - } +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} - var childLines = concat( - path.map(function(childPath) { - var child = childPath.getValue(); +module.exports = get; - if (namedTypes.Literal.check(child) && - typeof child.value === "string") { - if (/\S/.test(child.value)) { - return child.value.replace(/^\s+|\s+$/g, ""); - } else if (/\n/.test(child.value)) { - return "\n"; - } - } +},{"./_baseGet":365}],506:[function(require,module,exports){ +var baseHas = require('./_baseHas'), + hasPath = require('./_hasPath'); - return print(childPath); - }, "children") - ).indentTail(options.tabWidth); +/** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ +function has(object, path) { + return object != null && hasPath(object, path, baseHas); +} - var closingLines = path.call(print, "closingElement"); +module.exports = has; - return concat([ - openingLines, - childLines, - closingLines - ]); +},{"./_baseHas":368,"./_hasPath":438}],507:[function(require,module,exports){ +var baseHasIn = require('./_baseHasIn'), + hasPath = require('./_hasPath'); - case "JSXOpeningElement": - parts.push("<", path.call(print, "name")); - var attrParts = []; +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} - path.each(function(attrPath) { - attrParts.push(" ", print(attrPath)); - }, "attributes"); +module.exports = hasIn; - var attrLines = concat(attrParts); +},{"./_baseHasIn":369,"./_hasPath":438}],508:[function(require,module,exports){ +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} - var needLineWrap = ( - attrLines.length > 1 || - attrLines.getLineLength(1) > options.wrapColumn - ); +module.exports = identity; - if (needLineWrap) { - attrParts.forEach(function(part, i) { - if (part === " ") { - assert.strictEqual(i % 2, 0); - attrParts[i] = "\n"; - } - }); +},{}],509:[function(require,module,exports){ +var baseIndexOf = require('./_baseIndexOf'), + isArrayLike = require('./isArrayLike'), + isString = require('./isString'), + toInteger = require('./toInteger'), + values = require('./values'); - attrLines = concat(attrParts).indentTail(options.tabWidth); - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - parts.push(attrLines, n.selfClosing ? " />" : ">"); +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - return concat(parts); + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} - case "JSXClosingElement": - return concat([""]); +module.exports = includes; - case "JSXText": - return fromString(n.value, options); +},{"./_baseIndexOf":370,"./isArrayLike":512,"./isString":522,"./toInteger":538,"./values":543}],510:[function(require,module,exports){ +var baseIsArguments = require('./_baseIsArguments'), + isObjectLike = require('./isObjectLike'); - case "JSXEmptyExpression": - return fromString(""); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - case "TypeAnnotatedIdentifier": - return concat([ - path.call(print, "annotation"), - " ", - path.call(print, "identifier") - ]); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - case "ClassBody": - if (n.body.length === 0) { - return fromString("{}"); - } +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - return concat([ - "{\n", - path.call(function(bodyPath) { - return printStatementSequence(bodyPath, options, print); - }, "body").indent(options.tabWidth), - "\n}" - ]); +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; - case "ClassPropertyDefinition": - parts.push("static ", path.call(print, "definition")); - if (!namedTypes.MethodDefinition.check(n.definition)) - parts.push(";"); - return concat(parts); +module.exports = isArguments; - case "ClassProperty": - if (n.static) - parts.push("static "); +},{"./_baseIsArguments":371,"./isObjectLike":519}],511:[function(require,module,exports){ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - var key = path.call(print, "key"); - if (n.computed) { - key = concat(["[", key, "]"]); - } else if (n.variance === "plus") { - key = concat(["+", key]); - } else if (n.variance === "minus") { - key = concat(["-", key]); - } - parts.push(key); +module.exports = isArray; - if (n.typeAnnotation) - parts.push(path.call(print, "typeAnnotation")); +},{}],512:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); - if (n.value) - parts.push(" = ", path.call(print, "value")); +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - parts.push(";"); - return concat(parts); +module.exports = isArrayLike; - case "ClassDeclaration": - case "ClassExpression": - parts.push("class"); +},{"./isFunction":515,"./isLength":517}],513:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); - if (n.id) { - parts.push( - " ", - path.call(print, "id"), - path.call(print, "typeParameters") - ); - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - if (n.superClass) { - parts.push( - " extends ", - path.call(print, "superClass"), - path.call(print, "superTypeParameters") - ); - } +module.exports = isArrayLikeObject; - if (n["implements"] && n['implements'].length > 0) { - parts.push( - " implements ", - fromString(", ").join(path.map(print, "implements")) - ); - } +},{"./isArrayLike":512,"./isObjectLike":519}],514:[function(require,module,exports){ +var root = require('./_root'), + stubFalse = require('./stubFalse'); - parts.push(" ", path.call(print, "body")); +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - return concat(parts); +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - case "TemplateElement": - return fromString(n.value.raw, options).lockIndentTail(); +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; - case "TemplateLiteral": - var expressions = path.map(print, "expressions"); - parts.push("`"); +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; - path.each(function(childPath) { - var i = childPath.getName(); - parts.push(print(childPath)); - if (i < expressions.length) { - parts.push("${", expressions[i], "}"); - } - }, "quasis"); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - parts.push("`"); +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; - return concat(parts).lockIndentTail(); +module.exports = isBuffer; - case "TaggedTemplateExpression": - return concat([ - path.call(print, "tag"), - path.call(print, "quasi") - ]); +},{"./_root":475,"./stubFalse":536}],515:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isObject = require('./isObject'); - // These types are unprintable because they serve as abstract - // supertypes for other (printable) types. - case "Node": - case "Printable": - case "SourceLocation": - case "Position": - case "Statement": - case "Function": - case "Pattern": - case "Expression": - case "Declaration": - case "Specifier": - case "NamedSpecifier": - case "Comment": // Supertype of Block and Line. - case "MemberTypeAnnotation": // Flow - case "TupleTypeAnnotation": // Flow - case "Type": // Flow - throw new Error("unprintable type: " + JSON.stringify(n.type)); +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; - case "CommentBlock": // Babel block comment. - case "Block": // Esprima block comment. - return concat(["/*", fromString(n.value, options), "*/"]); +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} - case "CommentLine": // Babel line comment. - case "Line": // Esprima line comment. - return concat(["//", fromString(n.value, options)]); +module.exports = isFunction; - // Type Annotations for Facebook Flow, typically stripped out or - // transformed away before printing. - case "TypeAnnotation": - if (n.typeAnnotation) { - if (n.typeAnnotation.type !== "FunctionTypeAnnotation") { - parts.push(": "); - } - parts.push(path.call(print, "typeAnnotation")); - return concat(parts); - } +},{"./_baseGetTag":367,"./isObject":518}],516:[function(require,module,exports){ +var toInteger = require('./toInteger'); - return fromString(""); +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} - case "ExistentialTypeParam": - case "ExistsTypeAnnotation": - return fromString("*", options); +module.exports = isInteger; - case "EmptyTypeAnnotation": - return fromString("empty", options); +},{"./toInteger":538}],517:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - case "AnyTypeAnnotation": - return fromString("any", options); +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - case "MixedTypeAnnotation": - return fromString("mixed", options); +module.exports = isLength; - case "ArrayTypeAnnotation": - return concat([ - path.call(print, "elementType"), - "[]" - ]); +},{}],518:[function(require,module,exports){ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} - case "BooleanTypeAnnotation": - return fromString("boolean", options); +module.exports = isObject; - case "BooleanLiteralTypeAnnotation": - assert.strictEqual(typeof n.value, "boolean"); - return fromString("" + n.value, options); +},{}],519:[function(require,module,exports){ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} - case "DeclareClass": - return printFlowDeclaration(path, [ - "class ", - path.call(print, "id"), - " ", - path.call(print, "body"), - ]); +module.exports = isObjectLike; - case "DeclareFunction": - return printFlowDeclaration(path, [ - "function ", - path.call(print, "id"), - ";" - ]); +},{}],520:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + getPrototype = require('./_getPrototype'), + isObjectLike = require('./isObjectLike'); - case "DeclareModule": - return printFlowDeclaration(path, [ - "module ", - path.call(print, "id"), - " ", - path.call(print, "body"), - ]); +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; - case "DeclareModuleExports": - return printFlowDeclaration(path, [ - "module.exports", - path.call(print, "typeAnnotation"), - ]); +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; - case "DeclareVariable": - return printFlowDeclaration(path, [ - "var ", - path.call(print, "id"), - ";" - ]); +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - case "DeclareExportDeclaration": - case "DeclareExportAllDeclaration": - return concat([ - "declare ", - printExportDeclaration(path, options, print) - ]); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - case "FunctionTypeAnnotation": - // FunctionTypeAnnotation is ambiguous: - // declare function(a: B): void; OR - // var A: (a: B) => void; - var parent = path.getParentNode(0); - var isArrowFunctionTypeAnnotation = !( - namedTypes.ObjectTypeCallProperty.check(parent) || - namedTypes.DeclareFunction.check(path.getParentNode(2)) - ); +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); - var needsColon = - isArrowFunctionTypeAnnotation && - !namedTypes.FunctionTypeParam.check(parent); +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} - if (needsColon) { - parts.push(": "); - } +module.exports = isPlainObject; - parts.push( - "(", - fromString(", ").join(path.map(print, "params")), - ")" - ); +},{"./_baseGetTag":367,"./_getPrototype":432,"./isObjectLike":519}],521:[function(require,module,exports){ +var baseIsRegExp = require('./_baseIsRegExp'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); - // The returnType is not wrapped in a TypeAnnotation, so the colon - // needs to be added separately. - if (n.returnType) { - parts.push( - isArrowFunctionTypeAnnotation ? " => " : ": ", - path.call(print, "returnType") - ); - } +/* Node.js helper references. */ +var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; - return concat(parts); +/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ +var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - case "FunctionTypeParam": - return concat([ - path.call(print, "name"), - n.optional ? '?' : '', - ": ", - path.call(print, "typeAnnotation"), - ]); +module.exports = isRegExp; - case "GenericTypeAnnotation": - return concat([ - path.call(print, "id"), - path.call(print, "typeParameters") - ]); +},{"./_baseIsRegExp":377,"./_baseUnary":396,"./_nodeUtil":471}],522:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isArray = require('./isArray'), + isObjectLike = require('./isObjectLike'); - case "DeclareInterface": - parts.push("declare "); +/** `Object#toString` result references. */ +var stringTag = '[object String]'; - case "InterfaceDeclaration": - parts.push( - fromString("interface ", options), - path.call(print, "id"), - path.call(print, "typeParameters"), - " " - ); +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); +} - if (n["extends"]) { - parts.push( - "extends ", - fromString(", ").join(path.map(print, "extends")) - ); - } +module.exports = isString; - parts.push(" ", path.call(print, "body")); +},{"./_baseGetTag":367,"./isArray":511,"./isObjectLike":519}],523:[function(require,module,exports){ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); - return concat(parts); +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - case "ClassImplements": - case "InterfaceExtends": - return concat([ - path.call(print, "id"), - path.call(print, "typeParameters") - ]); +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} - case "IntersectionTypeAnnotation": - return fromString(" & ").join(path.map(print, "types")); +module.exports = isSymbol; - case "NullableTypeAnnotation": - return concat([ - "?", - path.call(print, "typeAnnotation") - ]); +},{"./_baseGetTag":367,"./isObjectLike":519}],524:[function(require,module,exports){ +var baseIsTypedArray = require('./_baseIsTypedArray'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); - case "NullLiteralTypeAnnotation": - return fromString("null", options); +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - case "ThisTypeAnnotation": - return fromString("this", options); +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - case "NumberTypeAnnotation": - return fromString("number", options); +module.exports = isTypedArray; - case "ObjectTypeCallProperty": - return path.call(print, "value"); +},{"./_baseIsTypedArray":378,"./_baseUnary":396,"./_nodeUtil":471}],525:[function(require,module,exports){ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); - case "ObjectTypeIndexer": - var variance = - n.variance === "plus" ? "+" : - n.variance === "minus" ? "-" : ""; +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} - return concat([ - variance, - "[", - path.call(print, "id"), - ": ", - path.call(print, "key"), - "]: ", - path.call(print, "value") - ]); +module.exports = keys; - case "ObjectTypeProperty": - var variance = - n.variance === "plus" ? "+" : - n.variance === "minus" ? "-" : ""; +},{"./_arrayLikeKeys":346,"./_baseKeys":380,"./isArrayLike":512}],526:[function(require,module,exports){ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeysIn = require('./_baseKeysIn'), + isArrayLike = require('./isArrayLike'); - return concat([ - variance, - path.call(print, "key"), - n.optional ? "?" : "", - ": ", - path.call(print, "value") - ]); +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} - case "QualifiedTypeIdentifier": - return concat([ - path.call(print, "qualification"), - ".", - path.call(print, "id") - ]); +module.exports = keysIn; - case "StringLiteralTypeAnnotation": - return fromString(nodeStr(n.value, options), options); +},{"./_arrayLikeKeys":346,"./_baseKeysIn":381,"./isArrayLike":512}],527:[function(require,module,exports){ +var arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseMap = require('./_baseMap'), + isArray = require('./isArray'); - case "NumberLiteralTypeAnnotation": - case "NumericLiteralTypeAnnotation": - assert.strictEqual(typeof n.value, "number"); - return fromString(JSON.stringify(n.value), options); +/** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ +function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, baseIteratee(iteratee, 3)); +} - case "StringTypeAnnotation": - return fromString("string", options); +module.exports = map; - case "DeclareTypeAlias": - parts.push("declare "); +},{"./_arrayMap":347,"./_baseIteratee":379,"./_baseMap":382,"./isArray":511}],528:[function(require,module,exports){ +var MapCache = require('./_MapCache'); - case "TypeAlias": - return concat([ - "type ", - path.call(print, "id"), - path.call(print, "typeParameters"), - " = ", - path.call(print, "right"), - ";" - ]); +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; - case "TypeCastExpression": - return concat([ - "(", - path.call(print, "expression"), - path.call(print, "typeAnnotation"), - ")" - ]); +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; - case "TypeParameterDeclaration": - case "TypeParameterInstantiation": - return concat([ - "<", - fromString(", ").join(path.map(print, "params")), - ">" - ]); - case "TypeParameter": - switch (n.variance) { - case 'plus': - parts.push('+'); - break; - case 'minus': - parts.push('-'); - break; - default: - } + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; +} - parts.push(path.call(print, 'name')); +// Expose `MapCache`. +memoize.Cache = MapCache; - if (n.bound) { - parts.push(path.call(print, 'bound')); - } +module.exports = memoize; - if (n['default']) { - parts.push('=', path.call(print, 'default')); - } +},{"./_MapCache":331}],529:[function(require,module,exports){ +var baseMerge = require('./_baseMerge'), + createAssigner = require('./_createAssigner'); + +/** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ +var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); +}); - return concat(parts); +module.exports = mergeWith; - case "TypeofTypeAnnotation": - return concat([ - fromString("typeof ", options), - path.call(print, "argument") - ]); +},{"./_baseMerge":385,"./_createAssigner":416}],530:[function(require,module,exports){ +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} - case "UnionTypeAnnotation": - return fromString(" | ").join(path.map(print, "types")); +module.exports = noop; - case "VoidTypeAnnotation": - return fromString("void", options); +},{}],531:[function(require,module,exports){ +var baseProperty = require('./_baseProperty'), + basePropertyDeep = require('./_basePropertyDeep'), + isKey = require('./_isKey'), + toKey = require('./_toKey'); - case "NullTypeAnnotation": - return fromString("null", options); +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); +} - // Unhandled types below. If encountered, nodes of these types should - // be either left alone or desugared into AST types that are fully - // supported by the pretty-printer. - case "ClassHeritage": // TODO - case "ComprehensionBlock": // TODO - case "ComprehensionExpression": // TODO - case "Glob": // TODO - case "GeneratorExpression": // TODO - case "LetStatement": // TODO - case "LetExpression": // TODO - case "GraphExpression": // TODO - case "GraphIndexExpression": // TODO +module.exports = property; - // XML types that nobody cares about or needs to print. - case "XMLDefaultDeclaration": - case "XMLAnyName": - case "XMLQualifiedIdentifier": - case "XMLFunctionQualifiedIdentifier": - case "XMLAttributeSelector": - case "XMLFilterExpression": - case "XML": - case "XMLElement": - case "XMLList": - case "XMLEscape": - case "XMLText": - case "XMLStartTag": - case "XMLEndTag": - case "XMLPointTag": - case "XMLName": - case "XMLAttribute": - case "XMLCdata": - case "XMLComment": - case "XMLProcessingInstruction": - default: - debugger; - throw new Error("unknown type: " + JSON.stringify(n.type)); - } +},{"./_baseProperty":388,"./_basePropertyDeep":389,"./_isKey":450,"./_toKey":488}],532:[function(require,module,exports){ +var baseRepeat = require('./_baseRepeat'), + isIterateeCall = require('./_isIterateeCall'), + toInteger = require('./toInteger'), + toString = require('./toString'); - return p; +/** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ +function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); } -function printStatementSequence(path, options, print) { - var inClassBody = - namedTypes.ClassBody && - namedTypes.ClassBody.check(path.getParentNode()); +module.exports = repeat; - var filtered = []; - var sawComment = false; - var sawStatement = false; +},{"./_baseRepeat":390,"./_isIterateeCall":449,"./toInteger":538,"./toString":541}],533:[function(require,module,exports){ +var baseFlatten = require('./_baseFlatten'), + baseOrderBy = require('./_baseOrderBy'), + baseRest = require('./_baseRest'), + isIterateeCall = require('./_isIterateeCall'); - path.each(function(stmtPath) { - var i = stmtPath.getName(); - var stmt = stmtPath.getValue(); +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ +var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); +}); - // Just in case the AST has been modified to contain falsy - // "statements," it's safer simply to skip them. - if (!stmt) { - return; - } +module.exports = sortBy; - // Skip printing EmptyStatement nodes to avoid leaving stray - // semicolons lying around. - if (stmt.type === "EmptyStatement") { - return; - } +},{"./_baseFlatten":362,"./_baseOrderBy":387,"./_baseRest":391,"./_isIterateeCall":449}],534:[function(require,module,exports){ +var baseClamp = require('./_baseClamp'), + baseToString = require('./_baseToString'), + toInteger = require('./toInteger'), + toString = require('./toString'); - if (namedTypes.Comment.check(stmt)) { - // The pretty printer allows a dangling Comment node to act as - // a Statement when the Comment can't be attached to any other - // non-Comment node in the tree. - sawComment = true; - } else if (namedTypes.Statement.check(stmt)) { - sawStatement = true; - } else { - // When the pretty printer encounters a string instead of an - // AST node, it just prints the string. This behavior can be - // useful for fine-grained formatting decisions like inserting - // blank lines. - isString.assert(stmt); - } +/** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ +function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); - // We can't hang onto stmtPath outside of this function, because - // it's just a reference to a mutable FastPath object, so we have - // to go ahead and print it here. - filtered.push({ - node: stmt, - printed: print(stmtPath) - }); - }); + target = baseToString(target); + return string.slice(position, position + target.length) == target; +} - if (sawComment) { - assert.strictEqual( - sawStatement, false, - "Comments may appear as statements in otherwise empty statement " + - "lists, but may not coexist with non-Comment nodes." - ); - } +module.exports = startsWith; - var prevTrailingSpace = null; - var len = filtered.length; - var parts = []; +},{"./_baseClamp":357,"./_baseToString":395,"./toInteger":538,"./toString":541}],535:[function(require,module,exports){ +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} - filtered.forEach(function(info, i) { - var printed = info.printed; - var stmt = info.node; - var multiLine = printed.length > 1; - var notFirst = i > 0; - var notLast = i < len - 1; - var leadingSpace; - var trailingSpace; - var lines = stmt && stmt.loc && stmt.loc.lines; - var trueLoc = lines && options.reuseWhitespace && - util.getTrueLoc(stmt, lines); +module.exports = stubArray; - if (notFirst) { - if (trueLoc) { - var beforeStart = lines.skipSpaces(trueLoc.start, true); - var beforeStartLine = beforeStart ? beforeStart.line : 1; - var leadingGap = trueLoc.start.line - beforeStartLine; - leadingSpace = Array(leadingGap + 1).join("\n"); - } else { - leadingSpace = multiLine ? "\n\n" : "\n"; - } - } else { - leadingSpace = ""; - } +},{}],536:[function(require,module,exports){ +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} - if (notLast) { - if (trueLoc) { - var afterEnd = lines.skipSpaces(trueLoc.end); - var afterEndLine = afterEnd ? afterEnd.line : lines.length; - var trailingGap = afterEndLine - trueLoc.end.line; - trailingSpace = Array(trailingGap + 1).join("\n"); - } else { - trailingSpace = multiLine ? "\n\n" : "\n"; - } - } else { - trailingSpace = ""; - } +module.exports = stubFalse; - parts.push( - maxSpace(prevTrailingSpace, leadingSpace), - printed - ); +},{}],537:[function(require,module,exports){ +var toNumber = require('./toNumber'); - if (notLast) { - prevTrailingSpace = trailingSpace; - } else if (trailingSpace) { - parts.push(trailingSpace); - } - }); +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; - return concat(parts); +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; } -function maxSpace(s1, s2) { - if (!s1 && !s2) { - return fromString(""); - } +module.exports = toFinite; - if (!s1) { - return fromString(s2); - } +},{"./toNumber":539}],538:[function(require,module,exports){ +var toFinite = require('./toFinite'); - if (!s2) { - return fromString(s1); - } +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - var spaceLines1 = fromString(s1); - var spaceLines2 = fromString(s2); + return result === result ? (remainder ? result - remainder : result) : 0; +} - if (spaceLines2.length > spaceLines1.length) { - return spaceLines2; - } +module.exports = toInteger; - return spaceLines1; -} +},{"./toFinite":537}],539:[function(require,module,exports){ +var isObject = require('./isObject'), + isSymbol = require('./isSymbol'); -function printMethod(path, options, print) { - var node = path.getNode(); - var kind = node.kind; - var parts = []; +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; - if (node.type === "ObjectMethod" || node.type === "ClassMethod") { - node.value = node; - } else { - namedTypes.FunctionExpression.assert(node.value); - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - if (node.value.async) { - parts.push("async "); - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - if (!kind || kind === "init" || kind === "method" || kind === "constructor") { - if (node.value.generator) { - parts.push("*"); - } - } else { - assert.ok(kind === "get" || kind === "set"); - parts.push(kind, " "); - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - var key = path.call(print, "key"); - if (node.computed) { - key = concat(["[", key, "]"]); - } +module.exports = toNumber; - parts.push( - key, - path.call(print, "value", "typeParameters"), - "(", - path.call(function(valuePath) { - return printFunctionParams(valuePath, options, print); - }, "value"), - ")", - path.call(print, "value", "returnType"), - " ", - path.call(print, "value", "body") - ); +},{"./isObject":518,"./isSymbol":523}],540:[function(require,module,exports){ +var copyObject = require('./_copyObject'), + keysIn = require('./keysIn'); - return concat(parts); +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject(value) { + return copyObject(value, keysIn(value)); } -function printArgumentsList(path, options, print) { - var printed = path.map(print, "arguments"); - var trailingComma = util.isTrailingCommaEnabled(options, "parameters"); +module.exports = toPlainObject; - var joined = fromString(", ").join(printed); - if (joined.getLineLength(1) > options.wrapColumn) { - joined = fromString(",\n").join(printed); - return concat([ - "(\n", - joined.indent(options.tabWidth), - trailingComma ? ",\n)" : "\n)" - ]); - } +},{"./_copyObject":412,"./keysIn":526}],541:[function(require,module,exports){ +var baseToString = require('./_baseToString'); - return concat(["(", joined, ")"]); +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); } -function printFunctionParams(path, options, print) { - var fun = path.getValue(); - - namedTypes.Function.assert(fun); +module.exports = toString; - var printed = path.map(print, "params"); +},{"./_baseToString":395}],542:[function(require,module,exports){ +var baseUniq = require('./_baseUniq'); - if (fun.defaults) { - path.each(function(defExprPath) { - var i = defExprPath.getName(); - var p = printed[i]; - if (p && defExprPath.getValue()) { - printed[i] = concat([p, " = ", print(defExprPath)]); - } - }, "defaults"); - } +/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ +function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; +} - if (fun.rest) { - printed.push(concat(["...", path.call(print, "rest")])); - } +module.exports = uniq; - var joined = fromString(", ").join(printed); - if (joined.length > 1 || - joined.getLineLength(1) > options.wrapColumn) { - joined = fromString(",\n").join(printed); - if (util.isTrailingCommaEnabled(options, "parameters") && - !fun.rest && - fun.params[fun.params.length - 1].type !== 'RestElement') { - joined = concat([joined, ",\n"]); - } else { - joined = concat([joined, "\n"]); - } - return concat(["\n", joined.indent(options.tabWidth)]); - } +},{"./_baseUniq":397}],543:[function(require,module,exports){ +var baseValues = require('./_baseValues'), + keys = require('./keys'); - return joined; +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object == null ? [] : baseValues(object, keys(object)); } -function printObjectMethod(path, options, print) { - var objMethod = path.getValue(); - var parts = []; - - if (objMethod.async) - parts.push("async "); - - if (objMethod.generator) - parts.push("*"); +module.exports = values; - if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") { - return printMethod(path, options, print); - } +},{"./_baseValues":398,"./keys":525}],544:[function(require,module,exports){ +module.exports = minimatch +minimatch.Minimatch = Minimatch - var key = path.call(print, "key"); - if (objMethod.computed) { - parts.push("[", key, "]"); - } else { - parts.push(key); - } +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} - parts.push( - "(", - printFunctionParams(path, options, print), - ")", - path.call(print, "returnType"), - " ", - path.call(print, "body") - ); +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') - return concat(parts); +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } } -function printExportDeclaration(path, options, print) { - var decl = path.getValue(); - var parts = ["export "]; - var shouldPrintSpaces = options.objectCurlySpacing; - - namedTypes.Declaration.assert(decl); - - if (decl["default"] || - decl.type === "ExportDefaultDeclaration") { - parts.push("default "); - } - - if (decl.declaration) { - parts.push(path.call(print, "declaration")); - - } else if (decl.specifiers && - decl.specifiers.length > 0) { +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - if (decl.specifiers.length === 1 && - decl.specifiers[0].type === "ExportBatchSpecifier") { - parts.push("*"); - } else { - parts.push( - shouldPrintSpaces ? "{ " : "{", - fromString(", ").join(path.map(print, "specifiers")), - shouldPrintSpaces ? " }" : "}" - ); - } +// * => any number of characters +var star = qmark + '*?' - if (decl.source) { - parts.push(" from ", path.call(print, "source")); - } - } +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - var lines = concat(parts); +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - if (lastNonSpaceCharacter(lines) !== ";" && - ! (decl.declaration && - (decl.declaration.type === "FunctionDeclaration" || - decl.declaration.type === "ClassDeclaration"))) { - lines = concat([lines, ";"]); - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - return lines; +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) } -function printFlowDeclaration(path, parts) { - var parentExportDecl = util.getParentExportDeclaration(path); - - if (parentExportDecl) { - assert.strictEqual( - parentExportDecl.type, - "DeclareExportDeclaration" - ); - } else { - // If the parent node has type DeclareExportDeclaration, then it - // will be responsible for printing the "declare" token. Otherwise - // it needs to be printed with this non-exported declaration node. - parts.unshift("declare "); - } +// normalizes slashes. +var slashSplit = /\/+/ - return concat(parts); +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } } -function adjustClause(clause, options) { - if (clause.length > 1) - return concat([" ", clause]); - - return concat([ - "\n", - maybeAddSemicolon(clause).indent(options.tabWidth) - ]); +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t } -function lastNonSpaceCharacter(lines) { - var pos = lines.lastPos(); - do { - var ch = lines.charAt(pos); - if (/\S/.test(ch)) - return ch; - } while (lines.prevPos(pos)); -} +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch -function endsWithBrace(lines) { - return lastNonSpaceCharacter(lines) === "}"; -} + var orig = minimatch -function swapQuotes(str) { - return str.replace(/['"]/g, function(m) { - return m === '"' ? '\'' : '"'; - }); -} + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } -function nodeStr(str, options) { - isString.assert(str); - switch (options.quote) { - case "auto": - var double = JSON.stringify(str); - var single = swapQuotes(JSON.stringify(swapQuotes(str))); - return double.length > single.length ? single : double; - case "single": - return swapQuotes(JSON.stringify(swapQuotes(str))); - case "double": - default: - return JSON.stringify(str); - } + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m } -function maybeAddSemicolon(lines) { - var eoc = lastNonSpaceCharacter(lines); - if (!eoc || "\n};".indexOf(eoc) < 0) - return concat([lines, ";"]); - return lines; +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch } -},{"./comments":511,"./fast-path":512,"./lines":513,"./options":515,"./patcher":517,"./types":519,"./util":520,"assert":791,"source-map":534}],519:[function(require,module,exports){ -// This module was originally created so that Recast could add its own -// custom types to the AST type system (in particular, the File type), but -// those types are now incorporated into ast-types, so this module doesn't -// have much to do anymore. Still, it might prove useful in the future. -module.exports = require("ast-types"); +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } -},{"ast-types":24}],520:[function(require,module,exports){ -var assert = require("assert"); -var types = require("./types"); -var getFieldValue = types.getFieldValue; -var n = types.namedTypes; -var sourceMap = require("source-map"); -var SourceMapConsumer = sourceMap.SourceMapConsumer; -var SourceMapGenerator = sourceMap.SourceMapGenerator; -var hasOwn = Object.prototype.hasOwnProperty; -var util = exports; + if (!options) options = {} -function getUnionOfKeys() { - var result = {}; - var argc = arguments.length; - for (var i = 0; i < argc; ++i) { - var keys = Object.keys(arguments[i]); - var keyCount = keys.length; - for (var j = 0; j < keyCount; ++j) { - result[keys[j]] = true; - } + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false } - return result; -} -util.getUnionOfKeys = getUnionOfKeys; -function comparePos(pos1, pos2) { - return (pos1.line - pos2.line) || (pos1.column - pos2.column); -} -util.comparePos = comparePos; + // "" only matches "" + if (pattern.trim() === '') return p === '' -function copyPos(pos) { - return { - line: pos.line, - column: pos.column - }; + return new Minimatch(pattern, options).match(p) } -util.copyPos = copyPos; -util.composeSourceMaps = function(formerMap, latterMap) { - if (formerMap) { - if (!latterMap) { - return formerMap; - } - } else { - return latterMap || null; +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) } - var smcFormer = new SourceMapConsumer(formerMap); - var smcLatter = new SourceMapConsumer(latterMap); - var smg = new SourceMapGenerator({ - file: latterMap.file, - sourceRoot: latterMap.sourceRoot - }); + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } - var sourcesToContents = {}; + if (!options) options = {} + pattern = pattern.trim() - smcLatter.eachMapping(function(mapping) { - var origPos = smcFormer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } - var sourceName = origPos.source; - if (sourceName === null) { - return; - } + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false - smg.addMapping({ - source: sourceName, - original: copyPos(origPos), - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - }, - name: mapping.name - }); + // make the set of regexps etc. + this.make() +} - var sourceContent = smcFormer.sourceContentFor(sourceName); - if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { - sourcesToContents[sourceName] = sourceContent; - smg.setSourceContent(sourceName, sourceContent); - } - }); +Minimatch.prototype.debug = function () {} - return smg.toJSON(); -}; +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return -util.getTrueLoc = function(node, lines) { - // It's possible that node is newly-created (not parsed by Esprima), - // in which case it probably won't have a .loc property (or an - // .original property for that matter). That's fine; we'll just - // pretty-print it as usual. - if (!node.loc) { - return null; + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return } - var result = { - start: node.loc.start, - end: node.loc.end - }; + // step 1: figure out negation, etc. + this.parseNegate() - function include(node) { - expandLoc(result, node.loc); - } + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error - // If the node has any comments, their locations might contribute to - // the true start/end positions of the node. - if (node.comments) { - node.comments.forEach(include); - } + this.debug(this.pattern, set) - // If the node is an export declaration and its .declaration has any - // decorators, their locations might contribute to the true start/end - // positions of the export declaration node. - if (node.declaration && util.isExportDeclaration(node) && - node.declaration.decorators) { - node.declaration.decorators.forEach(include); - } + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) - if (comparePos(result.start, result.end) < 0) { - // Trim leading whitespace. - result.start = copyPos(result.start); - lines.skipSpaces(result.start, false, true); + this.debug(this.pattern, set) - if (comparePos(result.start, result.end) < 0) { - // Trim trailing whitespace, if the end location is not already the - // same as the start location. - result.end = copyPos(result.end); - lines.skipSpaces(result.end, true, true); - } - } + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) - return result; -}; + this.debug(this.pattern, set) -function expandLoc(parentLoc, childLoc) { - if (parentLoc && childLoc) { - if (comparePos(childLoc.start, parentLoc.start) < 0) { - parentLoc.start = childLoc.start; - } + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) - if (comparePos(parentLoc.end, childLoc.end) < 0) { - parentLoc.end = childLoc.end; - } - } + this.debug(this.pattern, set) + + this.set = set } -util.fixFaultyLocations = function(node, lines) { - var loc = node.loc; - if (loc) { - if (loc.start.line < 1) { - loc.start.line = 1; - } +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 - if (loc.end.line < 1) { - loc.end.line = 1; - } - } + if (options.nonegate) return - if (node.type === "File") { - // Babylon returns File nodes whose .loc.{start,end} do not include - // leading or trailing whitespace. - loc.start = lines.firstPos(); - loc.end = lines.lastPos(); + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ } - if (node.type === "TemplateLiteral") { - fixTemplateLiteral(node, lines); + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} - } else if (loc && node.decorators) { - // Expand the .loc of the node responsible for printing the decorators - // (here, the decorated node) so that it includes node.decorators. - node.decorators.forEach(function (decorator) { - expandLoc(loc, decorator.loc); - }); +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} - } else if (node.declaration && util.isExportDeclaration(node)) { - // Nullify .loc information for the child declaration so that we never - // try to reprint it without also reprinting the export declaration. - node.declaration.loc = null; +Minimatch.prototype.braceExpand = braceExpand - // Expand the .loc of the node responsible for printing the decorators - // (here, the export declaration) so that it includes node.decorators. - var decorators = node.declaration.decorators; - if (decorators) { - decorators.forEach(function (decorator) { - expandLoc(loc, decorator.loc); - }); +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} } + } - } else if ((n.MethodDefinition && n.MethodDefinition.check(node)) || - (n.Property.check(node) && (node.method || node.shorthand))) { - // If the node is a MethodDefinition or a .method or .shorthand - // Property, then the location information stored in - // node.value.loc is very likely untrustworthy (just the {body} - // part of a method, or nothing in the case of shorthand - // properties), so we null out that information to prevent - // accidental reuse of bogus source code during reprinting. - node.value.loc = null; + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern - if (n.FunctionExpression.check(node.value)) { - // FunctionExpression method values should be anonymous, - // because their .id fields are ignored anyway. - node.value.id = null; - } + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } - } else if (node.type === "ObjectTypeProperty") { - var loc = node.loc; - var end = loc && loc.end; - if (end) { - end = copyPos(end); - if (lines.prevPos(end) && - lines.charAt(end) === ",") { - // Some parsers accidentally include trailing commas in the - // .loc.end information for ObjectTypeProperty nodes. - if ((end = lines.skipSpaces(end, true, true))) { - loc.end = end; - } - } - } + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] } -}; -function fixTemplateLiteral(node, lines) { - assert.strictEqual(node.type, "TemplateLiteral"); + return expand(pattern) +} - if (node.quasis.length === 0) { - // If there are no quasi elements, then there is nothing to fix. - return; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') } - // First we need to exclude the opening ` from the .loc of the first - // quasi element, in case the parser accidentally decided to include it. - var afterLeftBackTickPos = copyPos(node.loc.start); - assert.strictEqual(lines.charAt(afterLeftBackTickPos), "`"); - assert.ok(lines.nextPos(afterLeftBackTickPos)); - var firstQuasi = node.quasis[0]; - if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) { - firstQuasi.loc.start = afterLeftBackTickPos; - } + var options = this.options - // Next we need to exclude the closing ` from the .loc of the last quasi - // element, in case the parser accidentally decided to include it. - var rightBackTickPos = copyPos(node.loc.end); - assert.ok(lines.prevPos(rightBackTickPos)); - assert.strictEqual(lines.charAt(rightBackTickPos), "`"); - var lastQuasi = node.quasis[node.quasis.length - 1]; - if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) { - lastQuasi.loc.end = rightBackTickPos; - } + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' - // Now we need to exclude ${ and } characters from the .loc's of all - // quasi elements, since some parsers accidentally include them. - node.expressions.forEach(function (expr, i) { - // Rewind from expr.loc.start over any whitespace and the ${ that - // precedes the expression. The position of the $ should be the same - // as the .loc.end of the preceding quasi element, but some parsers - // accidentally include the ${ in the .loc of the quasi element. - var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false); - if (lines.prevPos(dollarCurlyPos) && - lines.charAt(dollarCurlyPos) === "{" && - lines.prevPos(dollarCurlyPos) && - lines.charAt(dollarCurlyPos) === "$") { - var quasiBefore = node.quasis[i]; - if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) { - quasiBefore.loc.end = dollarCurlyPos; + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } + } - // Likewise, some parsers accidentally include the } that follows - // the expression in the .loc of the following quasi element. - var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false); - if (lines.charAt(rightCurlyPos) === "}") { - assert.ok(lines.nextPos(rightCurlyPos)); - // Now rightCurlyPos is technically the position just after the }. - var quasiAfter = node.quasis[i + 1]; - if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) { - quasiAfter.loc.start = rightCurlyPos; - } + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue } - }); -} -util.isExportDeclaration = function (node) { - if (node) switch (node.type) { - case "ExportDeclaration": - case "ExportDefaultDeclaration": - case "ExportDefaultSpecifier": - case "DeclareExportDeclaration": - case "ExportNamedDeclaration": - case "ExportAllDeclaration": - return true; - } + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false - return false; -}; + case '\\': + clearStateChar() + escaping = true + continue -util.getParentExportDeclaration = function (path) { - var parentNode = path.getParentNode(); - if (path.getName() === "declaration" && - util.isExportDeclaration(parentNode)) { - return parentNode; - } + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - return null; -}; + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -util.isTrailingCommaEnabled = function(options, context) { - var trailingComma = options.trailingComma; - if (typeof trailingComma === "object") { - return !!trailingComma[context]; - } - return !!trailingComma; -}; + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -},{"./types":519,"assert":791,"source-map":534}],521:[function(require,module,exports){ -(function (process){ -var types = require("./lib/types"); -var parse = require("./lib/parser").parse; -var Printer = require("./lib/printer").Printer; + case '(': + if (inClass) { + re += '(' + continue + } -function print(node, options) { - return new Printer(options).print(node); -} + if (!stateChar) { + re += '\\(' + continue + } -function prettyPrint(node, options) { - return new Printer(options).printGenerically(node); -} + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue -function run(transformer, options) { - return runFile(process.argv[2], transformer, options); -} + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -function runFile(path, transformer, options) { - require("fs").readFile(path, "utf-8", function(err, code) { - if (err) { - console.error(err); - return; + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) } + pl.reEnd = re.length + continue - runString(code, transformer, options); - }); -} + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -function defaultWriteback(output) { - process.stdout.write(output); -} + clearStateChar() + re += '|' + continue -function runString(code, transformer, options) { - var writeback = options && options.writeback || defaultWriteback; - transformer(parse(code, options), function(node) { - writeback(print(node, options).code); - }); -} + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -Object.defineProperties(exports, { - /** - * Parse a string of code into an augmented syntax tree suitable for - * arbitrary modification and reprinting. - */ - parse: { - enumerable: true, - value: parse - }, + if (inClass) { + re += '\\' + c + continue + } - /** - * Traverse and potentially modify an abstract syntax tree using a - * convenient visitor syntax: - * - * recast.visit(ast, { - * names: [], - * visitIdentifier: function(path) { - * var node = path.value; - * this.visitor.names.push(node.name); - * this.traverse(path); - * } - * }); - */ - visit: { - enumerable: true, - value: types.visit - }, + inClass = true + classStart = i + reClassStart = re.length + re += c + continue - /** - * Reprint a modified syntax tree using as much of the original source - * code as possible. - */ - print: { - enumerable: true, - value: print - }, + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } - /** - * Print without attempting to reuse any original source code. - */ - prettyPrint: { - enumerable: false, - value: prettyPrint - }, + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - /** - * Customized version of require("ast-types"). - */ - types: { - enumerable: false, - value: types - }, + default: + // swallow any state char that wasn't consumed + clearStateChar() - /** - * Convenient command-line interface (see e.g. example/add-braces). - */ - run: { - enumerable: false, - value: run - } -}); + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } -}).call(this,require('_process')) -},{"./lib/parser":516,"./lib/printer":518,"./lib/types":519,"_process":803,"fs":789}],522:[function(require,module,exports){ -'use strict'; -var isFinite = require('is-finite'); + re += c -module.exports = function (str, n) { - if (typeof str !== 'string') { - throw new TypeError('Expected `input` to be a string'); - } + } // switch + } // for - if (n < 0 || !isFinite(n)) { - throw new TypeError('Expected `count` to be a positive finite number'); - } + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } - var ret = ''; + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } - do { - if (n & 1) { - ret += str; - } + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) - str += str; - } while ((n >>= 1)); + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - return ret; -}; + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -},{"is-finite":285}],523:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var isExtendedLengthPath = /^\\\\\?\\/.test(str); - var hasNonAscii = /[^\x00-\x80]+/.test(str); + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } - if (isExtendedLengthPath || hasNonAscii) { - return str; - } + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } - return str.replace(/\\/g, '/'); -}; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] -},{}],524:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) -var util = require('./util'); -var has = Object.prototype.hasOwnProperty; + nlLast += nlAfter -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet() { - this._array = []; - this._set = Object.create(null); -} + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe } - return set; -}; - -/** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ -ArraySet.prototype.size = function ArraySet_size() { - return Object.getOwnPropertyNames(this._set).length; -}; -/** - * Add the given string to this set. - * - * @param String aStr - */ -ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = util.toSetString(aStr); - var isDuplicate = has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - if (!isDuplicate) { - this._set[sStr] = idx; + + if (addPatternStart) { + re = patternStart + re } -}; -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet.prototype.has = function ArraySet_has(aStr) { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); -}; + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } -/** - * What is the index of the given string in the array? - * - * @param String aStr - */ -ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) } - throw new Error('"' + aStr + '" is not in the set.'); -}; -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } - throw new Error('No element indexed by ' + aIdx); -}; -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; + regExp._glob = pattern + regExp._src = re -exports.ArraySet = ArraySet; + return regExp +} -},{"./util":533}],525:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} -var base64 = require('./base64'); +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set -var VLQ_BASE_SHIFT = 5; + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp } -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } + if (f === '/' && partial) return true - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } + var options = this.options - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) -},{"./base64":526}],526:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + var set = this.set + this.debug(this.pattern, 'set', set) -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break } - throw new TypeError("Must be between 0 and 63: " + number); -}; -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } - var littleA = 97; // 'a' - var littleZ = 122; // 'z' + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} - var zero = 48; // '0' - var nine = 57; // '9' +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options - var plus = 43; // '+' - var slash = 47; // '/' + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - var littleOffset = 26; - var numberOffset = 52; + this.debug('matchOne', file.length, pattern.length) - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } + this.debug(pattern, p, f) - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false - // 62: + - if (charCode == plus) { - return 62; - } + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) - // 63: / - if (charCode == slash) { - return 63; - } + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } - // Invalid base64 digit. - return -1; -}; + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -},{}],527:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false } - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) } else { - return aLow < 0 ? -1 : aLow; + hit = f.match(p) + this.debug('pattern match', p, f, hit) } - } -} -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; + if (!hit) return false } - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd } - return index; -}; - -},{}],528:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); + // should be unreachable. + throw new Error('wtf?') +} -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') } -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } +},{"brace-expansion":189,"path":13}],545:[function(require,module,exports){ /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. + * Helpers. */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. + * Parse or format the given `val`. * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); } - return this._array; + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); }; -exports.MappingList = MappingList; - -},{"./util":533}],529:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. + * Parse the given `str` and return milliseconds. * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. + * @param {String} str + * @return {Number} + * @api private */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } /** - * The Quick Sort algorithm. + * Short format for `ms`. * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array + * @param {Number} ms + * @return {String} + * @api private */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Sort the given array in-place with the given comparator function. + * Long format for `ms`. * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. + * @param {Number} ms + * @return {String} + * @api private */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; -},{}],530:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -var util = require('./util'); -var binarySearch = require('./binary-search'); -var ArraySet = require('./array-set').ArraySet; -var base64VLQ = require('./base64-vlq'); -var quickSort = require('./quick-sort').quickSort; +/** + * Pluralization helper. + */ -function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); +function plural(ms, n, name) { + if (ms < n) { + return; } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } -SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); +},{}],546:[function(require,module,exports){ +'use strict'; +module.exports = Number.isNaN || function (x) { + return x !== x; +}; + +},{}],547:[function(require,module,exports){ +(function (process){ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; } -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer.prototype._version = 3; +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; - return this.__generatedMappings; - } -}); +}).call(this,require('_process')) +},{"_process":15}],548:[function(require,module,exports){ +"use strict"; -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } +var originalObject = Object; +var originalDefProp = Object.defineProperty; +var originalCreate = Object.create; - return this.__originalMappings; +function defProp(obj, name, value) { + if (originalDefProp) try { + originalDefProp.call(originalObject, obj, name, { value: value }); + } catch (definePropertyIsBrokenInIE8) { + obj[name] = value; + } else { + obj[name] = value; } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; +} -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; +// For functions that will be invoked using .call or .apply, we need to +// define those methods on the function objects themselves, rather than +// inheriting them from Function.prototype, so that a malicious or clumsy +// third party cannot interfere with the functionality of this module by +// redefining Function.prototype.call or .apply. +function makeSafeToCall(fun) { + if (fun) { + defProp(fun, "call", fun.call); + defProp(fun, "apply", fun.apply); + } + return fun; +} -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; +makeSafeToCall(originalDefProp); +makeSafeToCall(originalCreate); -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; +var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); +var numToStr = makeSafeToCall(Number.prototype.toString); +var strSlice = makeSafeToCall(String.prototype.slice); -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; +var cloner = function(){}; +function create(prototype) { + if (originalCreate) { + return originalCreate.call(originalObject, prototype); + } + cloner.prototype = prototype || null; + return new cloner; +} - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } +var rand = Math.random; +var uniqueKeys = create(null); - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; +function makeUniqueKey() { + // Collisions are highly unlikely, but this module is in the business of + // making guarantees rather than safe bets. + do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); + while (hasOwn.call(uniqueKeys, uniqueKey)); + return uniqueKeys[uniqueKey] = uniqueKey; +} -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); +function internString(str) { + var obj = {}; + obj[str] = true; + return Object.keys(obj)[0]; +} - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; +// External users might find this function useful, but it is not necessary +// for the typical use of this module. +exports.makeUniqueKey = makeUniqueKey; - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; +// Object.getOwnPropertyNames is the only way to enumerate non-enumerable +// properties, so if we wrap it to ignore our secret keys, there should be +// no way (except guessing) to access those properties. +var originalGetOPNs = Object.getOwnPropertyNames; +Object.getOwnPropertyNames = function getOwnPropertyNames(object) { + for (var names = originalGetOPNs(object), + src = 0, + dst = 0, + len = names.length; + src < len; + ++src) { + if (!hasOwn.call(uniqueKeys, names[src])) { + if (src > dst) { + names[dst] = names[src]; + } + ++dst; } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; + } + names.length = dst; + return names; +}; - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; +function defaultCreatorFn(object) { + return create(null); +} - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); +function makeAccessor(secretCreatorFn) { + var brand = makeUniqueKey(); + var passkey = create(null); - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; + secretCreatorFn = secretCreatorFn || defaultCreatorFn; - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); + function register(object) { + var secret; // Created lazily. - mapping = this._originalMappings[++index]; - } + function vault(key, forget) { + // Only code that has access to the passkey can retrieve (or forget) + // the secret object. + if (key === passkey) { + return forget + ? secret = null + : secret || (secret = secretCreatorFn(object)); } } - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + defProp(object, brand, vault); } - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); + function accessor(object) { + if (!hasOwn.call(object, brand)) + register(object); + return object[brand](passkey); } - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); + accessor.forget = function(object) { + if (hasOwn.call(object, brand)) + object[brand](passkey, true); + }; - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; + return accessor; } -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } +exports.makeAccessor = makeAccessor; - destOriginalMappings.push(destMapping); - } +},{}],549:[function(require,module,exports){ +var assert = require("assert"); +var types = require("./types"); +var n = types.namedTypes; +var isArray = types.builtInTypes.array; +var isObject = types.builtInTypes.object; +var linesModule = require("./lines"); +var fromString = linesModule.fromString; +var Lines = linesModule.Lines; +var concat = linesModule.concat; +var util = require("./util"); +var comparePos = util.comparePos; +var childNodesCacheKey = require("private").makeUniqueKey(); - destGeneratedMappings.push(destMapping); +// TODO Move a non-caching implementation of this function into ast-types, +// and implement a caching wrapper function here. +function getSortedChildNodes(node, lines, resultArray) { + if (!node) { + return; } - quickSort(smc.__originalMappings, util.compareByOriginalPositions); + // The .loc checks below are sensitive to some of the problems that + // are fixed by this utility function. Specifically, if it decides to + // set node.loc to null, indicating that the node's .loc information + // is unreliable, then we don't want to add node to the resultArray. + util.fixFaultyLocations(node, lines); - return smc; - }; + if (resultArray) { + if (n.Node.check(node) && + n.SourceLocation.check(node.loc)) { + // This reverse insertion sort almost always takes constant + // time because we almost always (maybe always?) append the + // nodes in order anyway. + for (var i = resultArray.length - 1; i >= 0; --i) { + if (comparePos(resultArray[i].loc.end, + node.loc.start) <= 0) { + break; + } + } + resultArray.splice(i + 1, 0, node); + return; + } + } else if (node[childNodesCacheKey]) { + return node[childNodesCacheKey]; + } -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; + var names; + if (isArray.check(node)) { + names = Object.keys(node); + } else if (isObject.check(node)) { + names = types.getFieldNames(node); + } else { + return; + } -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } -}); + if (!resultArray) { + Object.defineProperty(node, childNodesCacheKey, { + value: resultArray = [], + enumerable: false + }); + } -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; + for (var i = 0, nameCount = names.length; i < nameCount; ++i) { + getSortedChildNodes(node[names[i]], lines, resultArray); + } + + return resultArray; } -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; +// As efficiently as possible, decorate the comment object with +// .precedingNode, .enclosingNode, and/or .followingNode properties, at +// least one of which is guaranteed to be defined. +function decorateComment(node, comment, lines) { + var childNodes = getSortedChildNodes(node, lines); - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; + // Time to dust off the old binary search robes and wizard hat. + var left = 0, right = childNodes.length; + while (left < right) { + var middle = (left + right) >> 1; + var child = childNodes[middle]; - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } + if (comparePos(child.loc.start, comment.loc.start) <= 0 && + comparePos(comment.loc.end, child.loc.end) <= 0) { + // The comment is completely contained by this child node. + decorateComment(comment.enclosingNode = child, comment, lines); + return; // Abandon the binary search at this level. } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } + if (comparePos(child.loc.end, comment.loc.start) <= 0) { + // This child node falls completely before the comment. + // Because we will never consider this node or any nodes + // before it again, this node must be the closest preceding + // node we have encountered so far. + var precedingNode = child; + left = middle + 1; + continue; + } - cachedSegments[str] = segment; + if (comparePos(comment.loc.end, child.loc.start) <= 0) { + // This child node falls completely after the comment. + // Because we will never consider this node or any nodes after + // it again, this node must be the closest following node we + // have encountered so far. + var followingNode = child; + right = middle; + continue; } - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; + throw new Error("Comment location overlaps with node location"); + } - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; + if (precedingNode) { + comment.precedingNode = precedingNode; + } - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; + if (followingNode) { + comment.followingNode = followingNode; + } +} - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; +exports.attach = function(comments, ast, lines) { + if (!isArray.check(comments)) { + return; + } - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } + var tiesToBreak = []; - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } + comments.forEach(function(comment) { + comment.loc.lines = lines; + decorateComment(ast, comment, lines); - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; + var pn = comment.precedingNode; + var en = comment.enclosingNode; + var fn = comment.followingNode; - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; + if (pn && fn) { + var tieCount = tiesToBreak.length; + if (tieCount > 0) { + var lastTie = tiesToBreak[tieCount - 1]; -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. + assert.strictEqual( + lastTie.precedingNode === comment.precedingNode, + lastTie.followingNode === comment.followingNode + ); - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } + if (lastTie.followingNode !== comment.followingNode) { + breakTies(tiesToBreak, lines); + } + } - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; + tiesToBreak.push(comment); -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; + } else if (pn) { + // No contest: we have a trailing comment. + breakTies(tiesToBreak, lines); + addTrailingComment(pn, comment); - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; + } else if (fn) { + // No contest: we have a leading comment. + breakTies(tiesToBreak, lines); + addLeadingComment(fn, comment); - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; + } else if (en) { + // The enclosing node has no child nodes at all, so what we + // have here is a dangling comment, e.g. [/* crickets */]. + breakTies(tiesToBreak, lines); + addDanglingComment(en, comment); + + } else { + throw new Error("AST contains no nodes at all?"); } - } + }); - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; + breakTies(tiesToBreak, lines); -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; + comments.forEach(function(comment) { + // These node references were useful for breaking ties, but we + // don't need them anymore, and they create cycles in the AST that + // may lead to infinite recursion if we don't delete them here. + delete comment.precedingNode; + delete comment.enclosingNode; + delete comment.followingNode; + }); +}; - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); +function breakTies(tiesToBreak, lines) { + var tieCount = tiesToBreak.length; + if (tieCount === 0) { + return; + } - if (index >= 0) { - var mapping = this._generatedMappings[index]; + var pn = tiesToBreak[0].precedingNode; + var fn = tiesToBreak[0].followingNode; + var gapEndPos = fn.loc.start; - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } + // Iterate backwards through tiesToBreak, examining the gaps + // between the tied comments. In order to qualify as leading, a + // comment must be separated from fn by an unbroken series of + // whitespace-only gaps (or other comments). + for (var indexOfFirstLeadingComment = tieCount; + indexOfFirstLeadingComment > 0; + --indexOfFirstLeadingComment) { + var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; + assert.strictEqual(comment.precedingNode, pn); + assert.strictEqual(comment.followingNode, fn); - return { - source: null, - line: null, - column: null, - name: null - }; - }; + var gap = lines.sliceString(comment.loc.end, gapEndPos); + if (/\S/.test(gap)) { + // The gap string contained something other than whitespace. + break; + } -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; + gapEndPos = comment.loc.start; } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; + while (indexOfFirstLeadingComment <= tieCount && + (comment = tiesToBreak[indexOfFirstLeadingComment]) && + // If the comment is a //-style comment and indented more + // deeply than the node itself, reconsider it as trailing. + (comment.type === "Line" || comment.type === "CommentLine") && + comment.loc.start.column > fn.loc.start.column) { + ++indexOfFirstLeadingComment; } - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } + tiesToBreak.forEach(function(comment, i) { + if (i < indexOfFirstLeadingComment) { + addTrailingComment(pn, comment); + } else { + addLeadingComment(fn, comment); + } + }); - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } + tiesToBreak.length = 0; +} - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } +function addCommentHelper(node, comment) { + var comments = node.comments || (node.comments = []); + comments.push(comment); +} - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } +function addLeadingComment(node, comment) { + comment.leading = true; + comment.trailing = false; + addCommentHelper(node, comment); +} - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; +function addDanglingComment(node, comment) { + comment.leading = false; + comment.trailing = false; + addCommentHelper(node, comment); +} -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); +function addTrailingComment(node, comment) { + comment.leading = false; + comment.trailing = true; + addCommentHelper(node, comment); +} - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; +function printLeadingComment(commentPath, print) { + var comment = commentPath.getValue(); + n.Comment.assert(comment); - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); + var loc = comment.loc; + var lines = loc && loc.lines; + var parts = [print(commentPath)]; - if (index >= 0) { - var mapping = this._originalMappings[index]; + if (comment.trailing) { + // When we print trailing comments as leading comments, we don't + // want to bring any trailing spaces along. + parts.push("\n"); - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } + } else if (lines instanceof Lines) { + var trailingSpace = lines.slice( + loc.end, + lines.skipSpaces(loc.end) + ); - return { - line: null, - column: null, - lastColumn: null - }; - }; + if (trailingSpace.length === 1) { + // If the trailing space contains no newlines, then we want to + // preserve it exactly as we found it. + parts.push(trailingSpace); + } else { + // If the trailing space contains newlines, then replace it + // with just that many newlines, with all other spaces removed. + parts.push(new Array(trailingSpace.length).join("\n")); + } -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + } else { + parts.push("\n"); + } -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } + return concat(parts); +} - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); +function printTrailingComment(commentPath, print) { + var comment = commentPath.getValue(commentPath); + n.Comment.assert(comment); - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } + var loc = comment.loc; + var lines = loc && loc.lines; + var parts = []; - this._sources = new ArraySet(); - this._names = new ArraySet(); + if (lines instanceof Lines) { + var fromPos = lines.skipSpaces(loc.start, true) || lines.firstPos(); + var leadingSpace = lines.slice(fromPos, loc.start); - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); + if (leadingSpace.length === 1) { + // If the leading space contains no newlines, then we want to + // preserve it exactly as we found it. + parts.push(leadingSpace); + } else { + // If the leading space contains newlines, then replace it + // with just that many newlines, sans all other spaces. + parts.push(new Array(leadingSpace.length).join("\n")); + } } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; + parts.push(print(commentPath)); - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); + return concat(parts); } -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; +exports.printComments = function(path, print) { + var value = path.getValue(); + var innerLines = print(path); + var comments = n.Node.check(value) && + types.getFieldValue(value, "comments"); -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } + if (!comments || comments.length === 0) { + return innerLines; } - return sources; - } -}); -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; + var leadingParts = []; + var trailingParts = [innerLines]; - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } + path.each(function(commentPath) { + var comment = commentPath.getValue(); + var leading = types.getFieldValue(comment, "leading"); + var trailing = types.getFieldValue(comment, "trailing"); - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; + if (leading || (trailing && !(n.Statement.check(value) || + comment.type === "Block" || + comment.type === "CommentBlock"))) { + leadingParts.push(printLeadingComment(commentPath, print)); + } else if (trailing) { + trailingParts.push(printTrailingComment(commentPath, print)); + } + }, "comments"); - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } + leadingParts.push.apply(leadingParts, trailingParts); + return concat(leadingParts); +}; - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; +},{"./lines":551,"./types":557,"./util":558,"assert":2,"private":548}],550:[function(require,module,exports){ +var assert = require("assert"); +var types = require("./types"); +var n = types.namedTypes; +var Node = n.Node; +var isArray = types.builtInTypes.array; +var isNumber = types.builtInTypes.number; -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; +function FastPath(value) { + assert.ok(this instanceof FastPath); + this.stack = [value]; +} -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; +var FPp = FastPath.prototype; +module.exports = FastPath; - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); +// Static convenience function for coercing a value to a FastPath. +FastPath.from = function(obj) { + if (obj instanceof FastPath) { + // Return a defensive copy of any existing FastPath instances. + return obj.copy(); } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } + if (obj instanceof types.NodePath) { + // For backwards compatibility, unroll NodePath instances into + // lightweight FastPath [..., name, value] stacks. + var copy = Object.create(FastPath.prototype); + var stack = [obj.value]; + for (var pp; (pp = obj.parentPath); obj = pp) + stack.push(obj.name, pp.value); + copy.stack = stack.reverse(); + return copy; } - return { - line: null, - column: null - }; - }; + // Otherwise use obj as the value of the new FastPath instance. + return new FastPath(obj); +}; -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; +FPp.copy = function copy() { + var copy = Object.create(FastPath.prototype); + copy.stack = this.stack.slice(0); + return copy; +}; - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); +// The name of the current property is always the penultimate element of +// this.stack, and always a String. +FPp.getName = function getName() { + var s = this.stack; + var len = s.length; + if (len > 1) { + return s[len - 2]; + } + // Since the name is always a string, null is a safe sentinel value to + // return if we do not know the name of the (root) value. + return null; +}; - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); +// The value of the current property is always the final element of +// this.stack. +FPp.getValue = function getValue() { + var s = this.stack; + return s[s.length - 1]; +}; - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; +function getNodeHelper(path, count) { + var s = path.stack; - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); + for (var i = s.length - 1; i >= 0; i -= 2) { + var value = s[i]; + if (n.Node.check(value) && --count < 0) { + return value; } - } } - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - -},{"./array-set":524,"./base64-vlq":525,"./binary-search":527,"./quick-sort":529,"./util":533}],531:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ + return null; +} -var base64VLQ = require('./base64-vlq'); -var util = require('./util'); -var ArraySet = require('./array-set').ArraySet; -var MappingList = require('./mapping-list').MappingList; +FPp.getNode = function getNode(count) { + return getNodeHelper(this, ~~count); +}; -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} +FPp.getParentNode = function getParentNode(count) { + return getNodeHelper(this, ~~count + 1); +}; -SourceMapGenerator.prototype._version = 3; +// The length of the stack can be either even or odd, depending on whether +// or not we have a name for the root value. The difference between the +// index of the root value and the index of the final value is always +// even, though, which allows us to return the root value in constant time +// (i.e. without iterating backwards through the stack). +FPp.getRootValue = function getRootValue() { + var s = this.stack; + if (s.length % 2 === 0) { + return s[1]; + } + return s[0]; +}; -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; +// Temporarily push properties named by string arguments given after the +// callback function onto this.stack, then call the callback with a +// reference to this (modified) FastPath object. Note that the stack will +// be restored to its original state after the callback is finished, so it +// is probably a mistake to retain a reference to the path. +FPp.call = function call(callback/*, name1, name2, ... */) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); + } + var result = callback(this); + s.length = origLen; + return result; +}; - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } +// Similar to FastPath.prototype.call, except that the value obtained by +// accessing this.getValue()[name1][name2]... should be array-like. The +// callback will be called with a reference to this path object for each +// element of the array. +FPp.each = function each(callback/*, name1, name2, ... */) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); + } - if (mapping.name != null) { - newMapping.name = mapping.name; + for (var i = 0; i < value.length; ++i) { + if (i in value) { + s.push(i, value[i]); + // If the callback needs to know the value of i, call + // path.getName(), assuming path is the parameter name. + callback(this); + s.length -= 2; } - } + } - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; + s.length = origLen; +}; -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); +// Similar to FastPath.prototype.each, except that the results of the +// callback function invocations are stored in an array and returned at +// the end of the iteration. +FPp.map = function map(callback/*, name1, name2, ... */) { + var s = this.stack; + var origLen = s.length; + var value = s[origLen - 1]; + var argc = arguments.length; - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); + for (var i = 1; i < argc; ++i) { + var name = arguments[i]; + value = value[name]; + s.push(name, value); } - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } + var result = new Array(value.length); + + for (var i = 0; i < value.length; ++i) { + if (i in value) { + s.push(i, value[i]); + result[i] = callback(this, i); + s.length -= 2; + } } - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } + s.length = origLen; + + return result; +}; + +// Inspired by require("ast-types").NodePath.prototype.needsParens, but +// more efficient because we're iterating backwards through a stack. +FPp.needsParens = function(assumeExpressionContext) { + var parent = this.getParentNode(); + if (!parent) { + return false; } - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; + var name = this.getName(); + var node = this.getNode(); -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); + // If the value of this path is some child of a Node and not a Node + // itself, then it doesn't need parentheses. Only Node objects (in + // fact, only Expression nodes) need parentheses. + if (this.getValue() !== node) { + return false; } - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } + // Only statements don't need parentheses. + if (n.Statement.check(node)) { + return false; } - }; -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; + // Identifiers never need parentheses. + if (node.type === "Identifier") { + return false; } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); + + if (parent.type === "ParenthesizedExpression") { + return false; } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } + switch (node.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return parent.type === "MemberExpression" + && name === "object" + && parent.object === node; - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } + case "BinaryExpression": + case "LogicalExpression": + switch (parent.type) { + case "CallExpression": + return name === "callee" + && parent.callee === node; - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + return true; - }, this); - this._sources = newSources; - this._names = newNames; + case "MemberExpression": + return name === "object" + && parent.object === node; - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); + case "BinaryExpression": + case "LogicalExpression": + var po = parent.operator; + var pp = PRECEDENCE[po]; + var no = node.operator; + var np = PRECEDENCE[no]; + + if (pp > np) { + return true; + } + + if (pp === np && name === "right") { + assert.strictEqual(parent.right, node); + return true; + } + + default: + return false; } - this.setSourceContent(sourceFile, content); - } - }, this); - }; -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; + case "SequenceExpression": + switch (parent.type) { + case "ReturnStatement": + return false; -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' + case "ExpressionStatement": + return name !== "expression"; - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; + + case "YieldExpression": + switch (parent.type) { + case "BinaryExpression": + case "LogicalExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "CallExpression": + case "MemberExpression": + case "NewExpression": + case "ConditionalExpression": + case "YieldExpression": + return true; + + default: + return false; } - } - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; + case "IntersectionTypeAnnotation": + case "UnionTypeAnnotation": + return parent.type === "NullableTypeAnnotation"; - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; + case "Literal": + return parent.type === "MemberExpression" + && isNumber.check(node.value) + && name === "object" + && parent.object === node; - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; + case "AssignmentExpression": + case "ConditionalExpression": + switch (parent.type) { + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + return true; - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; + case "CallExpression": + return name === "callee" + && parent.callee === node; - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; + case "ConditionalExpression": + return name === "test" + && parent.test === node; + + case "MemberExpression": + return name === "object" + && parent.object === node; + + default: + return false; } - } - result += next; - } + case "ArrowFunctionExpression": + if(n.CallExpression.check(parent) && name === 'callee') { + return true; + } + if(n.MemberExpression.check(parent) && name === 'object') { + return true; + } - return result; - }; + return isBinary(parent); -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; + case "ObjectExpression": + if (parent.type === "ArrowFunctionExpression" && + name === "body") { + return true; + } -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + default: + if (parent.type === "NewExpression" && + name === "callee" && + parent.callee === node) { + return containsCallExpression(node); + } } - return map; - }; + if (assumeExpressionContext !== true && + !this.canBeFirstInStatement() && + this.firstInStatement()) + return true; -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; + return false; +}; -exports.SourceMapGenerator = SourceMapGenerator; +function isBinary(node) { + return n.BinaryExpression.check(node) + || n.LogicalExpression.check(node); +} -},{"./array-set":524,"./base64-vlq":525,"./mapping-list":528,"./util":533}],532:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +function isUnaryLike(node) { + return n.UnaryExpression.check(node) + // I considered making SpreadElement and SpreadProperty subtypes + // of UnaryExpression, but they're not really Expression nodes. + || (n.SpreadElement && n.SpreadElement.check(node)) + || (n.SpreadProperty && n.SpreadProperty.check(node)); +} -var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; -var util = require('./util'); +var PRECEDENCE = {}; +[["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%", "**"] +].forEach(function(tier, i) { + tier.forEach(function(op) { + PRECEDENCE[op] = i; + }); +}); -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; +function containsCallExpression(node) { + if (n.CallExpression.check(node)) { + return true; + } -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; + if (isArray.check(node)) { + return node.some(containsCallExpression); + } -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; + if (n.Node.check(node)) { + return types.someField(node, function(name, child) { + return containsCallExpression(child); + }); + } -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); + return false; } -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); +FPp.canBeFirstInStatement = function() { + var node = this.getNode(); + return !n.FunctionExpression.check(node) + && !n.ObjectExpression.check(node); +}; - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are removed from this array, by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var shiftNextLine = function() { - var lineContents = remainingLines.shift(); - // The last line of a file might not have a newline. - var newLine = remainingLines.shift() || ""; - return lineContents + newLine; - }; +FPp.firstInStatement = function() { + var s = this.stack; + var parentName, parent; + var childName, child; - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; + for (var i = s.length - 1; i >= 0; i -= 2) { + if (n.Node.check(s[i])) { + childName = parentName; + child = parent; + parentName = s[i - 1]; + parent = s[i]; + } - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; + if (!parent || !child) { + continue; + } - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[0]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[0] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; + if (n.BlockStatement.check(parent) && + parentName === "body" && + childName === 0) { + assert.strictEqual(parent.body[0], child); + return true; } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[0]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[0] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLines.length > 0) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.join("")); - } - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); + if (n.ExpressionStatement.check(parent) && + childName === "expression") { + assert.strictEqual(parent.expression, child); + return true; } - node.setSourceContent(sourceFile, content); - } - }); - return node; + if (n.SequenceExpression.check(parent) && + parentName === "expressions" && + childName === 0) { + assert.strictEqual(parent.expressions[0], child); + continue; + } - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; + if (n.CallExpression.check(parent) && + childName === "callee") { + assert.strictEqual(parent.callee, child); + continue; + } -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; + if (n.MemberExpression.check(parent) && + childName === "object") { + assert.strictEqual(parent.object, child); + continue; + } -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; + if (n.ConditionalExpression.check(parent) && + childName === "test") { + assert.strictEqual(parent.test, child); + continue; + } -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; + if (isBinary(parent) && + childName === "left") { + assert.strictEqual(parent.left, child); + continue; + } -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); + if (n.UnaryExpression.check(parent) && + !parent.prefix && + childName === "argument") { + assert.strictEqual(parent.argument, child); + continue; + } + + return false; } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; + return true; }; -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; +},{"./types":557,"assert":2}],551:[function(require,module,exports){ +var assert = require("assert"); +var sourceMap = require("source-map"); +var normalizeOptions = require("./options").normalize; +var secretKey = require("private").makeUniqueKey(); +var types = require("./types"); +var isString = types.builtInTypes.string; +var comparePos = require("./util").comparePos; +var Mapping = require("./mapping"); -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } +// Goals: +// 1. Minimize new string creation. +// 2. Keep (de)identation O(lines) time. +// 3. Permit negative indentations. +// 4. Enforce immutability. +// 5. No newline characters. - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; +function getSecret(lines) { + return lines[secretKey]; +} -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; +function Lines(infos, sourceFileName) { + assert.ok(this instanceof Lines); + assert.ok(infos.length > 0); -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column + if (sourceFileName) { + isString.assert(sourceFileName); + } else { + sourceFileName = null; + } + + Object.defineProperty(this, secretKey, { + value: { + infos: infos, + mappings: [], + name: sourceFileName, + cachedSourceMap: null } - }); - lastOriginalSource = null; - sourceMappingActive = false; + }); + + if (sourceFileName) { + getSecret(this).mappings.push(new Mapping(this, { + start: this.firstPos(), + end: this.lastPos() + })); } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); +} + +// Exposed for instanceof checks. The fromString function should be used +// to create new Lines objects. +exports.Lines = Lines; +var Lp = Lines.prototype; + +// These properties used to be assigned to each new object in the Lines +// constructor, but we can more efficiently stuff them into the secret and +// let these lazy accessors compute their values on-the-fly. +Object.defineProperties(Lp, { + length: { + get: function() { + return getSecret(this).infos.length; + } + }, + + name: { + get: function() { + return getSecret(this).name; } - } else { - generated.column++; - } } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); +}); - return { code: generated.code, map: map }; -}; +function copyLineInfo(info) { + return { + line: info.line, + indent: info.indent, + locked: info.locked, + sliceStart: info.sliceStart, + sliceEnd: info.sliceEnd + }; +} -exports.SourceNode = SourceNode; +var fromStringCache = {}; +var hasOwn = fromStringCache.hasOwnProperty; +var maxCacheKeyLen = 10; -},{"./source-map-generator":531,"./util":533}],533:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ +function countSpaces(spaces, tabWidth) { + var count = 0; + var len = spaces.length; -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; + for (var i = 0; i < len; ++i) { + switch (spaces.charCodeAt(i)) { + case 9: // '\t' + assert.strictEqual(typeof tabWidth, "number"); + assert.ok(tabWidth > 0); -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; + var next = Math.ceil(count / tabWidth) * tabWidth; + if (next === count) { + count += tabWidth; + } else { + count = next; + } -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; + break; -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; + case 11: // '\v' + case 12: // '\f' + case 13: // '\r' + case 0xfeff: // zero-width non-breaking space + // These characters contribute nothing to indentation. + break; -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; + case 32: // ' ' + default: // Treat all other whitespace like ' '. + count += 1; + break; + } } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); + return count; +} +exports.countSpaces = countSpaces; - if (path === '') { - path = isAbsolute ? '/' : '.'; - } +var leadingSpaceExp = /^\s*/; - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; +// As specified here: http://www.ecma-international.org/ecma-262/6.0/#sec-line-terminators +var lineTerminatorSeqExp = + /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/; /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. + * @param {Object} options - Options object that configures printing. */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } +function fromString(string, options) { + if (string instanceof Lines) + return string; - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } + string += ""; - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } + var tabWidth = options && options.tabWidth; + var tabless = string.indexOf("\t") < 0; + var locked = !! (options && options.locked); + var cacheable = !options && tabless && (string.length <= maxCacheKeyLen); - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } + assert.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string); - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + if (cacheable && hasOwn.call(fromStringCache, string)) + return fromStringCache[string]; - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; + var lines = new Lines(string.split(lineTerminatorSeqExp).map(function(line) { + var spaces = leadingSpaceExp.exec(line)[0]; + return { + line: line, + indent: countSpaces(spaces, tabWidth), + // Boolean indicating whether this line can be reindented. + locked: locked, + sliceStart: spaces.length, + sliceEnd: line.length + }; + }), normalizeOptions(options).sourceFileName); + + if (cacheable) + fromStringCache[string] = lines; + + return lines; } -exports.join = join; +exports.fromString = fromString; -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); +function isOnlyWhitespace(string) { + return !/\S/.test(string); +} + +Lp.toString = function(options) { + return this.sliceString(this.firstPos(), this.lastPos(), options); }; -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } +Lp.getSourceMap = function(sourceMapName, sourceRoot) { + if (!sourceMapName) { + // Although we could make up a name or generate an anonymous + // source map, instead we assume that any consumer who does not + // provide a name does not actually want a source map. + return null; + } - aRoot = aRoot.replace(/\/$/, ''); + var targetLines = this; - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; + function updateJSON(json) { + json = json || {}; + + isString.assert(sourceMapName); + json.file = sourceMapName; + + if (sourceRoot) { + isString.assert(sourceRoot); + json.sourceRoot = sourceRoot; + } + + return json; } - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; + var secret = getSecret(targetLines); + if (secret.cachedSourceMap) { + // Since Lines objects are immutable, we can reuse any source map + // that was previously generated. Nevertheless, we return a new + // JSON object here to protect the cached source map from outside + // modification. + return updateJSON(secret.cachedSourceMap.toJSON()); } - ++level; - } + var smg = new sourceMap.SourceMapGenerator(updateJSON()); + var sourcesToContents = {}; - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; + secret.mappings.forEach(function(mapping) { + var sourceCursor = mapping.sourceLines.skipSpaces( + mapping.sourceLoc.start + ) || mapping.sourceLines.lastPos(); -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); + var targetCursor = targetLines.skipSpaces( + mapping.targetLoc.start + ) || targetLines.lastPos(); -function identity (s) { - return s; -} + while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && + comparePos(targetCursor, mapping.targetLoc.end) < 0) { -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } + var sourceChar = mapping.sourceLines.charAt(sourceCursor); + var targetChar = targetLines.charAt(targetCursor); + assert.strictEqual(sourceChar, targetChar); - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; + var sourceName = mapping.sourceLines.name; -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } + // Add mappings one character at a time for maximum resolution. + smg.addMapping({ + source: sourceName, + original: { line: sourceCursor.line, + column: sourceCursor.column }, + generated: { line: targetCursor.line, + column: targetCursor.column } + }); - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; + if (!hasOwn.call(sourcesToContents, sourceName)) { + var sourceContent = mapping.sourceLines.toString(); + smg.setSourceContent(sourceName, sourceContent); + sourcesToContents[sourceName] = sourceContent; + } -function isProtoString(s) { - if (!s) { - return false; - } + targetLines.nextPos(targetCursor, true); + mapping.sourceLines.nextPos(sourceCursor, true); + } + }); - var length = s.length; + secret.cachedSourceMap = smg; - if (length < 9 /* "__proto__".length */) { - return false; - } + return smg.toJSON(); +}; - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } +Lp.bootstrapCharAt = function(pos) { + assert.strictEqual(typeof pos, "object"); + assert.strictEqual(typeof pos.line, "number"); + assert.strictEqual(typeof pos.column, "number"); - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } + var line = pos.line, + column = pos.column, + strings = this.toString().split(lineTerminatorSeqExp), + string = strings[line - 1]; - return true; -} + if (typeof string === "undefined") + return ""; -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } + if (column === string.length && + line < strings.length) + return "\n"; + + if (column >= string.length) + return ""; + + return string.charAt(column); +}; + +Lp.charAt = function(pos) { + assert.strictEqual(typeof pos, "object"); + assert.strictEqual(typeof pos.line, "number"); + assert.strictEqual(typeof pos.column, "number"); + + var line = pos.line, + column = pos.column, + secret = getSecret(this), + infos = secret.infos, + info = infos[line - 1], + c = column; + + if (typeof info === "undefined" || c < 0) + return ""; + + var indent = this.getIndentAt(line); + if (c < indent) + return " "; + + c += info.sliceStart - indent; + + if (c === info.sliceEnd && + line < this.length) + return "\n"; + + if (c >= info.sliceEnd) + return ""; + + return info.line.charAt(c); +}; + +Lp.stripMargin = function(width, skipFirstLine) { + if (width === 0) + return this; + + assert.ok(width > 0, "negative margin: " + width); + + if (skipFirstLine && this.length === 1) + return this; + + var secret = getSecret(this); + + var lines = new Lines(secret.infos.map(function(info, i) { + if (info.line && (i > 0 || !skipFirstLine)) { + info = copyLineInfo(info); + info.indent = Math.max(0, info.indent - width); + } + return info; + })); + + if (secret.mappings.length > 0) { + var newMappings = getSecret(lines).mappings; + assert.strictEqual(newMappings.length, 0); + secret.mappings.forEach(function(mapping) { + newMappings.push(mapping.indent(width, skipFirstLine, true)); + }); + } - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } + return lines; +}; - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } +Lp.indent = function(by) { + if (by === 0) + return this; - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } + var secret = getSecret(this); - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } + var lines = new Lines(secret.infos.map(function(info) { + if (info.line && ! info.locked) { + info = copyLineInfo(info); + info.indent += by; + } + return info + })); - return mappingA.name - mappingB.name; -} -exports.compareByOriginalPositions = compareByOriginalPositions; + if (secret.mappings.length > 0) { + var newMappings = getSecret(lines).mappings; + assert.strictEqual(newMappings.length, 0); + secret.mappings.forEach(function(mapping) { + newMappings.push(mapping.indent(by)); + }); + } -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } + return lines; +}; - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } +Lp.indentTail = function(by) { + if (by === 0) + return this; - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } + if (this.length < 2) + return this; - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } + var secret = getSecret(this); - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } + var lines = new Lines(secret.infos.map(function(info, i) { + if (i > 0 && info.line && ! info.locked) { + info = copyLineInfo(info); + info.indent += by; + } - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + return info; + })); -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } + if (secret.mappings.length > 0) { + var newMappings = getSecret(lines).mappings; + assert.strictEqual(newMappings.length, 0); + secret.mappings.forEach(function(mapping) { + newMappings.push(mapping.indent(by, true)); + }); + } - if (aStr1 > aStr2) { - return 1; - } + return lines; +}; - return -1; -} +Lp.lockIndentTail = function () { + if (this.length < 2) { + return this; + } -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } + var infos = getSecret(this).infos; - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } + return new Lines(infos.map(function (info, i) { + info = copyLineInfo(info); + info.locked = i > 0; + return info; + })); +}; - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } +Lp.getIndentAt = function(line) { + assert.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); + var secret = getSecret(this), + info = secret.infos[line - 1]; + return Math.max(info.indent, 0); +}; - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } +Lp.guessTabWidth = function() { + var secret = getSecret(this); + if (hasOwn.call(secret, "cachedTabWidth")) { + return secret.cachedTabWidth; + } - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } + var counts = []; // Sparse array. + var lastIndent = 0; - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + for (var line = 1, last = this.length; line <= last; ++line) { + var info = secret.infos[line - 1]; + var sliced = info.line.slice(info.sliceStart, info.sliceEnd); -},{}],534:[function(require,module,exports){ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./lib/source-node').SourceNode; + // Whitespace-only lines don't tell us much about the likely tab + // width of this code. + if (isOnlyWhitespace(sliced)) { + continue; + } -},{"./lib/source-map-consumer":530,"./lib/source-map-generator":531,"./lib/source-node":532}],535:[function(require,module,exports){ -'use strict'; -var ansiRegex = require('ansi-regex')(); + var diff = Math.abs(info.indent - lastIndent); + counts[diff] = ~~counts[diff] + 1; + lastIndent = info.indent; + } -module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; -}; + var maxCount = -1; + var result = 2; -},{"ansi-regex":4}],536:[function(require,module,exports){ -(function (process){ -'use strict'; -var argv = process.argv; + for (var tabWidth = 1; + tabWidth < counts.length; + tabWidth += 1) { + if (hasOwn.call(counts, tabWidth) && + counts[tabWidth] > maxCount) { + maxCount = counts[tabWidth]; + result = tabWidth; + } + } -var terminator = argv.indexOf('--'); -var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); + return secret.cachedTabWidth = result; }; -module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } +// Determine if the list of lines has a first line that starts with a // +// or /* comment. If this is the case, the code may need to be wrapped in +// parens to avoid ASI issues. +Lp.startsWithComment = function () { + var secret = getSecret(this); + if (secret.infos.length === 0) { + return false; + } + var firstLineInfo = secret.infos[0], + sliceStart = firstLineInfo.sliceStart, + sliceEnd = firstLineInfo.sliceEnd, + firstLine = firstLineInfo.line.slice(sliceStart, sliceEnd).trim(); + return firstLine.length === 0 || + firstLine.slice(0, 2) === "//" || + firstLine.slice(0, 2) === "/*"; +}; - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } +Lp.isOnlyWhitespace = function() { + return isOnlyWhitespace(this.toString()); +}; - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } +Lp.isPrecededOnlyByWhitespace = function(pos) { + var secret = getSecret(this); + var info = secret.infos[pos.line - 1]; + var indent = Math.max(info.indent, 0); - if (process.stdout && !process.stdout.isTTY) { - return false; - } + var diff = pos.column - indent; + if (diff <= 0) { + // If pos.column does not exceed the indentation amount, then + // there must be only whitespace before it. + return true; + } - if (process.platform === 'win32') { - return true; - } + var start = info.sliceStart; + var end = Math.min(start + diff, info.sliceEnd); + var prefix = info.line.slice(start, end); - if ('COLORTERM' in process.env) { - return true; - } + return isOnlyWhitespace(prefix); +}; - if (process.env.TERM === 'dumb') { - return false; - } +Lp.getLineLength = function(line) { + var secret = getSecret(this), + info = secret.infos[line - 1]; + return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; +}; - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } +Lp.nextPos = function(pos, skipSpaces) { + var l = Math.max(pos.line, 0), + c = Math.max(pos.column, 0); - return false; -})(); + if (c < this.getLineLength(l)) { + pos.column += 1; -}).call(this,require('_process')) -},{"_process":803}],537:[function(require,module,exports){ -(function (process){ -var Stream = require('stream') + return skipSpaces + ? !!this.skipSpaces(pos, false, true) + : true; + } -// through -// -// a stream that does nothing but re-emit the input. -// useful for aggregating a series of changing but not ending streams into one stream) + if (l < this.length) { + pos.line += 1; + pos.column = 0; -exports = module.exports = through -through.through = through + return skipSpaces + ? !!this.skipSpaces(pos, false, true) + : true; + } -//create a readable writable stream. + return false; +}; -function through (write, end, opts) { - write = write || function (data) { this.queue(data) } - end = end || function () { this.queue(null) } +Lp.prevPos = function(pos, skipSpaces) { + var l = pos.line, + c = pos.column; - var ended = false, destroyed = false, buffer = [], _ended = false - var stream = new Stream() - stream.readable = stream.writable = true - stream.paused = false + if (c < 1) { + l -= 1; -// stream.autoPause = !(opts && opts.autoPause === false) - stream.autoDestroy = !(opts && opts.autoDestroy === false) + if (l < 1) + return false; - stream.write = function (data) { - write.call(this, data) - return !stream.paused - } + c = this.getLineLength(l); - function drain() { - while(buffer.length && !stream.paused) { - var data = buffer.shift() - if(null === data) - return stream.emit('end') - else - stream.emit('data', data) + } else { + c = Math.min(c - 1, this.getLineLength(l)); } - } - - stream.queue = stream.push = function (data) { -// console.error(ended) - if(_ended) return stream - if(data === null) _ended = true - buffer.push(data) - drain() - return stream - } - - //this will be registered as the first 'end' listener - //must call destroy next tick, to make sure we're after any - //stream piped from here. - //this is only a problem if end is not emitted synchronously. - //a nicer way to do this is to make sure this is the last listener for 'end' - - stream.on('end', function () { - stream.readable = false - if(!stream.writable && stream.autoDestroy) - process.nextTick(function () { - stream.destroy() - }) - }) - function _end () { - stream.writable = false - end.call(stream) - if(!stream.readable && stream.autoDestroy) - stream.destroy() - } + pos.line = l; + pos.column = c; - stream.end = function (data) { - if(ended) return - ended = true - if(arguments.length) stream.write(data) - _end() // will emit or queue - return stream - } + return skipSpaces + ? !!this.skipSpaces(pos, true, true) + : true; +}; - stream.destroy = function () { - if(destroyed) return - destroyed = true - ended = true - buffer.length = 0 - stream.writable = stream.readable = false - stream.emit('close') - return stream - } +Lp.firstPos = function() { + // Trivial, but provided for completeness. + return { line: 1, column: 0 }; +}; - stream.pause = function () { - if(stream.paused) return - stream.paused = true - return stream - } +Lp.lastPos = function() { + return { + line: this.length, + column: this.getLineLength(this.length) + }; +}; - stream.resume = function () { - if(stream.paused) { - stream.paused = false - stream.emit('resume') +Lp.skipSpaces = function(pos, backward, modifyInPlace) { + if (pos) { + pos = modifyInPlace ? pos : { + line: pos.line, + column: pos.column + }; + } else if (backward) { + pos = this.lastPos(); + } else { + pos = this.firstPos(); } - drain() - //may have become paused again, - //as drain emits 'data'. - if(!stream.paused) - stream.emit('drain') - return stream - } - return stream -} + if (backward) { + while (this.prevPos(pos)) { + if (!isOnlyWhitespace(this.charAt(pos)) && + this.nextPos(pos)) { + return pos; + } + } -}).call(this,require('_process')) -},{"_process":803,"stream":804}],538:[function(require,module,exports){ -'use strict'; -module.exports = function toFastproperties(o) { - function Sub() {} - Sub.prototype = o; - var receiver = new Sub(); // create an instance - function ic() { return typeof receiver.foo; } // perform access - ic(); - ic(); - return o; - eval("o" + o); // ensure no dead code elimination -} + return null; -},{}],539:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var tail = str.length; + } else { + while (isOnlyWhitespace(this.charAt(pos))) { + if (!this.nextPos(pos)) { + return null; + } + } - while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { - tail--; - } + return pos; + } +}; - return str.slice(0, tail); +Lp.trimLeft = function() { + var pos = this.skipSpaces(this.firstPos(), false, true); + return pos ? this.slice(pos) : emptyLines; }; -},{}],540:[function(require,module,exports){ -module.exports = { - plugins: [ - require("babel-plugin-syntax-async-functions"), - require("babel-plugin-syntax-async-generators"), - require("babel-plugin-transform-es2015-classes"), - require("babel-plugin-transform-es2015-arrow-functions"), - require("babel-plugin-transform-es2015-block-scoping"), - require("babel-plugin-transform-es2015-for-of"), - require("regenerator-transform").default - ] -}; - -},{"babel-plugin-syntax-async-functions":80,"babel-plugin-syntax-async-generators":81,"babel-plugin-transform-es2015-arrow-functions":82,"babel-plugin-transform-es2015-block-scoping":83,"babel-plugin-transform-es2015-classes":85,"babel-plugin-transform-es2015-for-of":88,"regenerator-transform":546}],541:[function(require,module,exports){ -(function (__dirname){ -exports.path = require("path").join( - __dirname, - "runtime.js" -); +Lp.trimRight = function() { + var pos = this.skipSpaces(this.lastPos(), true, true); + return pos ? this.slice(this.firstPos(), pos) : emptyLines; +}; + +Lp.trim = function() { + var start = this.skipSpaces(this.firstPos(), false, true); + if (start === null) + return emptyLines; -}).call(this,"/node_modules/regenerator-runtime") -},{"path":801}],542:[function(require,module,exports){ -// This method of obtaining a reference to the global object needs to be -// kept identical to the way it is obtained in runtime.js -var g = (function() { return this })() || Function("return this")(); + var end = this.skipSpaces(this.lastPos(), true, true); + assert.notStrictEqual(end, null); -// Use `getOwnPropertyNames` because not all browsers support calling -// `hasOwnProperty` on the global `self` object in a worker. See #183. -var hadRuntime = g.regeneratorRuntime && - Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; + return this.slice(start, end); +}; -// Save the old regeneratorRuntime in case it needs to be restored later. -var oldRuntime = hadRuntime && g.regeneratorRuntime; +Lp.eachPos = function(callback, startPos, skipSpaces) { + var pos = this.firstPos(); -// Force reevalutation of runtime.js. -g.regeneratorRuntime = undefined; + if (startPos) { + pos.line = startPos.line, + pos.column = startPos.column + } -module.exports = require("./runtime"); + if (skipSpaces && !this.skipSpaces(pos, false, true)) { + return; // Encountered nothing but spaces. + } -if (hadRuntime) { - // Restore the original runtime. - g.regeneratorRuntime = oldRuntime; -} else { - // Remove the global property added by runtime.js. - try { - delete g.regeneratorRuntime; - } catch(e) { - g.regeneratorRuntime = undefined; - } -} + do callback.call(this, pos); + while (this.nextPos(pos, skipSpaces)); +}; -},{"./runtime":543}],543:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ +Lp.bootstrapSlice = function(start, end) { + var strings = this.toString().split( + lineTerminatorSeqExp + ).slice( + start.line - 1, + end.line + ); -!(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } + strings.push(strings.pop().slice(0, end.column)); + strings[0] = strings[0].slice(start.column); - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + return fromString(strings.join("\n")); +}; - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); +Lp.slice = function(start, end) { + if (!end) { + if (!start) { + // The client seems to want a copy of this Lines object, but + // Lines objects are immutable, so it's perfectly adequate to + // return the same object. + return this; + } - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); + // Slice to the end if no end position was provided. + end = this.lastPos(); + } - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; + var secret = getSecret(this); + var sliced = secret.infos.slice(start.line - 1, end.line); + + if (start.line === end.line) { + sliced[0] = sliceInfo(sliced[0], start.column, end.column); + } else { + assert.ok(start.line < end.line); + sliced[0] = sliceInfo(sliced[0], start.column); + sliced.push(sliceInfo(sliced.pop(), 0, end.column)); } - } - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; + var lines = new Lines(sliced); - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; + if (secret.mappings.length > 0) { + var newMappings = getSecret(lines).mappings; + assert.strictEqual(newMappings.length, 0); + secret.mappings.forEach(function(mapping) { + var sliced = mapping.slice(this, start, end); + if (sliced) { + newMappings.push(sliced); + } + }, this); + } - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} + return lines; +}; - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; +function sliceInfo(info, startCol, endCol) { + var sliceStart = info.sliceStart; + var sliceEnd = info.sliceEnd; + var indent = Math.max(info.indent, 0); + var lineLength = indent + sliceEnd - sliceStart; - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } + if (typeof endCol === "undefined") { + endCol = lineLength; + } - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; + startCol = Math.max(startCol, 0); + endCol = Math.min(endCol, lineLength); + endCol = Math.max(endCol, startCol); - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + if (endCol < indent) { + indent = endCol; + sliceEnd = sliceStart; } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } + sliceEnd -= lineLength - endCol; } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } + lineLength = endCol; + lineLength -= startCol; - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } + if (startCol < indent) { + indent -= startCol; + } else { + startCol -= indent; + indent = 0; + sliceStart += startCol; + } - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); + assert.ok(indent >= 0); + assert.ok(sliceStart <= sliceEnd); + assert.strictEqual(lineLength, indent + sliceEnd - sliceStart); - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; + if (info.indent === indent && + info.sliceStart === sliceStart && + info.sliceEnd === sliceEnd) { + return info; + } - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; + return { + line: info.line, + indent: indent, + // A destructive slice always unlocks indentation. + locked: false, + sliceStart: sliceStart, + sliceEnd: sliceEnd + }; +} - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } +Lp.bootstrapSliceString = function(start, end, options) { + return this.slice(start, end).toString(options); +}; - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; +Lp.sliceString = function(start, end, options) { + if (!end) { + if (!start) { + // The client seems to want a copy of this Lines object, but + // Lines objects are immutable, so it's perfectly adequate to + // return the same object. + return this; } - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } + // Slice to the end if no end position was provided. + end = this.lastPos(); + } - context.method = method; - context.arg = arg; + options = normalizeOptions(options); - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } + var infos = getSecret(this).infos; + var parts = []; + var tabWidth = options.tabWidth; - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; + for (var line = start.line; line <= end.line; ++line) { + var info = infos[line - 1]; - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } + if (line === start.line) { + if (line === end.line) { + info = sliceInfo(info, start.column, end.column); + } else { + info = sliceInfo(info, start.column); + } + } else if (line === end.line) { + info = sliceInfo(info, 0, end.column); + } - context.dispatchException(context.arg); + var indent = Math.max(info.indent, 0); - } else if (context.method === "return") { - context.abrupt("return", context.arg); + var before = info.line.slice(0, info.sliceStart); + if (options.reuseWhitespace && + isOnlyWhitespace(before) && + countSpaces(before, options.tabWidth) === indent) { + // Reuse original spaces if the indentation is correct. + parts.push(info.line.slice(0, info.sliceEnd)); + continue; } - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; + var tabs = 0; + var spaces = indent; - if (record.arg === ContinueSentinel) { - continue; - } + if (options.useTabs) { + tabs = Math.floor(indent / tabWidth); + spaces -= tabs * tabWidth; + } - return { - value: record.arg, - done: context.done - }; + var result = ""; - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; + if (tabs > 0) { + result += new Array(tabs + 1).join("\t"); } - } - }; - } - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } + if (spaces > 0) { + result += new Array(spaces + 1).join(" "); } - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } + result += info.line.slice(info.sliceStart, info.sliceEnd); - return ContinueSentinel; + parts.push(result); } - var record = tryCatch(method, delegate.iterator, context.arg); + return parts.join(options.lineTerminator); +}; + +Lp.isEmpty = function() { + return this.length < 2 && this.getLineLength(1) < 1; +}; - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } +Lp.join = function(elements) { + var separator = this; + var separatorSecret = getSecret(separator); + var infos = []; + var mappings = []; + var prevInfo; - var info = record.arg; + function appendSecret(secret) { + if (secret === null) + return; - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } + if (prevInfo) { + var info = secret.infos[0]; + var indent = new Array(info.indent + 1).join(" "); + var prevLine = infos.length; + var prevColumn = Math.max(prevInfo.indent, 0) + + prevInfo.sliceEnd - prevInfo.sliceStart; - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; + prevInfo.line = prevInfo.line.slice( + 0, prevInfo.sliceEnd) + indent + info.line.slice( + info.sliceStart, info.sliceEnd); - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; + // If any part of a line is indentation-locked, the whole line + // will be indentation-locked. + prevInfo.locked = prevInfo.locked || info.locked; - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } + prevInfo.sliceEnd = prevInfo.line.length; - } else { - // Re-yield the result returned by the delegate method. - return info; + if (secret.mappings.length > 0) { + secret.mappings.forEach(function(mapping) { + mappings.push(mapping.add(prevLine, prevColumn)); + }); + } + + } else if (secret.mappings.length > 0) { + mappings.push.apply(mappings, secret.mappings); + } + + secret.infos.forEach(function(info, i) { + if (!prevInfo || i > 0) { + prevInfo = copyLineInfo(info); + infos.push(prevInfo); + } + }); } - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } + function appendWithSeparator(secret, i) { + if (i > 0) + appendSecret(separatorSecret); + appendSecret(secret); + } - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); + elements.map(function(elem) { + var lines = fromString(elem); + if (lines.isEmpty()) + return null; + return getSecret(lines); + }).forEach(separator.isEmpty() + ? appendSecret + : appendWithSeparator); - Gp[toStringTagSymbol] = "Generator"; + if (infos.length < 1) + return emptyLines; - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; + var lines = new Lines(infos); - Gp.toString = function() { - return "[object Generator]"; - }; + getSecret(lines).mappings = mappings; - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; + return lines; +}; - if (1 in locs) { - entry.catchLoc = locs[1]; - } +exports.concat = function(elements) { + return emptyLines.join(elements); +}; - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } +Lp.concat = function(other) { + var args = arguments, + list = [this]; + list.push.apply(list, args); + assert.strictEqual(list.length, args.length + 1); + return emptyLines.join(list); +}; - this.tryEntries.push(entry); - } +// The emptyLines object needs to be created all the way down here so that +// Lines.prototype will be fully populated. +var emptyLines = fromString(""); - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } +},{"./mapping":552,"./options":553,"./types":557,"./util":558,"assert":2,"private":548,"source-map":572}],552:[function(require,module,exports){ +var assert = require("assert"); +var types = require("./types"); +var isString = types.builtInTypes.string; +var isNumber = types.builtInTypes.number; +var SourceLocation = types.namedTypes.SourceLocation; +var Position = types.namedTypes.Position; +var linesModule = require("./lines"); +var comparePos = require("./util").comparePos; - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } +function Mapping(sourceLines, sourceLoc, targetLoc) { + assert.ok(this instanceof Mapping); + assert.ok(sourceLines instanceof linesModule.Lines); + SourceLocation.assert(sourceLoc); - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); + if (targetLoc) { + // In certain cases it's possible for targetLoc.{start,end}.column + // values to be negative, which technically makes them no longer + // valid SourceLocation nodes, so we need to be more forgiving. + assert.ok( + isNumber.check(targetLoc.start.line) && + isNumber.check(targetLoc.start.column) && + isNumber.check(targetLoc.end.line) && + isNumber.check(targetLoc.end.column) + ); + } else { + // Assume identity mapping if no targetLoc specified. + targetLoc = sourceLoc; } - keys.reverse(); - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } + Object.defineProperties(this, { + sourceLines: { value: sourceLines }, + sourceLoc: { value: sourceLoc }, + targetLoc: { value: targetLoc } + }); +} - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; +var Mp = Mapping.prototype; +module.exports = Mapping; - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } +Mp.slice = function(lines, start, end) { + assert.ok(lines instanceof linesModule.Lines); + Position.assert(start); - if (typeof iterable.next === "function") { - return iterable; - } + if (end) { + Position.assert(end); + } else { + end = lines.lastPos(); + } - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } + var sourceLines = this.sourceLines; + var sourceLoc = this.sourceLoc; + var targetLoc = this.targetLoc; - next.value = undefined; - next.done = true; + function skip(name) { + var sourceFromPos = sourceLoc[name]; + var targetFromPos = targetLoc[name]; + var targetToPos = start; - return next; - }; + if (name === "end") { + targetToPos = end; + } else { + assert.strictEqual(name, "start"); + } - return next.next = next; - } + return skipChars( + sourceLines, sourceFromPos, + lines, targetFromPos, targetToPos + ); } - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, + if (comparePos(start, targetLoc.start) <= 0) { + if (comparePos(targetLoc.end, end) <= 0) { + targetLoc = { + start: subtractPos(targetLoc.start, start.line, start.column), + end: subtractPos(targetLoc.end, start.line, start.column) + }; - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; + // The sourceLoc can stay the same because the contents of the + // targetLoc have not changed. - this.method = "next"; - this.arg = undefined; + } else if (comparePos(end, targetLoc.start) <= 0) { + return null; - this.tryEntries.forEach(resetTryEntry); + } else { + sourceLoc = { + start: sourceLoc.start, + end: skip("end") + }; - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } + targetLoc = { + start: subtractPos(targetLoc.start, start.line, start.column), + end: subtractPos(end, start.line, start.column) + }; } - } - }, - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } + } else { + if (comparePos(targetLoc.end, start) <= 0) { + return null; + } - return this.rval; - }, + if (comparePos(targetLoc.end, end) <= 0) { + sourceLoc = { + start: skip("start"), + end: sourceLoc.end + }; - dispatchException: function(exception) { - if (this.done) { - throw exception; - } + targetLoc = { + // Same as subtractPos(start, start.line, start.column): + start: { line: 1, column: 0 }, + end: subtractPos(targetLoc.end, start.line, start.column) + }; - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; + } else { + sourceLoc = { + start: skip("start"), + end: skip("end") + }; - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; + targetLoc = { + // Same as subtractPos(start, start.line, start.column): + start: { line: 1, column: 0 }, + end: subtractPos(end, start.line, start.column) + }; } + } - return !! caught; - } + return new Mapping(this.sourceLines, sourceLoc, targetLoc); +}; - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; +Mp.add = function(line, column) { + return new Mapping(this.sourceLines, this.sourceLoc, { + start: addPos(this.targetLoc.start, line, column), + end: addPos(this.targetLoc.end, line, column) + }); +}; - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } +function addPos(toPos, line, column) { + return { + line: toPos.line + line - 1, + column: (toPos.line === 1) + ? toPos.column + column + : toPos.column + }; +} - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); +Mp.subtract = function(line, column) { + return new Mapping(this.sourceLines, this.sourceLoc, { + start: subtractPos(this.targetLoc.start, line, column), + end: subtractPos(this.targetLoc.end, line, column) + }); +}; - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } +function subtractPos(fromPos, line, column) { + return { + line: fromPos.line - line + 1, + column: (fromPos.line === line) + ? fromPos.column - column + : fromPos.column + }; +} - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } +Mp.indent = function(by, skipFirstLine, noNegativeColumns) { + if (by === 0) { + return this; + } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } + var targetLoc = this.targetLoc; + var startLine = targetLoc.start.line; + var endLine = targetLoc.end.line; - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, + if (skipFirstLine && startLine === 1 && endLine === 1) { + return this; + } - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } + targetLoc = { + start: targetLoc.start, + end: targetLoc.end + }; - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } + if (!skipFirstLine || startLine > 1) { + var startColumn = targetLoc.start.column + by; + targetLoc.start = { + line: startLine, + column: noNegativeColumns + ? Math.max(0, startColumn) + : startColumn + }; + } - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; + if (!skipFirstLine || endLine > 1) { + var endColumn = targetLoc.end.column + by; + targetLoc.end = { + line: endLine, + column: noNegativeColumns + ? Math.max(0, endColumn) + : endColumn + }; + } - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } + return new Mapping(this.sourceLines, this.sourceLoc, targetLoc); +}; - return this.complete(record); - }, +function skipChars( + sourceLines, sourceFromPos, + targetLines, targetFromPos, targetToPos +) { + assert.ok(sourceLines instanceof linesModule.Lines); + assert.ok(targetLines instanceof linesModule.Lines); + Position.assert(sourceFromPos); + Position.assert(targetFromPos); + Position.assert(targetToPos); - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } + var targetComparison = comparePos(targetFromPos, targetToPos); + if (targetComparison === 0) { + // Trivial case: no characters to skip. + return sourceFromPos; + } - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } + if (targetComparison < 0) { + // Skipping forward. - return ContinueSentinel; - }, + var sourceCursor = sourceLines.skipSpaces(sourceFromPos); + var targetCursor = targetLines.skipSpaces(targetFromPos); - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; + var lineDiff = targetToPos.line - targetCursor.line; + sourceCursor.line += lineDiff; + targetCursor.line += lineDiff; + + if (lineDiff > 0) { + // If jumping to later lines, reset columns to the beginnings + // of those lines. + sourceCursor.column = 0; + targetCursor.column = 0; + } else { + assert.strictEqual(lineDiff, 0); } - } - }, - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; + while (comparePos(targetCursor, targetToPos) < 0 && + targetLines.nextPos(targetCursor, true)) { + assert.ok(sourceLines.nextPos(sourceCursor, true)); + assert.strictEqual( + sourceLines.charAt(sourceCursor), + targetLines.charAt(targetCursor) + ); } - } - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, + } else { + // Skipping backward. - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; + var sourceCursor = sourceLines.skipSpaces(sourceFromPos, true); + var targetCursor = targetLines.skipSpaces(targetFromPos, true); - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } + var lineDiff = targetToPos.line - targetCursor.line; + sourceCursor.line += lineDiff; + targetCursor.line += lineDiff; - return ContinueSentinel; - } - }; -})( - // In sloppy mode, unbound `this` refers to the global object, fallback to - // Function constructor if we're in global strict mode. That is sadly a form - // of indirect eval which violates Content Security Policy. - (function() { return this })() || Function("return this")() -); + if (lineDiff < 0) { + // If jumping to earlier lines, reset columns to the ends of + // those lines. + sourceCursor.column = sourceLines.getLineLength(sourceCursor.line); + targetCursor.column = targetLines.getLineLength(targetCursor.line); + } else { + assert.strictEqual(lineDiff, 0); + } -},{}],544:[function(require,module,exports){ -"use strict"; + while (comparePos(targetToPos, targetCursor) < 0 && + targetLines.prevPos(targetCursor, true)) { + assert.ok(sourceLines.prevPos(sourceCursor, true)); + assert.strictEqual( + sourceLines.charAt(sourceCursor), + targetLines.charAt(targetCursor) + ); + } + } -var _stringify = require("babel-runtime/core-js/json/stringify"); + return sourceCursor; +} -var _stringify2 = _interopRequireDefault(_stringify); +},{"./lines":551,"./types":557,"./util":558,"assert":2}],553:[function(require,module,exports){ +var defaults = { + // If you want to use a different branch of esprima, or any other + // module that supports a .parse function, pass that module object to + // recast.parse as options.parser (legacy synonym: options.esprima). + parser: require("esprima"), -var _assert = require("assert"); + // Number of spaces the pretty-printer should use per tab for + // indentation. If you do not pass this option explicitly, it will be + // (quite reliably!) inferred from the original code. + tabWidth: 4, -var _assert2 = _interopRequireDefault(_assert); + // If you really want the pretty-printer to use tabs instead of + // spaces, make this option true. + useTabs: false, -var _babelTypes = require("babel-types"); + // The reprinting code leaves leading whitespace untouched unless it + // has to reindent a line, or you pass false for this option. + reuseWhitespace: true, -var t = _interopRequireWildcard(_babelTypes); + // Override this option to use a different line terminator, e.g. \r\n. + lineTerminator: require("os").EOL, -var _leap = require("./leap"); + // Some of the pretty-printer code (such as that for printing function + // parameter lists) makes a valiant attempt to prevent really long + // lines. You can adjust the limit by changing this option; however, + // there is no guarantee that line length will fit inside this limit. + wrapColumn: 74, // Aspirational for now. -var leap = _interopRequireWildcard(_leap); + // Pass a string as options.sourceFileName to recast.parse to tell the + // reprinter to keep track of reused code so that it can construct a + // source map automatically. + sourceFileName: null, -var _meta = require("./meta"); + // Pass a string as options.sourceMapName to recast.print, and + // (provided you passed options.sourceFileName earlier) the + // PrintResult of recast.print will have a .map property for the + // generated source map. + sourceMapName: null, -var meta = _interopRequireWildcard(_meta); + // If provided, this option will be passed along to the source map + // generator as a root directory for relative source file paths. + sourceRoot: null, -var _util = require("./util"); + // If you provide a source map that was generated from a previous call + // to recast.print as options.inputSourceMap, the old source map will + // be composed with the new source map. + inputSourceMap: null, -var util = _interopRequireWildcard(_util); + // If you want esprima to generate .range information (recast only + // uses .loc internally), pass true for this option. + range: false, -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + // If you want esprima not to throw exceptions when it encounters + // non-fatal errors, keep this option true. + tolerant: true, -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // If you want to override the quotes used in string literals, specify + // either "single", "double", or "auto" here ("auto" will select the one + // which results in the shorter literal) + // Otherwise, double quotes are used. + quote: null, -var hasOwn = Object.prototype.hasOwnProperty; /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + // Controls the printing of trailing commas in object literals, + // array expressions and function parameters. + // + // This option could either be: + // * Boolean - enable/disable in all contexts (objects, arrays and function params). + // * Object - enable/disable per context. + // + // Example: + // trailingComma: { + // objects: true, + // arrays: true, + // parameters: false, + // } + trailingComma: false, -function Emitter(contextId) { - _assert2.default.ok(this instanceof Emitter); - t.assertIdentifier(contextId); + // Controls the printing of spaces inside array brackets. + // See: http://eslint.org/docs/rules/array-bracket-spacing + arrayBracketSpacing: false, - // Used to generate unique temporary names. - this.nextTempId = 0; + // Controls the printing of spaces inside object literals, + // destructuring assignments, and import/export specifiers. + // See: http://eslint.org/docs/rules/object-curly-spacing + objectCurlySpacing: true, - // In order to make sure the context object does not collide with - // anything in the local scope, we might have to rename it, so we - // refer to it symbolically instead of just assuming that it will be - // called "context". - this.contextId = contextId; + // If you want parenthesis to wrap single-argument arrow function parameter + // lists, pass true for this option. + arrowParensAlways: false, - // An append-only list of Statements that grows each time this.emit is - // called. - this.listing = []; + // There are 2 supported syntaxes (`,` and `;`) in Flow Object Types; + // The use of commas is in line with the more popular style and matches + // how objects are defined in JS, making it a bit more natural to write. + flowObjectCommas: true, +}, hasOwn = defaults.hasOwnProperty; - // A sparse array whose keys correspond to locations in this.listing - // that have been marked as branch/jump targets. - this.marked = [true]; +// Copy options and fill in default values. +exports.normalize = function(options) { + options = options || defaults; - // The last location will be marked when this.getDispatchLoop is - // called. - this.finalLoc = loc(); + function get(key) { + return hasOwn.call(options, key) + ? options[key] + : defaults[key]; + } - // A list of all leap.TryEntry statements emitted. - this.tryEntries = []; + return { + tabWidth: +get("tabWidth"), + useTabs: !!get("useTabs"), + reuseWhitespace: !!get("reuseWhitespace"), + lineTerminator: get("lineTerminator"), + wrapColumn: Math.max(get("wrapColumn"), 0), + sourceFileName: get("sourceFileName"), + sourceMapName: get("sourceMapName"), + sourceRoot: get("sourceRoot"), + inputSourceMap: get("inputSourceMap"), + parser: get("esprima") || get("parser"), + range: get("range"), + tolerant: get("tolerant"), + quote: get("quote"), + trailingComma: get("trailingComma"), + arrayBracketSpacing: get("arrayBracketSpacing"), + objectCurlySpacing: get("objectCurlySpacing"), + arrowParensAlways: get("arrowParensAlways"), + flowObjectCommas: get("flowObjectCommas"), + }; +}; - // Each time we evaluate the body of a loop, we tell this.leapManager - // to enter a nested loop context that determines the meaning of break - // and continue statements therein. - this.leapManager = new leap.LeapManager(this); -} +},{"esprima":314,"os":12}],554:[function(require,module,exports){ +var assert = require("assert"); +var types = require("./types"); +var n = types.namedTypes; +var b = types.builders; +var isObject = types.builtInTypes.object; +var isArray = types.builtInTypes.array; +var isFunction = types.builtInTypes.function; +var Patcher = require("./patcher").Patcher; +var normalizeOptions = require("./options").normalize; +var fromString = require("./lines").fromString; +var attachComments = require("./comments").attach; +var util = require("./util"); -var Ep = Emitter.prototype; -exports.Emitter = Emitter; +exports.parse = function parse(source, options) { + options = normalizeOptions(options); -// Offsets into this.listing that could be used as targets for branches or -// jumps are represented as numeric Literal nodes. This representation has -// the amazingly convenient benefit of allowing the exact value of the -// location to be determined at any time, even after generating code that -// refers to the location. -function loc() { - return t.numericLiteral(-1); -} + var lines = fromString(source, options); -// Sets the exact value of the given location to the offset of the next -// Statement emitted. -Ep.mark = function (loc) { - t.assertLiteral(loc); - var index = this.listing.length; - if (loc.value === -1) { - loc.value = index; - } else { - // Locations can be marked redundantly, but their values cannot change - // once set the first time. - _assert2.default.strictEqual(loc.value, index); - } - this.marked[index] = true; - return loc; -}; + var sourceWithoutTabs = lines.toString({ + tabWidth: options.tabWidth, + reuseWhitespace: false, + useTabs: false + }); -Ep.emit = function (node) { - if (t.isExpression(node)) { - node = t.expressionStatement(node); - } + var comments = []; + var program = options.parser.parse(sourceWithoutTabs, { + jsx: true, + loc: true, + locations: true, + range: options.range, + comment: true, + onComment: comments, + tolerant: options.tolerant, + ecmaVersion: 6, + sourceType: 'module' + }); - t.assertStatement(node); - this.listing.push(node); -}; + // If the source was empty, some parsers give loc.{start,end}.line + // values of 0, instead of the minimum of 1. + util.fixFaultyLocations(program, lines); -// Shorthand for emitting assignment statements. This will come in handy -// for assignments to temporary variables. -Ep.emitAssign = function (lhs, rhs) { - this.emit(this.assign(lhs, rhs)); - return lhs; -}; + program.loc = program.loc || { + start: lines.firstPos(), + end: lines.lastPos() + }; -// Shorthand for an assignment statement. -Ep.assign = function (lhs, rhs) { - return t.expressionStatement(t.assignmentExpression("=", lhs, rhs)); -}; + program.loc.lines = lines; + program.loc.indent = 0; -// Convenience function for generating expressions like context.next, -// context.sent, and context.rval. -Ep.contextProperty = function (name, computed) { - return t.memberExpression(this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed); -}; + // Expand the Program node's .loc to include all comments, since + // typically its .loc.start and .loc.end will coincide with those of the + // first and last statements, respectively, excluding any comments that + // fall outside that region. + var trueProgramLoc = util.getTrueLoc(program, lines); + program.loc.start = trueProgramLoc.start; + program.loc.end = trueProgramLoc.end; -// Shorthand for setting context.rval and jumping to `context.stop()`. -Ep.stop = function (rval) { - if (rval) { - this.setReturnValue(rval); + if (program.comments) { + comments = program.comments; + delete program.comments; } - this.jump(this.finalLoc); -}; + // In order to ensure we reprint leading and trailing program comments, + // wrap the original Program node with a File node. + var file = program; + if (file.type === "Program") { + var file = b.file(program, options.sourceFileName || null); + file.loc = { + lines: lines, + indent: 0, + start: lines.firstPos(), + end: lines.lastPos() + }; + } else if (file.type === "File") { + program = file.program; + } -Ep.setReturnValue = function (valuePath) { - t.assertExpression(valuePath.value); + // Passing file.program here instead of just file means that initial + // comments will be attached to program.body[0] instead of program. + attachComments( + comments, + program.body.length ? file.program : file, + lines + ); - this.emitAssign(this.contextProperty("rval"), this.explodeExpression(valuePath)); + // Return a copy of the original AST so that any changes made may be + // compared to the original. + return new TreeCopier(lines).copy(file); }; -Ep.clearPendingException = function (tryLoc, assignee) { - t.assertLiteral(tryLoc); +function TreeCopier(lines) { + assert.ok(this instanceof TreeCopier); + this.lines = lines; + this.indent = 0; +} - var catchCall = t.callExpression(this.contextProperty("catch", true), [tryLoc]); +var TCp = TreeCopier.prototype; - if (assignee) { - this.emitAssign(assignee, catchCall); - } else { - this.emit(catchCall); +TCp.copy = function(node) { + if (isArray.check(node)) { + return node.map(this.copy, this); } -}; - -// Emits code for an unconditional jump to the given location, even if the -// exact value of the location is not yet known. -Ep.jump = function (toLoc) { - this.emitAssign(this.contextProperty("next"), toLoc); - this.emit(t.breakStatement()); -}; - -// Conditional jump. -Ep.jumpIf = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); - - this.emit(t.ifStatement(test, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; - -// Conditional jump, with the condition negated. -Ep.jumpIfNot = function (test, toLoc) { - t.assertExpression(test); - t.assertLiteral(toLoc); - var negatedTest = void 0; - if (t.isUnaryExpression(test) && test.operator === "!") { - // Avoid double negation. - negatedTest = test.argument; - } else { - negatedTest = t.unaryExpression("!", test); + if (!isObject.check(node)) { + return node; } - this.emit(t.ifStatement(negatedTest, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); -}; - -// Returns a unique MemberExpression that can be used to store and -// retrieve temporary values. Since the object of the member expression is -// the context object, which is presumed to coexist peacefully with all -// other local variables, and since we just increment `nextTempId` -// monotonically, uniqueness is assured. -Ep.makeTempVar = function () { - return this.contextProperty("t" + this.nextTempId++); -}; - -Ep.getContextFunction = function (id) { - return t.functionExpression(id || null /*Anonymous*/ - , [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! - false // Nor an expression. - ); -}; - -// Turns this.listing into a loop of the form -// -// while (1) switch (context.next) { -// case 0: -// ... -// case n: -// return context.stop(); -// } -// -// Each marked location in this.listing will correspond to one generated -// case statement. -Ep.getDispatchLoop = function () { - var self = this; - var cases = []; - var current = void 0; - - // If we encounter a break, continue, or return statement in a switch - // case, we can skip the rest of the statements until the next case. - var alreadyEnded = false; + util.fixFaultyLocations(node, this.lines); - self.listing.forEach(function (stmt, i) { - if (self.marked.hasOwnProperty(i)) { - cases.push(t.switchCase(t.numericLiteral(i), current = [])); - alreadyEnded = false; + var copy = Object.create(Object.getPrototypeOf(node), { + original: { // Provide a link from the copy to the original. + value: node, + configurable: false, + enumerable: false, + writable: true } + }); - if (!alreadyEnded) { - current.push(stmt); - if (t.isCompletionStatement(stmt)) alreadyEnded = true; + var loc = node.loc; + var oldIndent = this.indent; + var newIndent = oldIndent; + + if (loc) { + // When node is a comment, we set node.loc.indent to + // node.loc.start.column so that, when/if we print the comment by + // itself, we can strip that much whitespace from the left margin of + // the comment. This only really matters for multiline Block comments, + // but it doesn't hurt for Line comments. + if (node.type === "Block" || node.type === "Line" || + node.type === "CommentBlock" || node.type === "CommentLine" || + this.lines.isPrecededOnlyByWhitespace(loc.start)) { + newIndent = this.indent = loc.start.column; } - }); - // Now that we know how many statements there will be in this.listing, - // we can finally resolve this.finalLoc.value. - this.finalLoc.value = this.listing.length; + loc.lines = this.lines; + loc.indent = newIndent; + } - cases.push(t.switchCase(this.finalLoc, [ - // Intentionally fall through to the "end" case... - ]), + var keys = Object.keys(node); + var keyCount = keys.length; + for (var i = 0; i < keyCount; ++i) { + var key = keys[i]; + if (key === "loc") { + copy[key] = node[key]; + } else if (key === "tokens" && + node.type === "File") { + // Preserve file.tokens (uncopied) in case client code cares about + // it, even though Recast ignores it when reprinting. + copy[key] = node[key]; + } else { + copy[key] = this.copy(node[key]); + } + } - // So that the runtime can jump to the final location without having - // to know its offset, we provide the "end" case as a synonym. - t.switchCase(t.stringLiteral("end"), [ - // This will check/clear both context.thrown and context.rval. - t.returnStatement(t.callExpression(this.contextProperty("stop"), []))])); + this.indent = oldIndent; - return t.whileStatement(t.numericLiteral(1), t.switchStatement(t.assignmentExpression("=", this.contextProperty("prev"), this.contextProperty("next")), cases)); + return copy; }; -Ep.getTryLocsList = function () { - if (this.tryEntries.length === 0) { - // To avoid adding a needless [] to the majority of runtime.wrap - // argument lists, force the caller to handle this case specially. - return null; - } +},{"./comments":549,"./lines":551,"./options":553,"./patcher":555,"./types":557,"./util":558,"assert":2}],555:[function(require,module,exports){ +var assert = require("assert"); +var linesModule = require("./lines"); +var types = require("./types"); +var getFieldValue = types.getFieldValue; +var Printable = types.namedTypes.Printable; +var Expression = types.namedTypes.Expression; +var ReturnStatement = types.namedTypes.ReturnStatement; +var SourceLocation = types.namedTypes.SourceLocation; +var util = require("./util"); +var comparePos = util.comparePos; +var FastPath = require("./fast-path"); +var isObject = types.builtInTypes.object; +var isArray = types.builtInTypes.array; +var isString = types.builtInTypes.string; +var riskyAdjoiningCharExp = /[0-9a-z_$]/i; - var lastLocValue = 0; +function Patcher(lines) { + assert.ok(this instanceof Patcher); + assert.ok(lines instanceof linesModule.Lines); - return t.arrayExpression(this.tryEntries.map(function (tryEntry) { - var thisLocValue = tryEntry.firstLoc.value; - _assert2.default.ok(thisLocValue >= lastLocValue, "try entries out of order"); - lastLocValue = thisLocValue; + var self = this, + replacements = []; - var ce = tryEntry.catchEntry; - var fe = tryEntry.finallyEntry; + self.replace = function(loc, lines) { + if (isString.check(lines)) + lines = linesModule.fromString(lines); - var locs = [tryEntry.firstLoc, - // The null here makes a hole in the array. - ce ? ce.firstLoc : null]; + replacements.push({ + lines: lines, + start: loc.start, + end: loc.end + }); + }; - if (fe) { - locs[2] = fe.firstLoc; - locs[3] = fe.afterLoc; - } + self.get = function(loc) { + // If no location is provided, return the complete Lines object. + loc = loc || { + start: { line: 1, column: 0 }, + end: { line: lines.length, + column: lines.getLineLength(lines.length) } + }; - return t.arrayExpression(locs); - })); -}; + var sliceFrom = loc.start, + toConcat = []; -// All side effects must be realized in order. + function pushSlice(from, to) { + assert.ok(comparePos(from, to) <= 0); + toConcat.push(lines.slice(from, to)); + } -// If any subexpression harbors a leap, all subexpressions must be -// neutered of side effects. + replacements.sort(function(a, b) { + return comparePos(a.start, b.start); + }).forEach(function(rep) { + if (comparePos(sliceFrom, rep.start) > 0) { + // Ignore nested replacement ranges. + } else { + pushSlice(sliceFrom, rep.start); + toConcat.push(rep.lines); + sliceFrom = rep.end; + } + }); -// No destructive modification of AST nodes. + pushSlice(sliceFrom, loc.end); -Ep.explode = function (path, ignoreResult) { - var node = path.node; - var self = this; + return linesModule.concat(toConcat); + }; +} +exports.Patcher = Patcher; - t.assertNode(node); +var Pp = Patcher.prototype; - if (t.isDeclaration(node)) throw getDeclError(node); +Pp.tryToReprintComments = function(newNode, oldNode, print) { + var patcher = this; - if (t.isStatement(node)) return self.explodeStatement(path); + if (!newNode.comments && + !oldNode.comments) { + // We were (vacuously) able to reprint all the comments! + return true; + } - if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); + var newPath = FastPath.from(newNode); + var oldPath = FastPath.from(oldNode); - switch (node.type) { - case "Program": - return path.get("body").map(self.explodeStatement, self); + newPath.stack.push("comments", getSurroundingComments(newNode)); + oldPath.stack.push("comments", getSurroundingComments(oldNode)); - case "VariableDeclarator": - throw getDeclError(node); + var reprints = []; + var ableToReprintComments = + findArrayReprints(newPath, oldPath, reprints); - // These node types should be handled by their parent nodes - // (ObjectExpression, SwitchStatement, and TryStatement, respectively). - case "Property": - case "SwitchCase": - case "CatchClause": - throw new Error(node.type + " nodes should be handled by their parents"); + // No need to pop anything from newPath.stack or oldPath.stack, since + // newPath and oldPath are fresh local variables. - default: - throw new Error("unknown Node of type " + (0, _stringify2.default)(node.type)); - } + if (ableToReprintComments && reprints.length > 0) { + reprints.forEach(function(reprint) { + var oldComment = reprint.oldPath.getValue(); + assert.ok(oldComment.leading || oldComment.trailing); + patcher.replace( + oldComment.loc, + // Comments can't have .comments, so it doesn't matter + // whether we print with comments or without. + print(reprint.newPath).indentTail(oldComment.loc.indent) + ); + }); + } + + return ableToReprintComments; }; -function getDeclError(node) { - return new Error("all declarations should have been transformed into " + "assignments before the Exploder began its work: " + (0, _stringify2.default)(node)); +// Get all comments that are either leading or trailing, ignoring any +// comments that occur inside node.loc. Returns an empty array for nodes +// with no leading or trailing comments. +function getSurroundingComments(node) { + var result = []; + if (node.comments && + node.comments.length > 0) { + node.comments.forEach(function(comment) { + if (comment.leading || comment.trailing) { + result.push(comment); + } + }); + } + return result; } -Ep.explodeStatement = function (path, labelId) { - var stmt = path.node; - var self = this; - var before = void 0, - after = void 0, - head = void 0; +Pp.deleteComments = function(node) { + if (!node.comments) { + return; + } - t.assertStatement(stmt); + var patcher = this; - if (labelId) { - t.assertIdentifier(labelId); - } else { - labelId = null; - } + node.comments.forEach(function(comment) { + if (comment.leading) { + // Delete leading comments along with any trailing whitespace + // they might have. + patcher.replace({ + start: comment.loc.start, + end: node.loc.lines.skipSpaces( + comment.loc.end, false, false) + }, ""); - // Explode BlockStatement nodes even if they do not contain a yield, - // because we don't want or need the curly braces. - if (t.isBlockStatement(stmt)) { - path.get("body").forEach(function (path) { - self.explodeStatement(path); + } else if (comment.trailing) { + // Delete trailing comments along with any leading whitespace + // they might have. + patcher.replace({ + start: node.loc.lines.skipSpaces( + comment.loc.start, true, false), + end: comment.loc.end + }, ""); + } }); - return; - } - - if (!meta.containsLeap(stmt)) { - // Technically we should be able to avoid emitting the statement - // altogether if !meta.hasSideEffects(stmt), but that leads to - // confusing generated code (for instance, `while (true) {}` just - // disappears) and is probably a more appropriate job for a dedicated - // dead code elimination pass. - self.emit(stmt); - return; - } - - switch (stmt.type) { - case "ExpressionStatement": - self.explodeExpression(path.get("expression"), true); - break; - - case "LabeledStatement": - after = loc(); - - // Did you know you can break from any labeled block statement or - // control structure? Well, you can! Note: when a labeled loop is - // encountered, the leap.LabeledEntry created here will immediately - // enclose a leap.LoopEntry on the leap manager's stack, and both - // entries will have the same label. Though this works just fine, it - // may seem a bit redundant. In theory, we could check here to - // determine if stmt knows how to handle its own label; for example, - // stmt happens to be a WhileStatement and so we know it's going to - // establish its own LoopEntry when we explode it (below). Then this - // LabeledEntry would be unnecessary. Alternatively, we might be - // tempted not to pass stmt.label down into self.explodeStatement, - // because we've handled the label here, but that's a mistake because - // labeled loops may contain labeled continue statements, which is not - // something we can handle in this generic case. All in all, I think a - // little redundancy greatly simplifies the logic of this case, since - // it's clear that we handle all possible LabeledStatements correctly - // here, regardless of whether they interact with the leap manager - // themselves. Also remember that labels and break/continue-to-label - // statements are rare, and all of this logic happens at transform - // time, so it has no additional runtime cost. - self.leapManager.withEntry(new leap.LabeledEntry(after, stmt.label), function () { - self.explodeStatement(path.get("body"), stmt.label); - }); +}; - self.mark(after); +exports.getReprinter = function(path) { + assert.ok(path instanceof FastPath); - break; + // Make sure that this path refers specifically to a Node, rather than + // some non-Node subproperty of a Node. + var node = path.getValue(); + if (!Printable.check(node)) + return; - case "WhileStatement": - before = loc(); - after = loc(); + var orig = node.original; + var origLoc = orig && orig.loc; + var lines = origLoc && origLoc.lines; + var reprints = []; - self.mark(before); - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - self.leapManager.withEntry(new leap.LoopEntry(after, before, labelId), function () { - self.explodeStatement(path.get("body")); - }); - self.jump(before); - self.mark(after); + if (!lines || !findReprints(path, reprints)) + return; - break; + return function(print) { + var patcher = new Patcher(lines); - case "DoWhileStatement": - var first = loc(); - var test = loc(); - after = loc(); + reprints.forEach(function(reprint) { + var newNode = reprint.newPath.getValue(); + var oldNode = reprint.oldPath.getValue(); - self.mark(first); - self.leapManager.withEntry(new leap.LoopEntry(after, test, labelId), function () { - self.explode(path.get("body")); - }); - self.mark(test); - self.jumpIf(self.explodeExpression(path.get("test")), first); - self.mark(after); + SourceLocation.assert(oldNode.loc, true); - break; + var needToPrintNewPathWithComments = + !patcher.tryToReprintComments(newNode, oldNode, print) - case "ForStatement": - head = loc(); - var update = loc(); - after = loc(); + if (needToPrintNewPathWithComments) { + // Since we were not able to preserve all leading/trailing + // comments, we delete oldNode's comments, print newPath + // with comments, and then patch the resulting lines where + // oldNode used to be. + patcher.deleteComments(oldNode); + } - if (stmt.init) { - // We pass true here to indicate that if stmt.init is an expression - // then we do not care about its result. - self.explode(path.get("init"), true); - } + var newLines = print( + reprint.newPath, + needToPrintNewPathWithComments + ).indentTail(oldNode.loc.indent); - self.mark(head); + var nls = needsLeadingSpace(lines, oldNode.loc, newLines); + var nts = needsTrailingSpace(lines, oldNode.loc, newLines); - if (stmt.test) { - self.jumpIfNot(self.explodeExpression(path.get("test")), after); - } else { - // No test means continue unconditionally. - } + // If we try to replace the argument of a ReturnStatement like + // return"asdf" with e.g. a literal null expression, we run + // the risk of ending up with returnnull, so we need to add an + // extra leading space in situations where that might + // happen. Likewise for "asdf"in obj. See #170. + if (nls || nts) { + var newParts = []; + nls && newParts.push(" "); + newParts.push(newLines); + nts && newParts.push(" "); + newLines = linesModule.concat(newParts); + } - self.leapManager.withEntry(new leap.LoopEntry(after, update, labelId), function () { - self.explodeStatement(path.get("body")); - }); + patcher.replace(oldNode.loc, newLines); + }); - self.mark(update); + // Recall that origLoc is the .loc of an ancestor node that is + // guaranteed to contain all the reprinted nodes and comments. + return patcher.get(origLoc).indentTail(-orig.loc.indent); + }; +}; - if (stmt.update) { - // We pass true here to indicate that if stmt.update is an - // expression then we do not care about its result. - self.explode(path.get("update"), true); - } +// If the last character before oldLoc and the first character of newLines +// are both identifier characters, they must be separated by a space, +// otherwise they will most likely get fused together into a single token. +function needsLeadingSpace(oldLines, oldLoc, newLines) { + var posBeforeOldLoc = util.copyPos(oldLoc.start); - self.jump(head); + // The character just before the location occupied by oldNode. + var charBeforeOldLoc = + oldLines.prevPos(posBeforeOldLoc) && + oldLines.charAt(posBeforeOldLoc); - self.mark(after); + // First character of the reprinted node. + var newFirstChar = newLines.charAt(newLines.firstPos()); - break; + return charBeforeOldLoc && + riskyAdjoiningCharExp.test(charBeforeOldLoc) && + newFirstChar && + riskyAdjoiningCharExp.test(newFirstChar); +} - case "TypeCastExpression": - return self.explodeExpression(path.get("expression")); +// If the last character of newLines and the first character after oldLoc +// are both identifier characters, they must be separated by a space, +// otherwise they will most likely get fused together into a single token. +function needsTrailingSpace(oldLines, oldLoc, newLines) { + // The character just after the location occupied by oldNode. + var charAfterOldLoc = oldLines.charAt(oldLoc.end); - case "ForInStatement": - head = loc(); - after = loc(); + var newLastPos = newLines.lastPos(); - var keyIterNextFn = self.makeTempVar(); - self.emitAssign(keyIterNextFn, t.callExpression(util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))])); + // Last character of the reprinted node. + var newLastChar = newLines.prevPos(newLastPos) && + newLines.charAt(newLastPos); - self.mark(head); + return newLastChar && + riskyAdjoiningCharExp.test(newLastChar) && + charAfterOldLoc && + riskyAdjoiningCharExp.test(charAfterOldLoc); +} - var keyInfoTmpVar = self.makeTempVar(); - self.jumpIf(t.memberExpression(t.assignmentExpression("=", keyInfoTmpVar, t.callExpression(keyIterNextFn, [])), t.identifier("done"), false), after); +function findReprints(newPath, reprints) { + var newNode = newPath.getValue(); + Printable.assert(newNode); - self.emitAssign(stmt.left, t.memberExpression(keyInfoTmpVar, t.identifier("value"), false)); + var oldNode = newNode.original; + Printable.assert(oldNode); - self.leapManager.withEntry(new leap.LoopEntry(after, head, labelId), function () { - self.explodeStatement(path.get("body")); - }); + assert.deepEqual(reprints, []); - self.jump(head); + if (newNode.type !== oldNode.type) { + return false; + } - self.mark(after); + var oldPath = new FastPath(oldNode); + var canReprint = findChildReprints(newPath, oldPath, reprints); - break; + if (!canReprint) { + // Make absolutely sure the calling code does not attempt to reprint + // any nodes. + reprints.length = 0; + } - case "BreakStatement": - self.emitAbruptCompletion({ - type: "break", - target: self.leapManager.getBreakLoc(stmt.label) - }); + return canReprint; +} - break; +function findAnyReprints(newPath, oldPath, reprints) { + var newNode = newPath.getValue(); + var oldNode = oldPath.getValue(); - case "ContinueStatement": - self.emitAbruptCompletion({ - type: "continue", - target: self.leapManager.getContinueLoc(stmt.label) - }); + if (newNode === oldNode) + return true; - break; + if (isArray.check(newNode)) + return findArrayReprints(newPath, oldPath, reprints); - case "SwitchStatement": - // Always save the discriminant into a temporary variable in case the - // test expressions overwrite values like context.sent. - var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); + if (isObject.check(newNode)) + return findObjectReprints(newPath, oldPath, reprints); - after = loc(); - var defaultLoc = loc(); - var condition = defaultLoc; - var caseLocs = []; + return false; +} - // If there are no cases, .cases might be undefined. - var cases = stmt.cases || []; +function findArrayReprints(newPath, oldPath, reprints) { + var newNode = newPath.getValue(); + var oldNode = oldPath.getValue(); + isArray.assert(newNode); + var len = newNode.length; - for (var i = cases.length - 1; i >= 0; --i) { - var c = cases[i]; - t.assertSwitchCase(c); + if (!(isArray.check(oldNode) && + oldNode.length === len)) + return false; - if (c.test) { - condition = t.conditionalExpression(t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition); - } else { - caseLocs[i] = defaultLoc; + for (var i = 0; i < len; ++i) { + newPath.stack.push(i, newNode[i]); + oldPath.stack.push(i, oldNode[i]); + var canReprint = findAnyReprints(newPath, oldPath, reprints); + newPath.stack.length -= 2; + oldPath.stack.length -= 2; + if (!canReprint) { + return false; } - } - - var discriminant = path.get("discriminant"); - util.replaceWithOrRemove(discriminant, condition); - self.jump(self.explodeExpression(discriminant)); + } - self.leapManager.withEntry(new leap.SwitchEntry(after), function () { - path.get("cases").forEach(function (casePath) { - var i = casePath.key; - self.mark(caseLocs[i]); + return true; +} - casePath.get("consequent").forEach(function (path) { - self.explodeStatement(path); - }); - }); - }); +function findObjectReprints(newPath, oldPath, reprints) { + var newNode = newPath.getValue(); + isObject.assert(newNode); - self.mark(after); - if (defaultLoc.value === -1) { - self.mark(defaultLoc); - _assert2.default.strictEqual(after.value, defaultLoc.value); - } + if (newNode.original === null) { + // If newNode.original node was set to null, reprint the node. + return false; + } - break; + var oldNode = oldPath.getValue(); + if (!isObject.check(oldNode)) + return false; - case "IfStatement": - var elseLoc = stmt.alternate && loc(); - after = loc(); + if (Printable.check(newNode)) { + if (!Printable.check(oldNode)) { + return false; + } - self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); + // Here we need to decide whether the reprinted code for newNode + // is appropriate for patching into the location of oldNode. - self.explodeStatement(path.get("consequent")); + if (newNode.type === oldNode.type) { + var childReprints = []; - if (elseLoc) { - self.jump(after); - self.mark(elseLoc); - self.explodeStatement(path.get("alternate")); - } + if (findChildReprints(newPath, oldPath, childReprints)) { + reprints.push.apply(reprints, childReprints); + } else if (oldNode.loc) { + // If we have no .loc information for oldNode, then we + // won't be able to reprint it. + reprints.push({ + oldPath: oldPath.copy(), + newPath: newPath.copy() + }); + } else { + return false; + } - self.mark(after); + return true; + } - break; + if (Expression.check(newNode) && + Expression.check(oldNode) && + // If we have no .loc information for oldNode, then we won't + // be able to reprint it. + oldNode.loc) { - case "ReturnStatement": - self.emitAbruptCompletion({ - type: "return", - value: self.explodeExpression(path.get("argument")) - }); + // If both nodes are subtypes of Expression, then we should be + // able to fill the location occupied by the old node with + // code printed for the new node with no ill consequences. + reprints.push({ + oldPath: oldPath.copy(), + newPath: newPath.copy() + }); - break; + return true; + } - case "WithStatement": - throw new Error("WithStatement not supported in generator functions."); + // The nodes have different types, and at least one of the types + // is not a subtype of the Expression type, so we cannot safely + // assume the nodes are syntactically interchangeable. + return false; + } - case "TryStatement": - after = loc(); + return findChildReprints(newPath, oldPath, reprints); +} - var handler = stmt.handler; +// This object is reused in hasOpeningParen and hasClosingParen to avoid +// having to allocate a temporary object. +var reusablePos = { line: 1, column: 0 }; +var nonSpaceExp = /\S/; - var catchLoc = handler && loc(); - var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); +function hasOpeningParen(oldPath) { + var oldNode = oldPath.getValue(); + var loc = oldNode.loc; + var lines = loc && loc.lines; - var finallyLoc = stmt.finalizer && loc(); - var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); + if (lines) { + var pos = reusablePos; + pos.line = loc.start.line; + pos.column = loc.start.column; - var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); + while (lines.prevPos(pos)) { + var ch = lines.charAt(pos); - self.tryEntries.push(tryEntry); - self.updateContextPrevLoc(tryEntry.firstLoc); + if (ch === "(") { + // If we found an opening parenthesis but it occurred before + // the start of the original subtree for this reprinting, then + // we must not return true for hasOpeningParen(oldPath). + return comparePos(oldPath.getRootValue().loc.start, pos) <= 0; + } - self.leapManager.withEntry(tryEntry, function () { - self.explodeStatement(path.get("block")); + if (nonSpaceExp.test(ch)) { + return false; + } + } + } - if (catchLoc) { - if (finallyLoc) { - // If we have both a catch block and a finally block, then - // because we emit the catch block first, we need to jump over - // it to the finally block. - self.jump(finallyLoc); - } else { - // If there is no finally block, then we need to jump over the - // catch block to the fall-through location. - self.jump(after); - } + return false; +} - self.updateContextPrevLoc(self.mark(catchLoc)); +function hasClosingParen(oldPath) { + var oldNode = oldPath.getValue(); + var loc = oldNode.loc; + var lines = loc && loc.lines; - var bodyPath = path.get("handler.body"); - var safeParam = self.makeTempVar(); - self.clearPendingException(tryEntry.firstLoc, safeParam); + if (lines) { + var pos = reusablePos; + pos.line = loc.end.line; + pos.column = loc.end.column; - bodyPath.traverse(catchParamVisitor, { - safeParam: safeParam, - catchParamName: handler.param.name - }); + do { + var ch = lines.charAt(pos); - self.leapManager.withEntry(catchEntry, function () { - self.explodeStatement(bodyPath); - }); - } + if (ch === ")") { + // If we found a closing parenthesis but it occurred after the + // end of the original subtree for this reprinting, then we + // must not return true for hasClosingParen(oldPath). + return comparePos(pos, oldPath.getRootValue().loc.end) <= 0; + } - if (finallyLoc) { - self.updateContextPrevLoc(self.mark(finallyLoc)); + if (nonSpaceExp.test(ch)) { + return false; + } - self.leapManager.withEntry(finallyEntry, function () { - self.explodeStatement(path.get("finalizer")); - }); + } while (lines.nextPos(pos)); + } - self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); - } - }); + return false; +} - self.mark(after); +function hasParens(oldPath) { + // This logic can technically be fooled if the node has parentheses + // but there are comments intervening between the parentheses and the + // node. In such cases the node will be harmlessly wrapped in an + // additional layer of parentheses. + return hasOpeningParen(oldPath) && hasClosingParen(oldPath); +} - break; +function findChildReprints(newPath, oldPath, reprints) { + var newNode = newPath.getValue(); + var oldNode = oldPath.getValue(); - case "ThrowStatement": - self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); + isObject.assert(newNode); + isObject.assert(oldNode); - break; + if (newNode.original === null) { + // If newNode.original node was set to null, reprint the node. + return false; + } - default: - throw new Error("unknown Statement of type " + (0, _stringify2.default)(stmt.type)); - } -}; + // If this type of node cannot come lexically first in its enclosing + // statement (e.g. a function expression or object literal), and it + // seems to be doing so, then the only way we can ignore this problem + // and save ourselves from falling back to the pretty printer is if an + // opening parenthesis happens to precede the node. For example, + // (function(){ ... }()); does not need to be reprinted, even though + // the FunctionExpression comes lexically first in the enclosing + // ExpressionStatement and fails the hasParens test, because the + // parent CallExpression passes the hasParens test. If we relied on + // the path.needsParens() && !hasParens(oldNode) check below, the + // absence of a closing parenthesis after the FunctionExpression would + // trigger pretty-printing unnecessarily. + if (!newPath.canBeFirstInStatement() && + newPath.firstInStatement() && + !hasOpeningParen(oldPath)) + return false; -var catchParamVisitor = { - Identifier: function Identifier(path, state) { - if (path.node.name === state.catchParamName && util.isReference(path)) { - util.replaceWithOrRemove(path, state.safeParam); + // If this node needs parentheses and will not be wrapped with + // parentheses when reprinted, then return false to skip reprinting + // and let it be printed generically. + if (newPath.needsParens(true) && !hasParens(oldPath)) { + return false; } - }, - Scope: function Scope(path, state) { - if (path.scope.hasOwnBinding(state.catchParamName)) { - // Don't descend into nested scopes that shadow the catch - // parameter with their own declarations. - path.skip(); + var keys = util.getUnionOfKeys(oldNode, newNode); + + if (oldNode.type === "File" || + newNode.type === "File") { + // Don't bother traversing file.tokens, an often very large array + // returned by Babylon, and useless for our purposes. + delete keys.tokens; } - } -}; -Ep.emitAbruptCompletion = function (record) { - if (!isValidCompletion(record)) { - _assert2.default.ok(false, "invalid completion record: " + (0, _stringify2.default)(record)); - } + // Don't bother traversing .loc objects looking for reprintable nodes. + delete keys.loc; - _assert2.default.notStrictEqual(record.type, "normal", "normal completions are not abrupt"); + var originalReprintCount = reprints.length; - var abruptArgs = [t.stringLiteral(record.type)]; + for (var k in keys) { + newPath.stack.push(k, types.getFieldValue(newNode, k)); + oldPath.stack.push(k, types.getFieldValue(oldNode, k)); + var canReprint = findAnyReprints(newPath, oldPath, reprints); + newPath.stack.length -= 2; + oldPath.stack.length -= 2; - if (record.type === "break" || record.type === "continue") { - t.assertLiteral(record.target); - abruptArgs[1] = record.target; - } else if (record.type === "return" || record.type === "throw") { - if (record.value) { - t.assertExpression(record.value); - abruptArgs[1] = record.value; + if (!canReprint) { + return false; + } } - } - this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); -}; + // Return statements might end up running into ASI issues due to comments + // inserted deep within the tree, so reprint them if anything changed + // within them. + if (ReturnStatement.check(newPath.getNode()) && + reprints.length > originalReprintCount) { + return false; + } -function isValidCompletion(record) { - var type = record.type; + return true; +} - if (type === "normal") { - return !hasOwn.call(record, "target"); - } +},{"./fast-path":550,"./lines":551,"./types":557,"./util":558,"assert":2}],556:[function(require,module,exports){ +var assert = require("assert"); +var sourceMap = require("source-map"); +var printComments = require("./comments").printComments; +var linesModule = require("./lines"); +var fromString = linesModule.fromString; +var concat = linesModule.concat; +var normalizeOptions = require("./options").normalize; +var getReprinter = require("./patcher").getReprinter; +var types = require("./types"); +var namedTypes = types.namedTypes; +var isString = types.builtInTypes.string; +var isObject = types.builtInTypes.object; +var FastPath = require("./fast-path"); +var util = require("./util"); - if (type === "break" || type === "continue") { - return !hasOwn.call(record, "value") && t.isLiteral(record.target); - } +function PrintResult(code, sourceMap) { + assert.ok(this instanceof PrintResult); - if (type === "return" || type === "throw") { - return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); - } + isString.assert(code); + this.code = code; - return false; + if (sourceMap) { + isObject.assert(sourceMap); + this.map = sourceMap; + } } -// Not all offsets into emitter.listing are potential jump targets. For -// example, execution typically falls into the beginning of a try block -// without jumping directly there. This method returns the current offset -// without marking it, so that a switch case will not necessarily be -// generated for this offset (I say "not necessarily" because the same -// location might end up being marked in the process of emitting other -// statements). There's no logical harm in marking such locations as jump -// targets, but minimizing the number of switch cases keeps the generated -// code shorter. -Ep.getUnmarkedCurrentLoc = function () { - return t.numericLiteral(this.listing.length); -}; +var PRp = PrintResult.prototype; +var warnedAboutToString = false; -// The context.prev property takes the value of context.next whenever we -// evaluate the switch statement discriminant, which is generally good -// enough for tracking the last location we jumped to, but sometimes -// context.prev needs to be more precise, such as when we fall -// successfully out of a try block and into a finally block without -// jumping. This method exists to update context.prev to the freshest -// available location. If we were implementing a full interpreter, we -// would know the location of the current instruction with complete -// precision at all times, but we don't have that luxury here, as it would -// be costly and verbose to set context.prev before every statement. -Ep.updateContextPrevLoc = function (loc) { - if (loc) { - t.assertLiteral(loc); +PRp.toString = function() { + if (!warnedAboutToString) { + console.warn( + "Deprecation warning: recast.print now returns an object with " + + "a .code property. You appear to be treating the object as a " + + "string, which might still work but is strongly discouraged." + ); - if (loc.value === -1) { - // If an uninitialized location literal was passed in, set its value - // to the current this.listing.length. - loc.value = this.listing.length; - } else { - // Otherwise assert that the location matches the current offset. - _assert2.default.strictEqual(loc.value, this.listing.length); + warnedAboutToString = true; } - } else { - loc = this.getUnmarkedCurrentLoc(); - } - // Make sure context.prev is up to date in case we fell into this try - // statement without jumping to it. TODO Consider avoiding this - // assignment when we know control must have jumped here. - this.emitAssign(this.contextProperty("prev"), loc); + return this.code; }; -Ep.explodeExpression = function (path, ignoreResult) { - var expr = path.node; - if (expr) { - t.assertExpression(expr); - } else { - return expr; - } - - var self = this; - var result = void 0; // Used optionally by several cases below. - var after = void 0; - - function finish(expr) { - t.assertExpression(expr); - if (ignoreResult) { - self.emit(expr); - } else { - return expr; - } - } - - // If the expression does not contain a leap, then we either emit the - // expression as a standalone statement or return it whole. - if (!meta.containsLeap(expr)) { - return finish(expr); - } - - // If any child contains a leap (such as a yield or labeled continue or - // break statement), then any sibling subexpressions will almost - // certainly have to be exploded in order to maintain the order of their - // side effects relative to the leaping child(ren). - var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); +var emptyPrintResult = new PrintResult(""); - // In order to save the rest of explodeExpression from a combinatorial - // trainwreck of special cases, explodeViaTempVar is responsible for - // deciding when a subexpression needs to be "exploded," which is my - // very technical term for emitting the subexpression as an assignment - // to a temporary variable and the substituting the temporary variable - // for the original subexpression. Think of exploded view diagrams, not - // Michael Bay movies. The point of exploding subexpressions is to - // control the precise order in which the generated code realizes the - // side effects of those subexpressions. - function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { - _assert2.default.ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); +function Printer(originalOptions) { + assert.ok(this instanceof Printer); - var result = self.explodeExpression(childPath, ignoreChildResult); + var explicitTabWidth = originalOptions && originalOptions.tabWidth; + var options = normalizeOptions(originalOptions); + assert.notStrictEqual(options, originalOptions); - if (ignoreChildResult) { - // Side effects already emitted above. + // It's common for client code to pass the same options into both + // recast.parse and recast.print, but the Printer doesn't need (and + // can be confused by) options.sourceFileName, so we null it out. + options.sourceFileName = null; - } else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { - // If tempVar was provided, then the result will always be assigned - // to it, even if the result does not otherwise need to be assigned - // to a temporary variable. When no tempVar is provided, we have - // the flexibility to decide whether a temporary variable is really - // necessary. Unfortunately, in general, a temporary variable is - // required whenever any child contains a yield expression, since it - // is difficult to prove (at all, let alone efficiently) whether - // this result would evaluate to the same value before and after the - // yield (see #206). One narrow case where we can prove it doesn't - // matter (and thus we do not need a temporary variable) is when the - // result in question is a Literal value. - result = self.emitAssign(tempVar || self.makeTempVar(), result); + function printWithComments(path) { + assert.ok(path instanceof FastPath); + return printComments(path, print); } - return result; - } - - // If ignoreResult is true, then we must take full responsibility for - // emitting the expression with all its side effects, and we should not - // return a result. - - switch (expr.type) { - case "MemberExpression": - return finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)); - - case "CallExpression": - var calleePath = path.get("callee"); - var argsPath = path.get("arguments"); - var newCallee = void 0; - var newArgs = []; + function print(path, includeComments) { + if (includeComments) + return printWithComments(path); - var hasLeapingArgs = false; - argsPath.forEach(function (argPath) { - hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); - }); + assert.ok(path instanceof FastPath); - if (t.isMemberExpression(calleePath.node)) { - if (hasLeapingArgs) { - // If the arguments of the CallExpression contained any yield - // expressions, then we need to be sure to evaluate the callee - // before evaluating the arguments, but if the callee was a member - // expression, then we must be careful that the object of the - // member expression still gets bound to `this` for the call. + if (!explicitTabWidth) { + var oldTabWidth = options.tabWidth; + var loc = path.getNode().loc; + if (loc && loc.lines && loc.lines.guessTabWidth) { + options.tabWidth = loc.lines.guessTabWidth(); + var lines = maybeReprint(path); + options.tabWidth = oldTabWidth; + return lines; + } + } - var newObject = explodeViaTempVar( - // Assign the exploded callee.object expression to a temporary - // variable so that we can use it twice without reevaluating it. - self.makeTempVar(), calleePath.get("object")); + return maybeReprint(path); + } - var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; + function maybeReprint(path) { + var reprinter = getReprinter(path); + if (reprinter) { + // Since the print function that we pass to the reprinter will + // be used to print "new" nodes, it's tempting to think we + // should pass printRootGenerically instead of print, to avoid + // calling maybeReprint again, but that would be a mistake + // because the new nodes might not be entirely new, but merely + // moved from elsewhere in the AST. The print function is the + // right choice because it gives us the opportunity to reprint + // such nodes using their original source. + return maybeAddParens(path, reprinter(print)); + } + return printRootGenerically(path); + } - newArgs.unshift(newObject); + // Print the root node generically, but then resume reprinting its + // children non-generically. + function printRootGenerically(path, includeComments) { + return includeComments + ? printComments(path, printRootGenerically) + : genericPrint(path, options, printWithComments); + } - newCallee = t.memberExpression(t.memberExpression(newObject, newProperty, calleePath.node.computed), t.identifier("call"), false); - } else { - newCallee = self.explodeExpression(calleePath); - } - } else { - newCallee = explodeViaTempVar(null, calleePath); + // Print the entire AST generically. + function printGenerically(path) { + return genericPrint(path, options, printGenerically); + } - if (t.isMemberExpression(newCallee)) { - // If the callee was not previously a MemberExpression, then the - // CallExpression was "unqualified," meaning its `this` object - // should be the global object. If the exploded expression has - // become a MemberExpression (e.g. a context property, probably a - // temporary variable), then we need to force it to be unqualified - // by using the (0, object.property)(...) trick; otherwise, it - // will receive the object of the MemberExpression as its `this` - // object. - newCallee = t.sequenceExpression([t.numericLiteral(0), newCallee]); + this.print = function(ast) { + if (!ast) { + return emptyPrintResult; } - } - - argsPath.forEach(function (argPath) { - newArgs.push(explodeViaTempVar(null, argPath)); - }); - return finish(t.callExpression(newCallee, newArgs)); + var lines = print(FastPath.from(ast), true); - case "NewExpression": - return finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { - return explodeViaTempVar(null, argPath); - }))); + return new PrintResult( + lines.toString(options), + util.composeSourceMaps( + options.inputSourceMap, + lines.getSourceMap( + options.sourceMapName, + options.sourceRoot + ) + ) + ); + }; - case "ObjectExpression": - return finish(t.objectExpression(path.get("properties").map(function (propPath) { - if (propPath.isObjectProperty()) { - return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); - } else { - return propPath.node; + this.printGenerically = function(ast) { + if (!ast) { + return emptyPrintResult; } - }))); - case "ArrayExpression": - return finish(t.arrayExpression(path.get("elements").map(function (elemPath) { - return explodeViaTempVar(null, elemPath); - }))); + var path = FastPath.from(ast); + var oldReuseWhitespace = options.reuseWhitespace; - case "SequenceExpression": - var lastIndex = expr.expressions.length - 1; + // Do not reuse whitespace (or anything else, for that matter) + // when printing generically. + options.reuseWhitespace = false; - path.get("expressions").forEach(function (exprPath) { - if (exprPath.key === lastIndex) { - result = self.explodeExpression(exprPath, ignoreResult); - } else { - self.explodeExpression(exprPath, true); - } - }); + // TODO Allow printing of comments? + var pr = new PrintResult(printGenerically(path).toString(options)); + options.reuseWhitespace = oldReuseWhitespace; + return pr; + }; +} - return result; +exports.Printer = Printer; - case "LogicalExpression": - after = loc(); +function maybeAddParens(path, lines) { + return path.needsParens() ? concat(["(", lines, ")"]) : lines; +} - if (!ignoreResult) { - result = self.makeTempVar(); - } +function genericPrint(path, options, printPath) { + assert.ok(path instanceof FastPath); - var left = explodeViaTempVar(result, path.get("left")); + var node = path.getValue(); + var parts = []; + var needsParens = false; + var linesWithoutParens = + genericPrintNoParens(path, options, printPath); - if (expr.operator === "&&") { - self.jumpIfNot(left, after); - } else { - _assert2.default.strictEqual(expr.operator, "||"); - self.jumpIf(left, after); - } + if (! node || linesWithoutParens.isEmpty()) { + return linesWithoutParens; + } - explodeViaTempVar(result, path.get("right"), ignoreResult); + if (node.decorators && + node.decorators.length > 0 && + // If the parent node is an export declaration, it will be + // responsible for printing node.decorators. + ! util.getParentExportDeclaration(path)) { - self.mark(after); + path.each(function(decoratorPath) { + parts.push(printPath(decoratorPath), "\n"); + }, "decorators"); - return result; + } else if (util.isExportDeclaration(node) && + node.declaration && + node.declaration.decorators) { + // Export declarations are responsible for printing any decorators + // that logically apply to node.declaration. + path.each(function(decoratorPath) { + parts.push(printPath(decoratorPath), "\n"); + }, "declaration", "decorators"); - case "ConditionalExpression": - var elseLoc = loc(); - after = loc(); - var test = self.explodeExpression(path.get("test")); + } else { + // Nodes with decorators can't have parentheses, so we can avoid + // computing path.needsParens() except in this case. + needsParens = path.needsParens(); + } - self.jumpIfNot(test, elseLoc); + if (needsParens) { + parts.unshift("("); + } - if (!ignoreResult) { - result = self.makeTempVar(); - } + parts.push(linesWithoutParens); - explodeViaTempVar(result, path.get("consequent"), ignoreResult); - self.jump(after); + if (needsParens) { + parts.push(")"); + } - self.mark(elseLoc); - explodeViaTempVar(result, path.get("alternate"), ignoreResult); + return concat(parts); +} - self.mark(after); +function genericPrintNoParens(path, options, print) { + var n = path.getValue(); - return result; + if (!n) { + return fromString(""); + } - case "UnaryExpression": - return finish(t.unaryExpression(expr.operator, - // Can't (and don't need to) break up the syntax of the argument. - // Think about delete a[b]. - self.explodeExpression(path.get("argument")), !!expr.prefix)); + if (typeof n === "string") { + return fromString(n, options); + } - case "BinaryExpression": - return finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))); + namedTypes.Printable.assert(n); - case "AssignmentExpression": - return finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))); + var parts = []; - case "UpdateExpression": - return finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)); + switch (n.type) { + case "File": + return path.call(print, "program"); - case "YieldExpression": - after = loc(); - var arg = expr.argument && self.explodeExpression(path.get("argument")); + case "Program": + // Babel 6 + if (n.directives) { + path.each(function(childPath) { + parts.push(print(childPath), ";\n"); + }, "directives"); + } - if (arg && expr.delegate) { - var _result = self.makeTempVar(); + parts.push(path.call(function(bodyPath) { + return printStatementSequence(bodyPath, options, print); + }, "body")); - self.emit(t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after]))); + return concat(parts); - self.mark(after); + case "Noop": // Babel extension. + case "EmptyStatement": + return fromString(""); - return _result; - } + case "ExpressionStatement": + return concat([path.call(print, "expression"), ";"]); - self.emitAssign(self.contextProperty("next"), after); - self.emit(t.returnStatement(arg || null)); - self.mark(after); + case "ParenthesizedExpression": // Babel extension. + return concat(["(", path.call(print, "expression"), ")"]); - return self.contextProperty("sent"); + case "BinaryExpression": + case "LogicalExpression": + case "AssignmentExpression": + return fromString(" ").join([ + path.call(print, "left"), + n.operator, + path.call(print, "right") + ]); - default: - throw new Error("unknown Expression of type " + (0, _stringify2.default)(expr.type)); - } -}; -},{"./leap":547,"./meta":548,"./util":550,"assert":791,"babel-runtime/core-js/json/stringify":553,"babel-types":573}],545:[function(require,module,exports){ -"use strict"; + case "AssignmentPattern": + return concat([ + path.call(print, "left"), + " = ", + path.call(print, "right") + ]); -var _keys = require("babel-runtime/core-js/object/keys"); + case "MemberExpression": + parts.push(path.call(print, "object")); -var _keys2 = _interopRequireDefault(_keys); + var property = path.call(print, "property"); + if (n.computed) { + parts.push("[", property, "]"); + } else { + parts.push(".", property); + } -var _babelTypes = require("babel-types"); + return concat(parts); -var t = _interopRequireWildcard(_babelTypes); + case "MetaProperty": + return concat([ + path.call(print, "meta"), + ".", + path.call(print, "property") + ]); -var _util = require("./util"); + case "BindExpression": + if (n.object) { + parts.push(path.call(print, "object")); + } -var util = _interopRequireWildcard(_util); + parts.push("::", path.call(print, "callee")); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return concat(parts); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case "Path": + return fromString(".").join(n.body); -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + case "Identifier": + return concat([ + fromString(n.name, options), + path.call(print, "typeAnnotation") + ]); -var hasOwn = Object.prototype.hasOwnProperty; + case "SpreadElement": + case "SpreadElementPattern": + case "RestProperty": // Babel 6 for ObjectPattern + case "SpreadProperty": + case "SpreadPropertyPattern": + case "RestElement": + return concat(["...", path.call(print, "argument")]); -// The hoist function takes a FunctionExpression or FunctionDeclaration -// and replaces any Declaration nodes in its body with assignments, then -// returns a VariableDeclaration containing just the names of the removed -// declarations. -exports.hoist = function (funPath) { - t.assertFunction(funPath.node); + case "FunctionDeclaration": + case "FunctionExpression": + if (n.async) + parts.push("async "); - var vars = {}; + parts.push("function"); - function varDeclToExpr(vdec, includeIdentifiers) { - t.assertVariableDeclaration(vdec); - // TODO assert.equal(vdec.kind, "var"); - var exprs = []; + if (n.generator) + parts.push("*"); - vdec.declarations.forEach(function (dec) { - // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't - // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly. - vars[dec.id.name] = t.identifier(dec.id.name); + if (n.id) { + parts.push( + " ", + path.call(print, "id"), + path.call(print, "typeParameters") + ); + } - if (dec.init) { - exprs.push(t.assignmentExpression("=", dec.id, dec.init)); - } else if (includeIdentifiers) { - exprs.push(dec.id); - } - }); + parts.push( + "(", + printFunctionParams(path, options, print), + ")", + path.call(print, "returnType"), + " ", + path.call(print, "body") + ); - if (exprs.length === 0) return null; + return concat(parts); - if (exprs.length === 1) return exprs[0]; + case "ArrowFunctionExpression": + if (n.async) + parts.push("async "); - return t.sequenceExpression(exprs); - } + if (n.typeParameters) { + parts.push(path.call(print, "typeParameters")); + } - funPath.get("body").traverse({ - VariableDeclaration: { - exit: function exit(path) { - var expr = varDeclToExpr(path.node, false); - if (expr === null) { - path.remove(); + if ( + !options.arrowParensAlways && + n.params.length === 1 && + !n.rest && + n.params[0].type === 'Identifier' && + !n.params[0].typeAnnotation && + !n.returnType + ) { + parts.push(path.call(print, "params", 0)); } else { - // We don't need to traverse this expression any further because - // there can't be any new declarations inside an expression. - util.replaceWithOrRemove(path, t.expressionStatement(expr)); + parts.push( + "(", + printFunctionParams(path, options, print), + ")", + path.call(print, "returnType") + ); } - // Since the original node has been either removed or replaced, - // avoid traversing it any further. - path.skip(); - } - }, + parts.push(" => ", path.call(print, "body")); - ForStatement: function ForStatement(path) { - var init = path.node.init; - if (t.isVariableDeclaration(init)) { - util.replaceWithOrRemove(path.get("init"), varDeclToExpr(init, false)); - } - }, + return concat(parts); - ForXStatement: function ForXStatement(path) { - var left = path.get("left"); - if (left.isVariableDeclaration()) { - util.replaceWithOrRemove(left, varDeclToExpr(left.node, true)); - } - }, + case "MethodDefinition": + if (n.static) { + parts.push("static "); + } - FunctionDeclaration: function FunctionDeclaration(path) { - var node = path.node; - vars[node.id.name] = node.id; + parts.push(printMethod(path, options, print)); - var assignment = t.expressionStatement(t.assignmentExpression("=", node.id, t.functionExpression(node.id, node.params, node.body, node.generator, node.expression))); + return concat(parts); - if (path.parentPath.isBlockStatement()) { - // Insert the assignment form before the first statement in the - // enclosing block. - path.parentPath.unshiftContainer("body", assignment); + case "YieldExpression": + parts.push("yield"); - // Remove the function declaration now that we've inserted the - // equivalent assignment form at the beginning of the block. - path.remove(); - } else { - // If the parent node is not a block statement, then we can just - // replace the declaration with the equivalent assignment form - // without worrying about hoisting it. - util.replaceWithOrRemove(path, assignment); - } + if (n.delegate) + parts.push("*"); - // Don't hoist variables out of inner functions. - path.skip(); - }, + if (n.argument) + parts.push(" ", path.call(print, "argument")); - FunctionExpression: function FunctionExpression(path) { - // Don't descend into nested function expressions. - path.skip(); - } - }); + return concat(parts); - var paramNames = {}; - funPath.get("params").forEach(function (paramPath) { - var param = paramPath.node; - if (t.isIdentifier(param)) { - paramNames[param.name] = param; - } else { - // Variables declared by destructuring parameter patterns will be - // harmlessly re-declared. - } - }); + case "AwaitExpression": + parts.push("await"); - var declarations = []; + if (n.all) + parts.push("*"); - (0, _keys2.default)(vars).forEach(function (name) { - if (!hasOwn.call(paramNames, name)) { - declarations.push(t.variableDeclarator(vars[name], null)); - } - }); + if (n.argument) + parts.push(" ", path.call(print, "argument")); - if (declarations.length === 0) { - return null; // Be sure to handle this case! - } + return concat(parts); - return t.variableDeclaration("var", declarations); -}; -},{"./util":550,"babel-runtime/core-js/object/keys":557,"babel-types":573}],546:[function(require,module,exports){ -"use strict"; + case "ModuleDeclaration": + parts.push("module", path.call(print, "id")); -exports.__esModule = true; + if (n.source) { + assert.ok(!n.body); + parts.push("from", path.call(print, "source")); + } else { + parts.push(path.call(print, "body")); + } -exports.default = function () { - return require("./visit"); -}; -},{"./visit":551}],547:[function(require,module,exports){ -"use strict"; + return fromString(" ").join(parts); -var _assert = require("assert"); + case "ImportSpecifier": + if (n.imported) { + parts.push(path.call(print, "imported")); + if (n.local && + n.local.name !== n.imported.name) { + parts.push(" as ", path.call(print, "local")); + } + } else if (n.id) { + parts.push(path.call(print, "id")); + if (n.name) { + parts.push(" as ", path.call(print, "name")); + } + } -var _assert2 = _interopRequireDefault(_assert); + return concat(parts); -var _babelTypes = require("babel-types"); + case "ExportSpecifier": + if (n.local) { + parts.push(path.call(print, "local")); + if (n.exported && + n.exported.name !== n.local.name) { + parts.push(" as ", path.call(print, "exported")); + } + } else if (n.id) { + parts.push(path.call(print, "id")); + if (n.name) { + parts.push(" as ", path.call(print, "name")); + } + } -var t = _interopRequireWildcard(_babelTypes); + return concat(parts); -var _util = require("util"); + case "ExportBatchSpecifier": + return fromString("*"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case "ImportNamespaceSpecifier": + parts.push("* as "); + if (n.local) { + parts.push(path.call(print, "local")); + } else if (n.id) { + parts.push(path.call(print, "id")); + } + return concat(parts); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case "ImportDefaultSpecifier": + if (n.local) { + return path.call(print, "local"); + } + return path.call(print, "id"); -function Entry() { - _assert2.default.ok(this instanceof Entry); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + case "ExportDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + return printExportDeclaration(path, options, print); -function FunctionEntry(returnLoc) { - Entry.call(this); - t.assertLiteral(returnLoc); - this.returnLoc = returnLoc; -} + case "ExportAllDeclaration": + parts.push("export *"); -(0, _util.inherits)(FunctionEntry, Entry); -exports.FunctionEntry = FunctionEntry; + if (n.exported) { + parts.push(" as ", path.call(print, "exported")); + } -function LoopEntry(breakLoc, continueLoc, label) { - Entry.call(this); + parts.push( + " from ", + path.call(print, "source") + ); - t.assertLiteral(breakLoc); - t.assertLiteral(continueLoc); + return concat(parts); - if (label) { - t.assertIdentifier(label); - } else { - label = null; - } + case "ExportNamespaceSpecifier": + return concat(["* as ", path.call(print, "exported")]); - this.breakLoc = breakLoc; - this.continueLoc = continueLoc; - this.label = label; -} + case "ExportDefaultSpecifier": + return path.call(print, "exported"); -(0, _util.inherits)(LoopEntry, Entry); -exports.LoopEntry = LoopEntry; + case "Import": + return fromString("import", options); -function SwitchEntry(breakLoc) { - Entry.call(this); - t.assertLiteral(breakLoc); - this.breakLoc = breakLoc; -} + case "ImportDeclaration": + parts.push("import "); + + if (n.importKind && n.importKind !== "value") { + parts.push(n.importKind + " "); + } + + if (n.specifiers && + n.specifiers.length > 0) { + + var foundImportSpecifier = false; + + path.each(function(specifierPath) { + var i = specifierPath.getName(); + if (i > 0) { + parts.push(", "); + } + + var value = specifierPath.getValue(); + + if (namedTypes.ImportDefaultSpecifier.check(value) || + namedTypes.ImportNamespaceSpecifier.check(value)) { + assert.strictEqual(foundImportSpecifier, false); + } else { + namedTypes.ImportSpecifier.assert(value); + if (!foundImportSpecifier) { + foundImportSpecifier = true; + parts.push( + options.objectCurlySpacing ? "{ " : "{" + ); + } + } -(0, _util.inherits)(SwitchEntry, Entry); -exports.SwitchEntry = SwitchEntry; + parts.push(print(specifierPath)); + }, "specifiers"); -function TryEntry(firstLoc, catchEntry, finallyEntry) { - Entry.call(this); + if (foundImportSpecifier) { + parts.push( + options.objectCurlySpacing ? " }" : "}" + ); + } - t.assertLiteral(firstLoc); + parts.push(" from "); + } - if (catchEntry) { - _assert2.default.ok(catchEntry instanceof CatchEntry); - } else { - catchEntry = null; - } + parts.push(path.call(print, "source"), ";"); - if (finallyEntry) { - _assert2.default.ok(finallyEntry instanceof FinallyEntry); - } else { - finallyEntry = null; - } + return concat(parts); - // Have to have one or the other (or both). - _assert2.default.ok(catchEntry || finallyEntry); + case "BlockStatement": + var naked = path.call(function(bodyPath) { + return printStatementSequence(bodyPath, options, print); + }, "body"); - this.firstLoc = firstLoc; - this.catchEntry = catchEntry; - this.finallyEntry = finallyEntry; -} -(0, _util.inherits)(TryEntry, Entry); -exports.TryEntry = TryEntry; + if (naked.isEmpty()) { + if (!n.directives || n.directives.length === 0) { + return fromString("{}"); + } + } -function CatchEntry(firstLoc, paramId) { - Entry.call(this); + parts.push("{\n"); + // Babel 6 + if (n.directives) { + path.each(function(childPath) { + parts.push( + print(childPath).indent(options.tabWidth), + ";", + n.directives.length > 1 || !naked.isEmpty() ? "\n" : "" + ); + }, "directives"); + } + parts.push(naked.indent(options.tabWidth)); + parts.push("\n}"); - t.assertLiteral(firstLoc); - t.assertIdentifier(paramId); + return concat(parts); - this.firstLoc = firstLoc; - this.paramId = paramId; -} + case "ReturnStatement": + parts.push("return"); -(0, _util.inherits)(CatchEntry, Entry); -exports.CatchEntry = CatchEntry; + if (n.argument) { + var argLines = path.call(print, "argument"); + if (argLines.startsWithComment() || + (argLines.length > 1 && + namedTypes.JSXElement && + namedTypes.JSXElement.check(n.argument) + )) { + parts.push( + " (\n", + argLines.indent(options.tabWidth), + "\n)" + ); + } else { + parts.push(" ", argLines); + } + } -function FinallyEntry(firstLoc, afterLoc) { - Entry.call(this); - t.assertLiteral(firstLoc); - t.assertLiteral(afterLoc); - this.firstLoc = firstLoc; - this.afterLoc = afterLoc; -} + parts.push(";"); -(0, _util.inherits)(FinallyEntry, Entry); -exports.FinallyEntry = FinallyEntry; + return concat(parts); -function LabeledEntry(breakLoc, label) { - Entry.call(this); + case "CallExpression": + return concat([ + path.call(print, "callee"), + printArgumentsList(path, options, print) + ]); - t.assertLiteral(breakLoc); - t.assertIdentifier(label); + case "ObjectExpression": + case "ObjectPattern": + case "ObjectTypeAnnotation": + var allowBreak = false; + var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; + var separator = options.flowObjectCommas ? "," : (isTypeAnnotation ? ";" : ","); + var fields = []; - this.breakLoc = breakLoc; - this.label = label; -} + if (isTypeAnnotation) { + fields.push("indexers", "callProperties"); + } -(0, _util.inherits)(LabeledEntry, Entry); -exports.LabeledEntry = LabeledEntry; + fields.push("properties"); -function LeapManager(emitter) { - _assert2.default.ok(this instanceof LeapManager); + var len = 0; + fields.forEach(function(field) { + len += n[field].length; + }); - var Emitter = require("./emit").Emitter; - _assert2.default.ok(emitter instanceof Emitter); + var oneLine = (isTypeAnnotation && len === 1) || len === 0; + var leftBrace = n.exact ? "{|" : "{"; + var rightBrace = n.exact ? "|}" : "}"; + parts.push(oneLine ? leftBrace : leftBrace + "\n"); + var leftBraceIndex = parts.length - 1; - this.emitter = emitter; - this.entryStack = [new FunctionEntry(emitter.finalLoc)]; -} + var i = 0; + fields.forEach(function(field) { + path.each(function(childPath) { + var lines = print(childPath); -var LMp = LeapManager.prototype; -exports.LeapManager = LeapManager; + if (!oneLine) { + lines = lines.indent(options.tabWidth); + } -LMp.withEntry = function (entry, callback) { - _assert2.default.ok(entry instanceof Entry); - this.entryStack.push(entry); - try { - callback.call(this.emitter); - } finally { - var popped = this.entryStack.pop(); - _assert2.default.strictEqual(popped, entry); - } -}; + var multiLine = !isTypeAnnotation && lines.length > 1; + if (multiLine && allowBreak) { + // Similar to the logic for BlockStatement. + parts.push("\n"); + } -LMp._findLeapLocation = function (property, label) { - for (var i = this.entryStack.length - 1; i >= 0; --i) { - var entry = this.entryStack[i]; - var loc = entry[property]; - if (loc) { - if (label) { - if (entry.label && entry.label.name === label.name) { - return loc; - } - } else if (entry instanceof LabeledEntry) { - // Ignore LabeledEntry entries unless we are actually breaking to - // a label. - } else { - return loc; - } - } - } + parts.push(lines); - return null; -}; + if (i < len - 1) { + // Add an extra line break if the previous object property + // had a multi-line value. + parts.push(separator + (multiLine ? "\n\n" : "\n")); + allowBreak = !multiLine; + } else if (len !== 1 && isTypeAnnotation) { + parts.push(separator); + } else if (!oneLine && util.isTrailingCommaEnabled(options, "objects")) { + parts.push(separator); + } + i++; + }, field); + }); -LMp.getBreakLoc = function (label) { - return this._findLeapLocation("breakLoc", label); -}; + parts.push(oneLine ? rightBrace : "\n" + rightBrace); -LMp.getContinueLoc = function (label) { - return this._findLeapLocation("continueLoc", label); -}; -},{"./emit":544,"assert":791,"babel-types":573,"util":821}],548:[function(require,module,exports){ -"use strict"; + if (i !== 0 && oneLine && options.objectCurlySpacing) { + parts[leftBraceIndex] = leftBrace + " "; + parts[parts.length - 1] = " " + rightBrace; + } -var _assert = require("assert"); + return concat(parts); -var _assert2 = _interopRequireDefault(_assert); + case "PropertyPattern": + return concat([ + path.call(print, "key"), + ": ", + path.call(print, "pattern") + ]); -var _babelTypes = require("babel-types"); + case "ObjectProperty": // Babel 6 + case "Property": // Non-standard AST node type. + if (n.method || n.kind === "get" || n.kind === "set") { + return printMethod(path, options, print); + } -var t = _interopRequireWildcard(_babelTypes); + var key = path.call(print, "key"); + if (n.computed) { + parts.push("[", key, "]"); + } else { + parts.push(key); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (! n.shorthand) { + parts.push(": ", path.call(print, "value")); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return concat(parts); -var m = require("private").makeAccessor(); /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + case "ClassMethod": // Babel 6 + if (n.static) { + parts.push("static "); + } -var hasOwn = Object.prototype.hasOwnProperty; + return concat([parts, printObjectMethod(path, options, print)]); -function makePredicate(propertyName, knownTypes) { - function onlyChildren(node) { - t.assertNode(node); + case "ObjectMethod": // Babel 6 + return printObjectMethod(path, options, print); - // Assume no side effects until we find out otherwise. - var result = false; + case "Decorator": + return concat(["@", path.call(print, "expression")]); - function check(child) { - if (result) { - // Do nothing. - } else if (Array.isArray(child)) { - child.some(check); - } else if (t.isNode(child)) { - _assert2.default.strictEqual(result, false); - result = predicate(child); - } - return result; - } + case "ArrayExpression": + case "ArrayPattern": + var elems = n.elements, + len = elems.length; - var keys = t.VISITOR_KEYS[node.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = node[key]; - check(child); - } - } + var printed = path.map(print, "elements"); + var joined = fromString(", ").join(printed); + var oneLine = joined.getLineLength(1) <= options.wrapColumn; + if (oneLine) { + if (options.arrayBracketSpacing) { + parts.push("[ "); + } else { + parts.push("["); + } + } else { + parts.push("[\n"); + } - return result; - } + path.each(function(elemPath) { + var i = elemPath.getName(); + var elem = elemPath.getValue(); + if (!elem) { + // If the array expression ends with a hole, that hole + // will be ignored by the interpreter, but if it ends with + // two (or more) holes, we need to write out two (or more) + // commas so that the resulting code is interpreted with + // both (all) of the holes. + parts.push(","); + } else { + var lines = printed[i]; + if (oneLine) { + if (i > 0) + parts.push(" "); + } else { + lines = lines.indent(options.tabWidth); + } + parts.push(lines); + if (i < len - 1 || (!oneLine && util.isTrailingCommaEnabled(options, "arrays"))) + parts.push(","); + if (!oneLine) + parts.push("\n"); + } + }, "elements"); - function predicate(node) { - t.assertNode(node); + if (oneLine && options.arrayBracketSpacing) { + parts.push(" ]"); + } else { + parts.push("]"); + } - var meta = m(node); - if (hasOwn.call(meta, propertyName)) return meta[propertyName]; + return concat(parts); - // Certain types are "opaque," which means they have no side - // effects or leaps and we don't care about their subexpressions. - if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; + case "SequenceExpression": + return fromString(", ").join(path.map(print, "expressions")); - if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; + case "ThisExpression": + return fromString("this"); - return meta[propertyName] = onlyChildren(node); - } + case "Super": + return fromString("super"); - predicate.onlyChildren = onlyChildren; + case "NullLiteral": // Babel 6 Literal split + return fromString("null"); - return predicate; -} + case "RegExpLiteral": // Babel 6 Literal split + return fromString(n.extra.raw); -var opaqueTypes = { - FunctionExpression: true, - ArrowFunctionExpression: true -}; + case "BooleanLiteral": // Babel 6 Literal split + case "NumericLiteral": // Babel 6 Literal split + case "StringLiteral": // Babel 6 Literal split + case "Literal": + if (typeof n.value !== "string") + return fromString(n.value, options); -// These types potentially have side effects regardless of what side -// effects their subexpressions have. -var sideEffectTypes = { - CallExpression: true, // Anything could happen! - ForInStatement: true, // Modifies the key variable. - UnaryExpression: true, // Think delete. - BinaryExpression: true, // Might invoke .toString() or .valueOf(). - AssignmentExpression: true, // Side-effecting by definition. - UpdateExpression: true, // Updates are essentially assignments. - NewExpression: true // Similar to CallExpression. -}; + return fromString(nodeStr(n.value, options), options); -// These types are the direct cause of all leaps in control flow. -var leapTypes = { - YieldExpression: true, - BreakStatement: true, - ContinueStatement: true, - ReturnStatement: true, - ThrowStatement: true -}; + case "Directive": // Babel 6 + return path.call(print, "value"); -// All leap types are also side effect types. -for (var type in leapTypes) { - if (hasOwn.call(leapTypes, type)) { - sideEffectTypes[type] = leapTypes[type]; - } -} + case "DirectiveLiteral": // Babel 6 + return fromString(nodeStr(n.value, options)); -exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); -exports.containsLeap = makePredicate("containsLeap", leapTypes); -},{"assert":791,"babel-types":573,"private":787}],549:[function(require,module,exports){ -"use strict"; + case "ModuleSpecifier": + if (n.local) { + throw new Error( + "The ESTree ModuleSpecifier type should be abstract" + ); + } -exports.__esModule = true; -exports.default = replaceShorthandObjectMethod; + // The Esprima ModuleSpecifier type is just a string-valued + // Literal identifying the imported-from module. + return fromString(nodeStr(n.value, options), options); -var _babelTypes = require("babel-types"); + case "UnaryExpression": + parts.push(n.operator); + if (/[a-z]$/.test(n.operator)) + parts.push(" "); + parts.push(path.call(print, "argument")); + return concat(parts); -var t = _interopRequireWildcard(_babelTypes); + case "UpdateExpression": + parts.push( + path.call(print, "argument"), + n.operator + ); -var _util = require("./util"); + if (n.prefix) + parts.reverse(); -var util = _interopRequireWildcard(_util); + return concat(parts); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case "ConditionalExpression": + return concat([ + "(", path.call(print, "test"), + " ? ", path.call(print, "consequent"), + " : ", path.call(print, "alternate"), ")" + ]); -// this function converts a shorthand object generator method into a normal -// (non-shorthand) object property which is a generator function expression. for -// example, this: -// -// var foo = { -// *bar(baz) { return 5; } -// } -// -// should be replaced with: -// -// var foo = { -// bar: function*(baz) { return 5; } -// } -// -// to do this, it clones the parameter array and the body of the object generator -// method into a new FunctionExpression. -// -// this method can be passed any Function AST node path, and it will return -// either: -// a) the path that was passed in (iff the path did not need to be replaced) or -// b) the path of the new FunctionExpression that was created as a replacement -// (iff the path did need to be replaced) -// -// In either case, though, the caller can count on the fact that the return value -// is a Function AST node path. -// -// If this function is called with an AST node path that is not a Function (or with an -// argument that isn't an AST node path), it will throw an error. -function replaceShorthandObjectMethod(path) { - if (!path.node || !t.isFunction(path.node)) { - throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); - } + case "NewExpression": + parts.push("new ", path.call(print, "callee")); + var args = n.arguments; + if (args) { + parts.push(printArgumentsList(path, options, print)); + } - // this function only replaces shorthand object methods (called ObjectMethod - // in Babel-speak). - if (!t.isObjectMethod(path.node)) { - return path; - } + return concat(parts); - // this function only replaces generators. - if (!path.node.generator) { - return path; - } + case "VariableDeclaration": + parts.push(n.kind, " "); + var maxLen = 0; + var printed = path.map(function(childPath) { + var lines = print(childPath); + maxLen = Math.max(lines.length, maxLen); + return lines; + }, "declarations"); - var parameters = path.node.params.map(function (param) { - return t.cloneDeep(param); - }); + if (maxLen === 1) { + parts.push(fromString(", ").join(printed)); + } else if (printed.length > 1 ) { + parts.push( + fromString(",\n").join(printed) + .indentTail(n.kind.length + 1) + ); + } else { + parts.push(printed[0]); + } - var functionExpression = t.functionExpression(null, // id - parameters, // params - t.cloneDeep(path.node.body), // body - path.node.generator, path.node.async); + // We generally want to terminate all variable declarations with a + // semicolon, except when they are children of for loops. + var parentNode = path.getParentNode(); + if (!namedTypes.ForStatement.check(parentNode) && + !namedTypes.ForInStatement.check(parentNode) && + !(namedTypes.ForOfStatement && + namedTypes.ForOfStatement.check(parentNode)) && + !(namedTypes.ForAwaitStatement && + namedTypes.ForAwaitStatement.check(parentNode))) { + parts.push(";"); + } - util.replaceWithOrRemove(path, t.objectProperty(t.cloneDeep(path.node.key), // key - functionExpression, //value - path.node.computed, // computed - false // shorthand - )); + return concat(parts); - // path now refers to the ObjectProperty AST node path, but we want to return a - // Function AST node path for the function expression we created. we know that - // the FunctionExpression we just created is the value of the ObjectProperty, - // so return the "value" path off of this path. - return path.get("value"); -} -},{"./util":550,"babel-types":573}],550:[function(require,module,exports){ -"use strict"; + case "VariableDeclarator": + return n.init ? fromString(" = ").join([ + path.call(print, "id"), + path.call(print, "init") + ]) : path.call(print, "id"); -exports.__esModule = true; -exports.runtimeProperty = runtimeProperty; -exports.isReference = isReference; -exports.replaceWithOrRemove = replaceWithOrRemove; + case "WithStatement": + return concat([ + "with (", + path.call(print, "object"), + ") ", + path.call(print, "body") + ]); -var _babelTypes = require("babel-types"); + case "IfStatement": + var con = adjustClause(path.call(print, "consequent"), options), + parts = ["if (", path.call(print, "test"), ")", con]; -var t = _interopRequireWildcard(_babelTypes); + if (n.alternate) + parts.push( + endsWithBrace(con) ? " else" : "\nelse", + adjustClause(path.call(print, "alternate"), options)); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return concat(parts); -function runtimeProperty(name) { - return t.memberExpression(t.identifier("regeneratorRuntime"), t.identifier(name), false); -} /** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + case "ForStatement": + // TODO Get the for (;;) case right. + var init = path.call(print, "init"), + sep = init.length > 1 ? ";\n" : "; ", + forParen = "for (", + indented = fromString(sep).join([ + init, + path.call(print, "test"), + path.call(print, "update") + ]).indentTail(forParen.length), + head = concat([forParen, indented, ")"]), + clause = adjustClause(path.call(print, "body"), options), + parts = [head]; -function isReference(path) { - return path.isReferenced() || path.parentPath.isAssignmentExpression({ left: path.node }); -} + if (head.length > 1) { + parts.push("\n"); + clause = clause.trimLeft(); + } -function replaceWithOrRemove(path, replacement) { - if (replacement) { - path.replaceWith(replacement); - } else { - path.remove(); - } -} -},{"babel-types":573}],551:[function(require,module,exports){ -/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ + parts.push(clause); -"use strict"; + return concat(parts); -var _assert = require("assert"); + case "WhileStatement": + return concat([ + "while (", + path.call(print, "test"), + ")", + adjustClause(path.call(print, "body"), options) + ]); -var _assert2 = _interopRequireDefault(_assert); + case "ForInStatement": + // Note: esprima can't actually parse "for each (". + return concat([ + n.each ? "for each (" : "for (", + path.call(print, "left"), + " in ", + path.call(print, "right"), + ")", + adjustClause(path.call(print, "body"), options) + ]); -var _babelTypes = require("babel-types"); + case "ForOfStatement": + return concat([ + "for (", + path.call(print, "left"), + " of ", + path.call(print, "right"), + ")", + adjustClause(path.call(print, "body"), options) + ]); -var t = _interopRequireWildcard(_babelTypes); + case "ForAwaitStatement": + return concat([ + "for await (", + path.call(print, "left"), + " of ", + path.call(print, "right"), + ")", + adjustClause(path.call(print, "body"), options) + ]); -var _hoist = require("./hoist"); + case "DoWhileStatement": + var doBody = concat([ + "do", + adjustClause(path.call(print, "body"), options) + ]), parts = [doBody]; -var _emit = require("./emit"); + if (endsWithBrace(doBody)) + parts.push(" while"); + else + parts.push("\nwhile"); -var _replaceShorthandObjectMethod = require("./replaceShorthandObjectMethod"); + parts.push(" (", path.call(print, "test"), ");"); -var _replaceShorthandObjectMethod2 = _interopRequireDefault(_replaceShorthandObjectMethod); + return concat(parts); -var _util = require("./util"); + case "DoExpression": + var statements = path.call(function(bodyPath) { + return printStatementSequence(bodyPath, options, print); + }, "body"); -var util = _interopRequireWildcard(_util); + return concat([ + "do {\n", + statements.indent(options.tabWidth), + "\n}" + ]); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + case "BreakStatement": + parts.push("break"); + if (n.label) + parts.push(" ", path.call(print, "label")); + parts.push(";"); + return concat(parts); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + case "ContinueStatement": + parts.push("continue"); + if (n.label) + parts.push(" ", path.call(print, "label")); + parts.push(";"); + return concat(parts); -exports.name = "regenerator-transform"; + case "LabeledStatement": + return concat([ + path.call(print, "label"), + ":\n", + path.call(print, "body") + ]); -exports.visitor = { - Function: { - exit: function exit(path, state) { - var node = path.node; + case "TryStatement": + parts.push( + "try ", + path.call(print, "block") + ); - if (node.generator) { - if (node.async) { - // Async generator - if (state.opts.asyncGenerators === false) return; - } else { - // Plain generator - if (state.opts.generators === false) return; + if (n.handler) { + parts.push(" ", path.call(print, "handler")); + } else if (n.handlers) { + path.each(function(handlerPath) { + parts.push(" ", print(handlerPath)); + }, "handlers"); } - } else if (node.async) { - // Async function - if (state.opts.async === false) return; - } else { - // Not a generator or async function. - return; - } - // if this is an ObjectMethod, we need to convert it to an ObjectProperty - path = (0, _replaceShorthandObjectMethod2.default)(path); - node = path.node; + if (n.finalizer) { + parts.push(" finally ", path.call(print, "finalizer")); + } - var contextId = path.scope.generateUidIdentifier("context"); - var argsId = path.scope.generateUidIdentifier("args"); + return concat(parts); - path.ensureBlock(); - var bodyBlockPath = path.get("body"); + case "CatchClause": + parts.push("catch (", path.call(print, "param")); - if (node.async) { - bodyBlockPath.traverse(awaitVisitor); - } + if (n.guard) + // Note: esprima does not recognize conditional catch clauses. + parts.push(" if ", path.call(print, "guard")); - bodyBlockPath.traverse(functionSentVisitor, { - context: contextId - }); + parts.push(") ", path.call(print, "body")); - var outerBody = []; - var innerBody = []; + return concat(parts); - bodyBlockPath.get("body").forEach(function (childPath) { - var node = childPath.node; - if (t.isExpressionStatement(node) && t.isStringLiteral(node.expression)) { - // Babylon represents directives like "use strict" as elements - // of a bodyBlockPath.node.directives array, but they could just - // as easily be represented (by other parsers) as traditional - // string-literal-valued expression statements, so we need to - // handle that here. (#248) - outerBody.push(node); - } else if (node && node._blockHoist != null) { - outerBody.push(node); - } else { - innerBody.push(node); - } - }); + case "ThrowStatement": + return concat(["throw ", path.call(print, "argument"), ";"]); - if (outerBody.length > 0) { - // Only replace the inner body if we actually hoisted any statements - // to the outer body. - bodyBlockPath.node.body = innerBody; - } + case "SwitchStatement": + return concat([ + "switch (", + path.call(print, "discriminant"), + ") {\n", + fromString("\n").join(path.map(print, "cases")), + "\n}" + ]); - var outerFnExpr = getOuterFnExpr(path); - // Note that getOuterFnExpr has the side-effect of ensuring that the - // function has a name (so node.id will always be an Identifier), even - // if a temporary name has to be synthesized. - t.assertIdentifier(node.id); - var innerFnId = t.identifier(node.id.name + "$"); + // Note: ignoring n.lexical because it has no printing consequences. - // Turn all declarations into vars, and replace the original - // declarations with equivalent assignment expressions. - var vars = (0, _hoist.hoist)(path); + case "SwitchCase": + if (n.test) + parts.push("case ", path.call(print, "test"), ":"); + else + parts.push("default:"); - var didRenameArguments = renameArguments(path, argsId); - if (didRenameArguments) { - vars = vars || t.variableDeclaration("var", []); - var argumentIdentifier = t.identifier("arguments"); - // we need to do this as otherwise arguments in arrow functions gets hoisted - argumentIdentifier._shadowedFunctionLiteral = path; - vars.declarations.push(t.variableDeclarator(argsId, argumentIdentifier)); - } + if (n.consequent.length > 0) { + parts.push("\n", path.call(function(consequentPath) { + return printStatementSequence(consequentPath, options, print); + }, "consequent").indent(options.tabWidth)); + } - var emitter = new _emit.Emitter(contextId); - emitter.explode(path.get("body")); + return concat(parts); - if (vars && vars.declarations.length > 0) { - outerBody.push(vars); - } + case "DebuggerStatement": + return fromString("debugger;"); - var wrapArgs = [emitter.getContextFunction(innerFnId), - // Async functions that are not generators don't care about the - // outer function because they don't need it to be marked and don't - // inherit from its .prototype. - node.generator ? outerFnExpr : t.nullLiteral(), t.thisExpression()]; + // JSX extensions below. - var tryLocsList = emitter.getTryLocsList(); - if (tryLocsList) { - wrapArgs.push(tryLocsList); - } + case "JSXAttribute": + parts.push(path.call(print, "name")); + if (n.value) + parts.push("=", path.call(print, "value")); + return concat(parts); - var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs); + case "JSXIdentifier": + return fromString(n.name, options); - outerBody.push(t.returnStatement(wrapCall)); - node.body = t.blockStatement(outerBody); + case "JSXNamespacedName": + return fromString(":").join([ + path.call(print, "namespace"), + path.call(print, "name") + ]); - var oldDirectives = bodyBlockPath.node.directives; - if (oldDirectives) { - // Babylon represents directives like "use strict" as elements of - // a bodyBlockPath.node.directives array. (#248) - node.body.directives = oldDirectives; - } + case "JSXMemberExpression": + return fromString(".").join([ + path.call(print, "object"), + path.call(print, "property") + ]); - var wasGeneratorFunction = node.generator; - if (wasGeneratorFunction) { - node.generator = false; - } + case "JSXSpreadAttribute": + return concat(["{...", path.call(print, "argument"), "}"]); - if (node.async) { - node.async = false; - } + case "JSXExpressionContainer": + return concat(["{", path.call(print, "expression"), "}"]); - if (wasGeneratorFunction && t.isExpression(node)) { - util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node])); - path.addComment("leading", "#__PURE__"); - } + case "JSXElement": + var openingLines = path.call(print, "openingElement"); - // Generators are processed in 'exit' handlers so that regenerator only has to run on - // an ES5 AST, but that means traversal will not pick up newly inserted references - // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue. - path.requeue(); - } - } -}; + if (n.openingElement.selfClosing) { + assert.ok(!n.closingElement); + return openingLines; + } -// Given a NodePath for a Function, return an Expression node that can be -// used to refer reliably to the function object from inside the function. -// This expression is essentially a replacement for arguments.callee, with -// the key advantage that it works in strict mode. -function getOuterFnExpr(funPath) { - var node = funPath.node; - t.assertFunction(node); + var childLines = concat( + path.map(function(childPath) { + var child = childPath.getValue(); - if (!node.id) { - // Default-exported function declarations, and function expressions may not - // have a name to reference, so we explicitly add one. - node.id = funPath.scope.parent.generateUidIdentifier("callee"); - } + if (namedTypes.Literal.check(child) && + typeof child.value === "string") { + if (/\S/.test(child.value)) { + return child.value.replace(/^\s+|\s+$/g, ""); + } else if (/\n/.test(child.value)) { + return "\n"; + } + } - if (node.generator && // Non-generator functions don't need to be marked. - t.isFunctionDeclaration(node)) { - // Return the identifier returned by runtime.mark(). - return getMarkedFunctionId(funPath); - } + return print(childPath); + }, "children") + ).indentTail(options.tabWidth); - return node.id; -} + var closingLines = path.call(print, "closingElement"); -var getMarkInfo = require("private").makeAccessor(); + return concat([ + openingLines, + childLines, + closingLines + ]); -function getMarkedFunctionId(funPath) { - var node = funPath.node; - t.assertIdentifier(node.id); + case "JSXOpeningElement": + parts.push("<", path.call(print, "name")); + var attrParts = []; - var blockPath = funPath.findParent(function (path) { - return path.isProgram() || path.isBlockStatement(); - }); + path.each(function(attrPath) { + attrParts.push(" ", print(attrPath)); + }, "attributes"); - if (!blockPath) { - return node.id; - } + var attrLines = concat(attrParts); - var block = blockPath.node; - _assert2.default.ok(Array.isArray(block.body)); + var needLineWrap = ( + attrLines.length > 1 || + attrLines.getLineLength(1) > options.wrapColumn + ); - var info = getMarkInfo(block); - if (!info.decl) { - info.decl = t.variableDeclaration("var", []); - blockPath.unshiftContainer("body", info.decl); - info.declPath = blockPath.get("body.0"); - } + if (needLineWrap) { + attrParts.forEach(function(part, i) { + if (part === " ") { + assert.strictEqual(i % 2, 0); + attrParts[i] = "\n"; + } + }); - _assert2.default.strictEqual(info.declPath.node, info.decl); + attrLines = concat(attrParts).indentTail(options.tabWidth); + } - // Get a new unique identifier for our marked variable. - var markedId = blockPath.scope.generateUidIdentifier("marked"); - var markCallExp = t.callExpression(util.runtimeProperty("mark"), [node.id]); + parts.push(attrLines, n.selfClosing ? " />" : ">"); - var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1; + return concat(parts); - var markCallExpPath = info.declPath.get("declarations." + index + ".init"); + case "JSXClosingElement": + return concat([""]); - _assert2.default.strictEqual(markCallExpPath.node, markCallExp); + case "JSXText": + return fromString(n.value, options); - markCallExpPath.addComment("leading", "#__PURE__"); + case "JSXEmptyExpression": + return fromString(""); - return markedId; -} + case "TypeAnnotatedIdentifier": + return concat([ + path.call(print, "annotation"), + " ", + path.call(print, "identifier") + ]); -function renameArguments(funcPath, argsId) { - var state = { - didRenameArguments: false, - argsId: argsId - }; + case "ClassBody": + if (n.body.length === 0) { + return fromString("{}"); + } - funcPath.traverse(argumentsVisitor, state); + return concat([ + "{\n", + path.call(function(bodyPath) { + return printStatementSequence(bodyPath, options, print); + }, "body").indent(options.tabWidth), + "\n}" + ]); - // If the traversal replaced any arguments references, then we need to - // alias the outer function's arguments binding (be it the implicit - // arguments object or some other parameter or variable) to the variable - // named by argsId. - return state.didRenameArguments; -} + case "ClassPropertyDefinition": + parts.push("static ", path.call(print, "definition")); + if (!namedTypes.MethodDefinition.check(n.definition)) + parts.push(";"); + return concat(parts); -var argumentsVisitor = { - "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { - path.skip(); - }, + case "ClassProperty": + if (n.static) + parts.push("static "); - Identifier: function Identifier(path, state) { - if (path.node.name === "arguments" && util.isReference(path)) { - util.replaceWithOrRemove(path, state.argsId); - state.didRenameArguments = true; - } - } -}; + var key = path.call(print, "key"); + if (n.computed) { + key = concat(["[", key, "]"]); + } else if (n.variance === "plus") { + key = concat(["+", key]); + } else if (n.variance === "minus") { + key = concat(["-", key]); + } + parts.push(key); -var functionSentVisitor = { - MetaProperty: function MetaProperty(path) { - var node = path.node; + if (n.typeAnnotation) + parts.push(path.call(print, "typeAnnotation")); + if (n.value) + parts.push(" = ", path.call(print, "value")); - if (node.meta.name === "function" && node.property.name === "sent") { - util.replaceWithOrRemove(path, t.memberExpression(this.context, t.identifier("_sent"))); - } - } -}; + parts.push(";"); + return concat(parts); -var awaitVisitor = { - Function: function Function(path) { - path.skip(); // Don't descend into nested function scopes. - }, + case "ClassDeclaration": + case "ClassExpression": + parts.push("class"); - AwaitExpression: function AwaitExpression(path) { - // Convert await expressions to yield expressions. - var argument = path.node.argument; + if (n.id) { + parts.push( + " ", + path.call(print, "id"), + path.call(print, "typeParameters") + ); + } - // Transforming `await x` to `yield regeneratorRuntime.awrap(x)` - // causes the argument to be wrapped in such a way that the runtime - // can distinguish between awaited and merely yielded values. - util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false)); - } -}; -},{"./emit":544,"./hoist":545,"./replaceShorthandObjectMethod":549,"./util":550,"assert":791,"babel-types":573,"private":787}],552:[function(require,module,exports){ -arguments[4][89][0].apply(exports,arguments) -},{"core-js/library/fn/get-iterator":577,"dup":89}],553:[function(require,module,exports){ -arguments[4][90][0].apply(exports,arguments) -},{"core-js/library/fn/json/stringify":578,"dup":90}],554:[function(require,module,exports){ -arguments[4][92][0].apply(exports,arguments) -},{"core-js/library/fn/number/max-safe-integer":579,"dup":92}],555:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"core-js/library/fn/object/create":580,"dup":94}],556:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"core-js/library/fn/object/get-own-property-symbols":581,"dup":95}],557:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"core-js/library/fn/object/keys":582,"dup":96}],558:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"core-js/library/fn/symbol":584,"dup":98}],559:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"core-js/library/fn/symbol/for":583,"dup":99}],560:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"core-js/library/fn/symbol/iterator":585,"dup":100}],561:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"../core-js/symbol":558,"../core-js/symbol/iterator":560,"dup":107}],562:[function(require,module,exports){ -arguments[4][134][0].apply(exports,arguments) -},{"babel-runtime/core-js/symbol/for":559,"dup":134}],563:[function(require,module,exports){ -arguments[4][135][0].apply(exports,arguments) -},{"./index":573,"babel-runtime/core-js/get-iterator":552,"babel-runtime/core-js/json/stringify":553,"babel-runtime/core-js/number/max-safe-integer":554,"dup":135,"lodash/isPlainObject":778,"lodash/isRegExp":779}],564:[function(require,module,exports){ -arguments[4][136][0].apply(exports,arguments) -},{"../constants":562,"../index":573,"./index":568,"dup":136}],565:[function(require,module,exports){ -arguments[4][137][0].apply(exports,arguments) -},{"./index":568,"dup":137}],566:[function(require,module,exports){ -arguments[4][138][0].apply(exports,arguments) -},{"./index":568,"dup":138}],567:[function(require,module,exports){ -arguments[4][139][0].apply(exports,arguments) -},{"./index":568,"dup":139}],568:[function(require,module,exports){ -arguments[4][140][0].apply(exports,arguments) -},{"../index":573,"babel-runtime/core-js/get-iterator":552,"babel-runtime/core-js/json/stringify":553,"babel-runtime/helpers/typeof":561,"dup":140}],569:[function(require,module,exports){ -arguments[4][141][0].apply(exports,arguments) -},{"./core":564,"./es2015":565,"./experimental":566,"./flow":567,"./index":568,"./jsx":570,"./misc":571,"dup":141}],570:[function(require,module,exports){ -arguments[4][142][0].apply(exports,arguments) -},{"./index":568,"dup":142}],571:[function(require,module,exports){ -arguments[4][143][0].apply(exports,arguments) -},{"./index":568,"dup":143}],572:[function(require,module,exports){ -arguments[4][144][0].apply(exports,arguments) -},{"./index":573,"dup":144}],573:[function(require,module,exports){ -arguments[4][145][0].apply(exports,arguments) -},{"./constants":562,"./converters":563,"./definitions":568,"./definitions/init":569,"./flow":572,"./react":574,"./retrievers":575,"./validators":576,"babel-runtime/core-js/get-iterator":552,"babel-runtime/core-js/json/stringify":553,"babel-runtime/core-js/object/get-own-property-symbols":556,"babel-runtime/core-js/object/keys":557,"dup":145,"lodash/clone":768,"lodash/uniq":786,"to-fast-properties":788}],574:[function(require,module,exports){ -arguments[4][146][0].apply(exports,arguments) -},{"./index":573,"dup":146}],575:[function(require,module,exports){ -arguments[4][147][0].apply(exports,arguments) -},{"./index":573,"babel-runtime/core-js/object/create":555,"dup":147}],576:[function(require,module,exports){ -arguments[4][148][0].apply(exports,arguments) -},{"./constants":562,"./index":573,"./retrievers":575,"babel-runtime/core-js/get-iterator":552,"babel-runtime/core-js/object/keys":557,"babel-runtime/helpers/typeof":561,"dup":148,"esutils":659}],577:[function(require,module,exports){ -require('../modules/web.dom.iterable'); -require('../modules/es6.string.iterator'); -module.exports = require('../modules/core.get-iterator'); -},{"../modules/core.get-iterator":645,"../modules/es6.string.iterator":651,"../modules/web.dom.iterable":655}],578:[function(require,module,exports){ -var core = require('../../modules/_core') - , $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify}); -module.exports = function stringify(it){ // eslint-disable-line no-unused-vars - return $JSON.stringify.apply($JSON, arguments); -}; -},{"../../modules/_core":592}],579:[function(require,module,exports){ -require('../../modules/es6.number.max-safe-integer'); -module.exports = 0x1fffffffffffff; -},{"../../modules/es6.number.max-safe-integer":647}],580:[function(require,module,exports){ -require('../../modules/es6.object.create'); -var $Object = require('../../modules/_core').Object; -module.exports = function create(P, D){ - return $Object.create(P, D); -}; -},{"../../modules/_core":592,"../../modules/es6.object.create":648}],581:[function(require,module,exports){ -require('../../modules/es6.symbol'); -module.exports = require('../../modules/_core').Object.getOwnPropertySymbols; -},{"../../modules/_core":592,"../../modules/es6.symbol":652}],582:[function(require,module,exports){ -require('../../modules/es6.object.keys'); -module.exports = require('../../modules/_core').Object.keys; -},{"../../modules/_core":592,"../../modules/es6.object.keys":649}],583:[function(require,module,exports){ -require('../../modules/es6.symbol'); -module.exports = require('../../modules/_core').Symbol['for']; -},{"../../modules/_core":592,"../../modules/es6.symbol":652}],584:[function(require,module,exports){ -require('../../modules/es6.symbol'); -require('../../modules/es6.object.to-string'); -require('../../modules/es7.symbol.async-iterator'); -require('../../modules/es7.symbol.observable'); -module.exports = require('../../modules/_core').Symbol; -},{"../../modules/_core":592,"../../modules/es6.object.to-string":650,"../../modules/es6.symbol":652,"../../modules/es7.symbol.async-iterator":653,"../../modules/es7.symbol.observable":654}],585:[function(require,module,exports){ -require('../../modules/es6.string.iterator'); -require('../../modules/web.dom.iterable'); -module.exports = require('../../modules/_wks-ext').f('iterator'); -},{"../../modules/_wks-ext":642,"../../modules/es6.string.iterator":651,"../../modules/web.dom.iterable":655}],586:[function(require,module,exports){ -module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; -}; -},{}],587:[function(require,module,exports){ -module.exports = function(){ /* empty */ }; -},{}],588:[function(require,module,exports){ -var isObject = require('./_is-object'); -module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; -}; -},{"./_is-object":608}],589:[function(require,module,exports){ -// false -> Array#indexOf -// true -> Array#includes -var toIObject = require('./_to-iobject') - , toLength = require('./_to-length') - , toIndex = require('./_to-index'); -module.exports = function(IS_INCLUDES){ - return function($this, el, fromIndex){ - var O = toIObject($this) - , length = toLength(O.length) - , index = toIndex(fromIndex, length) - , value; - // Array#includes uses SameValueZero equality algorithm - if(IS_INCLUDES && el != el)while(length > index){ - value = O[index++]; - if(value != value)return true; - // Array#toIndex ignores holes, Array#includes - not - } else for(;length > index; index++)if(IS_INCLUDES || index in O){ - if(O[index] === el)return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; -}; -},{"./_to-index":634,"./_to-iobject":636,"./_to-length":637}],590:[function(require,module,exports){ -// getting tag from 19.1.3.6 Object.prototype.toString() -var cof = require('./_cof') - , TAG = require('./_wks')('toStringTag') - // ES3 wrong here - , ARG = cof(function(){ return arguments; }()) == 'Arguments'; + if (n.superClass) { + parts.push( + " extends ", + path.call(print, "superClass"), + path.call(print, "superTypeParameters") + ); + } -// fallback for IE11 Script Access Denied error -var tryGet = function(it, key){ - try { - return it[key]; - } catch(e){ /* empty */ } -}; + if (n["implements"] && n['implements'].length > 0) { + parts.push( + " implements ", + fromString(", ").join(path.map(print, "implements")) + ); + } -module.exports = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; -},{"./_cof":591,"./_wks":643}],591:[function(require,module,exports){ -var toString = {}.toString; + parts.push(" ", path.call(print, "body")); -module.exports = function(it){ - return toString.call(it).slice(8, -1); -}; -},{}],592:[function(require,module,exports){ -var core = module.exports = {version: '2.4.0'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef -},{}],593:[function(require,module,exports){ -// optional / simple context binding -var aFunction = require('./_a-function'); -module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; -}; -},{"./_a-function":586}],594:[function(require,module,exports){ -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; -}; -},{}],595:[function(require,module,exports){ -// Thank's IE8 for his funny defineProperty -module.exports = !require('./_fails')(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; -}); -},{"./_fails":600}],596:[function(require,module,exports){ -var isObject = require('./_is-object') - , document = require('./_global').document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; -},{"./_global":601,"./_is-object":608}],597:[function(require,module,exports){ -// IE 8- don't enum bug keys -module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' -).split(','); -},{}],598:[function(require,module,exports){ -// all enumerable object keys, includes symbols -var getKeys = require('./_object-keys') - , gOPS = require('./_object-gops') - , pIE = require('./_object-pie'); -module.exports = function(it){ - var result = getKeys(it) - , getSymbols = gOPS.f; - if(getSymbols){ - var symbols = getSymbols(it) - , isEnum = pIE.f - , i = 0 - , key; - while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); - } return result; -}; -},{"./_object-gops":622,"./_object-keys":625,"./_object-pie":626}],599:[function(require,module,exports){ -var global = require('./_global') - , core = require('./_core') - , ctx = require('./_ctx') - , hide = require('./_hide') - , PROTOTYPE = 'prototype'; - -var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(a, b, c){ - if(this instanceof C){ - switch(arguments.length){ - case 0: return new C; - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if(IS_PROTO){ - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); - } - } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -$export.U = 64; // safe -$export.R = 128; // real proto method for `library` -module.exports = $export; -},{"./_core":592,"./_ctx":593,"./_global":601,"./_hide":603}],600:[function(require,module,exports){ -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } -}; -},{}],601:[function(require,module,exports){ -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); -if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef -},{}],602:[function(require,module,exports){ -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function(it, key){ - return hasOwnProperty.call(it, key); -}; -},{}],603:[function(require,module,exports){ -var dP = require('./_object-dp') - , createDesc = require('./_property-desc'); -module.exports = require('./_descriptors') ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); -} : function(object, key, value){ - object[key] = value; - return object; -}; -},{"./_descriptors":595,"./_object-dp":617,"./_property-desc":628}],604:[function(require,module,exports){ -module.exports = require('./_global').document && document.documentElement; -},{"./_global":601}],605:[function(require,module,exports){ -module.exports = !require('./_descriptors') && !require('./_fails')(function(){ - return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7; -}); -},{"./_descriptors":595,"./_dom-create":596,"./_fails":600}],606:[function(require,module,exports){ -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = require('./_cof'); -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); -}; -},{"./_cof":591}],607:[function(require,module,exports){ -// 7.2.2 IsArray(argument) -var cof = require('./_cof'); -module.exports = Array.isArray || function isArray(arg){ - return cof(arg) == 'Array'; -}; -},{"./_cof":591}],608:[function(require,module,exports){ -module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; -}; -},{}],609:[function(require,module,exports){ -'use strict'; -var create = require('./_object-create') - , descriptor = require('./_property-desc') - , setToStringTag = require('./_set-to-string-tag') - , IteratorPrototype = {}; + return concat(parts); -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; }); + case "TemplateElement": + return fromString(n.value.raw, options).lockIndentTail(); -module.exports = function(Constructor, NAME, next){ - Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); - setToStringTag(Constructor, NAME + ' Iterator'); -}; -},{"./_hide":603,"./_object-create":616,"./_property-desc":628,"./_set-to-string-tag":630,"./_wks":643}],610:[function(require,module,exports){ -'use strict'; -var LIBRARY = require('./_library') - , $export = require('./_export') - , redefine = require('./_redefine') - , hide = require('./_hide') - , has = require('./_has') - , Iterators = require('./_iterators') - , $iterCreate = require('./_iter-create') - , setToStringTag = require('./_set-to-string-tag') - , getPrototypeOf = require('./_object-gpo') - , ITERATOR = require('./_wks')('iterator') - , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` - , FF_ITERATOR = '@@iterator' - , KEYS = 'keys' - , VALUES = 'values'; - -var returnThis = function(){ return this; }; - -module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ - $iterCreate(Constructor, NAME, next); - var getMethod = function(kind){ - if(!BUGGY && kind in proto)return proto[kind]; - switch(kind){ - case KEYS: return function keys(){ return new Constructor(this, kind); }; - case VALUES: return function values(){ return new Constructor(this, kind); }; - } return function entries(){ return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator' - , DEF_VALUES = DEFAULT == VALUES - , VALUES_BUG = false - , proto = Base.prototype - , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] - , $default = $native || getMethod(DEFAULT) - , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined - , $anyNative = NAME == 'Array' ? proto.entries || $native : $native - , methods, key, IteratorPrototype; - // Fix native - if($anyNative){ - IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); - if(IteratorPrototype !== Object.prototype){ - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if(DEF_VALUES && $native && $native.name !== VALUES){ - VALUES_BUG = true; - $default = function values(){ return $native.call(this); }; - } - // Define iterator - if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if(DEFAULT){ - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if(FORCED)for(key in methods){ - if(!(key in proto))redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; -}; -},{"./_export":599,"./_has":602,"./_hide":603,"./_iter-create":609,"./_iterators":612,"./_library":614,"./_object-gpo":623,"./_redefine":629,"./_set-to-string-tag":630,"./_wks":643}],611:[function(require,module,exports){ -module.exports = function(done, value){ - return {value: value, done: !!done}; -}; -},{}],612:[function(require,module,exports){ -module.exports = {}; -},{}],613:[function(require,module,exports){ -var getKeys = require('./_object-keys') - , toIObject = require('./_to-iobject'); -module.exports = function(object, el){ - var O = toIObject(object) - , keys = getKeys(O) - , length = keys.length - , index = 0 - , key; - while(length > index)if(O[key = keys[index++]] === el)return key; -}; -},{"./_object-keys":625,"./_to-iobject":636}],614:[function(require,module,exports){ -module.exports = true; -},{}],615:[function(require,module,exports){ -var META = require('./_uid')('meta') - , isObject = require('./_is-object') - , has = require('./_has') - , setDesc = require('./_object-dp').f - , id = 0; -var isExtensible = Object.isExtensible || function(){ - return true; -}; -var FREEZE = !require('./_fails')(function(){ - return isExtensible(Object.preventExtensions({})); -}); -var setMeta = function(it){ - setDesc(it, META, {value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - }}); -}; -var fastKey = function(it, create){ - // return primitive with prefix - if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return 'F'; - // not necessary to add metadata - if(!create)return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; -}; -var getWeak = function(it, create){ - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return true; - // not necessary to add metadata - if(!create)return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; -}; -// add metadata on freeze-family methods calling -var onFreeze = function(it){ - if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); - return it; -}; -var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze -}; -},{"./_fails":600,"./_has":602,"./_is-object":608,"./_object-dp":617,"./_uid":640}],616:[function(require,module,exports){ -// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -var anObject = require('./_an-object') - , dPs = require('./_object-dps') - , enumBugKeys = require('./_enum-bug-keys') - , IE_PROTO = require('./_shared-key')('IE_PROTO') - , Empty = function(){ /* empty */ } - , PROTOTYPE = 'prototype'; + case "TemplateLiteral": + var expressions = path.map(print, "expressions"); + parts.push("`"); -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var createDict = function(){ - // Thrash, waste and sodomy: IE GC bug - var iframe = require('./_dom-create')('iframe') - , i = enumBugKeys.length - , lt = '<' - , gt = '>' - , iframeDocument; - iframe.style.display = 'none'; - require('./_html').appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); -}; + path.each(function(childPath) { + var i = childPath.getName(); + parts.push(print(childPath)); + if (i < expressions.length) { + parts.push("${", expressions[i], "}"); + } + }, "quasis"); -module.exports = Object.create || function create(O, Properties){ - var result; - if(O !== null){ - Empty[PROTOTYPE] = anObject(O); - result = new Empty; - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); -}; + parts.push("`"); -},{"./_an-object":588,"./_dom-create":596,"./_enum-bug-keys":597,"./_html":604,"./_object-dps":618,"./_shared-key":631}],617:[function(require,module,exports){ -var anObject = require('./_an-object') - , IE8_DOM_DEFINE = require('./_ie8-dom-define') - , toPrimitive = require('./_to-primitive') - , dP = Object.defineProperty; + return concat(parts).lockIndentTail(); -exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; -}; -},{"./_an-object":588,"./_descriptors":595,"./_ie8-dom-define":605,"./_to-primitive":639}],618:[function(require,module,exports){ -var dP = require('./_object-dp') - , anObject = require('./_an-object') - , getKeys = require('./_object-keys'); + case "TaggedTemplateExpression": + return concat([ + path.call(print, "tag"), + path.call(print, "quasi") + ]); -module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){ - anObject(O); - var keys = getKeys(Properties) - , length = keys.length - , i = 0 - , P; - while(length > i)dP.f(O, P = keys[i++], Properties[P]); - return O; -}; -},{"./_an-object":588,"./_descriptors":595,"./_object-dp":617,"./_object-keys":625}],619:[function(require,module,exports){ -var pIE = require('./_object-pie') - , createDesc = require('./_property-desc') - , toIObject = require('./_to-iobject') - , toPrimitive = require('./_to-primitive') - , has = require('./_has') - , IE8_DOM_DEFINE = require('./_ie8-dom-define') - , gOPD = Object.getOwnPropertyDescriptor; + // These types are unprintable because they serve as abstract + // supertypes for other (printable) types. + case "Node": + case "Printable": + case "SourceLocation": + case "Position": + case "Statement": + case "Function": + case "Pattern": + case "Expression": + case "Declaration": + case "Specifier": + case "NamedSpecifier": + case "Comment": // Supertype of Block and Line. + case "MemberTypeAnnotation": // Flow + case "TupleTypeAnnotation": // Flow + case "Type": // Flow + throw new Error("unprintable type: " + JSON.stringify(n.type)); -exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){ - O = toIObject(O); - P = toPrimitive(P, true); - if(IE8_DOM_DEFINE)try { - return gOPD(O, P); - } catch(e){ /* empty */ } - if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); -}; -},{"./_descriptors":595,"./_has":602,"./_ie8-dom-define":605,"./_object-pie":626,"./_property-desc":628,"./_to-iobject":636,"./_to-primitive":639}],620:[function(require,module,exports){ -// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window -var toIObject = require('./_to-iobject') - , gOPN = require('./_object-gopn').f - , toString = {}.toString; + case "CommentBlock": // Babel block comment. + case "Block": // Esprima block comment. + return concat(["/*", fromString(n.value, options), "*/"]); -var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; + case "CommentLine": // Babel line comment. + case "Line": // Esprima line comment. + return concat(["//", fromString(n.value, options)]); -var getWindowNames = function(it){ - try { - return gOPN(it); - } catch(e){ - return windowNames.slice(); - } -}; + // Type Annotations for Facebook Flow, typically stripped out or + // transformed away before printing. + case "TypeAnnotation": + if (n.typeAnnotation) { + if (n.typeAnnotation.type !== "FunctionTypeAnnotation") { + parts.push(": "); + } + parts.push(path.call(print, "typeAnnotation")); + return concat(parts); + } -module.exports.f = function getOwnPropertyNames(it){ - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); -}; + return fromString(""); -},{"./_object-gopn":621,"./_to-iobject":636}],621:[function(require,module,exports){ -// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) -var $keys = require('./_object-keys-internal') - , hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype'); + case "ExistentialTypeParam": + case "ExistsTypeAnnotation": + return fromString("*", options); -exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ - return $keys(O, hiddenKeys); -}; -},{"./_enum-bug-keys":597,"./_object-keys-internal":624}],622:[function(require,module,exports){ -exports.f = Object.getOwnPropertySymbols; -},{}],623:[function(require,module,exports){ -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var has = require('./_has') - , toObject = require('./_to-object') - , IE_PROTO = require('./_shared-key')('IE_PROTO') - , ObjectProto = Object.prototype; + case "EmptyTypeAnnotation": + return fromString("empty", options); -module.exports = Object.getPrototypeOf || function(O){ - O = toObject(O); - if(has(O, IE_PROTO))return O[IE_PROTO]; - if(typeof O.constructor == 'function' && O instanceof O.constructor){ - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; -}; -},{"./_has":602,"./_shared-key":631,"./_to-object":638}],624:[function(require,module,exports){ -var has = require('./_has') - , toIObject = require('./_to-iobject') - , arrayIndexOf = require('./_array-includes')(false) - , IE_PROTO = require('./_shared-key')('IE_PROTO'); - -module.exports = function(object, names){ - var O = toIObject(object) - , i = 0 - , result = [] - , key; - for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while(names.length > i)if(has(O, key = names[i++])){ - ~arrayIndexOf(result, key) || result.push(key); - } - return result; -}; -},{"./_array-includes":589,"./_has":602,"./_shared-key":631,"./_to-iobject":636}],625:[function(require,module,exports){ -// 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = require('./_object-keys-internal') - , enumBugKeys = require('./_enum-bug-keys'); + case "AnyTypeAnnotation": + return fromString("any", options); -module.exports = Object.keys || function keys(O){ - return $keys(O, enumBugKeys); -}; -},{"./_enum-bug-keys":597,"./_object-keys-internal":624}],626:[function(require,module,exports){ -exports.f = {}.propertyIsEnumerable; -},{}],627:[function(require,module,exports){ -// most Object methods by ES6 should accept primitives -var $export = require('./_export') - , core = require('./_core') - , fails = require('./_fails'); -module.exports = function(KEY, exec){ - var fn = (core.Object || {})[KEY] || Object[KEY] - , exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); -}; -},{"./_core":592,"./_export":599,"./_fails":600}],628:[function(require,module,exports){ -module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; -}; -},{}],629:[function(require,module,exports){ -module.exports = require('./_hide'); -},{"./_hide":603}],630:[function(require,module,exports){ -var def = require('./_object-dp').f - , has = require('./_has') - , TAG = require('./_wks')('toStringTag'); - -module.exports = function(it, tag, stat){ - if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); -}; -},{"./_has":602,"./_object-dp":617,"./_wks":643}],631:[function(require,module,exports){ -var shared = require('./_shared')('keys') - , uid = require('./_uid'); -module.exports = function(key){ - return shared[key] || (shared[key] = uid(key)); -}; -},{"./_shared":632,"./_uid":640}],632:[function(require,module,exports){ -var global = require('./_global') - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); -module.exports = function(key){ - return store[key] || (store[key] = {}); -}; -},{"./_global":601}],633:[function(require,module,exports){ -var toInteger = require('./_to-integer') - , defined = require('./_defined'); -// true -> String#at -// false -> String#codePointAt -module.exports = function(TO_STRING){ - return function(that, pos){ - var s = String(defined(that)) - , i = toInteger(pos) - , l = s.length - , a, b; - if(i < 0 || i >= l)return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; -},{"./_defined":594,"./_to-integer":635}],634:[function(require,module,exports){ -var toInteger = require('./_to-integer') - , max = Math.max - , min = Math.min; -module.exports = function(index, length){ - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; -},{"./_to-integer":635}],635:[function(require,module,exports){ -// 7.1.4 ToInteger -var ceil = Math.ceil - , floor = Math.floor; -module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; -},{}],636:[function(require,module,exports){ -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = require('./_iobject') - , defined = require('./_defined'); -module.exports = function(it){ - return IObject(defined(it)); -}; -},{"./_defined":594,"./_iobject":606}],637:[function(require,module,exports){ -// 7.1.15 ToLength -var toInteger = require('./_to-integer') - , min = Math.min; -module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; -},{"./_to-integer":635}],638:[function(require,module,exports){ -// 7.1.13 ToObject(argument) -var defined = require('./_defined'); -module.exports = function(it){ - return Object(defined(it)); -}; -},{"./_defined":594}],639:[function(require,module,exports){ -// 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = require('./_is-object'); -// instead of the ES6 spec version, we didn't implement @@toPrimitive case -// and the second argument - flag - preferred type is a string -module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); -}; -},{"./_is-object":608}],640:[function(require,module,exports){ -var id = 0 - , px = Math.random(); -module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; -},{}],641:[function(require,module,exports){ -var global = require('./_global') - , core = require('./_core') - , LIBRARY = require('./_library') - , wksExt = require('./_wks-ext') - , defineProperty = require('./_object-dp').f; -module.exports = function(name){ - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); -}; -},{"./_core":592,"./_global":601,"./_library":614,"./_object-dp":617,"./_wks-ext":642}],642:[function(require,module,exports){ -exports.f = require('./_wks'); -},{"./_wks":643}],643:[function(require,module,exports){ -var store = require('./_shared')('wks') - , uid = require('./_uid') - , Symbol = require('./_global').Symbol - , USE_SYMBOL = typeof Symbol == 'function'; + case "MixedTypeAnnotation": + return fromString("mixed", options); -var $exports = module.exports = function(name){ - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); -}; + case "ArrayTypeAnnotation": + return concat([ + path.call(print, "elementType"), + "[]" + ]); -$exports.store = store; -},{"./_global":601,"./_shared":632,"./_uid":640}],644:[function(require,module,exports){ -var classof = require('./_classof') - , ITERATOR = require('./_wks')('iterator') - , Iterators = require('./_iterators'); -module.exports = require('./_core').getIteratorMethod = function(it){ - if(it != undefined)return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; -}; -},{"./_classof":590,"./_core":592,"./_iterators":612,"./_wks":643}],645:[function(require,module,exports){ -var anObject = require('./_an-object') - , get = require('./core.get-iterator-method'); -module.exports = require('./_core').getIterator = function(it){ - var iterFn = get(it); - if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); - return anObject(iterFn.call(it)); -}; -},{"./_an-object":588,"./_core":592,"./core.get-iterator-method":644}],646:[function(require,module,exports){ -'use strict'; -var addToUnscopables = require('./_add-to-unscopables') - , step = require('./_iter-step') - , Iterators = require('./_iterators') - , toIObject = require('./_to-iobject'); + case "BooleanTypeAnnotation": + return fromString("boolean", options); -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){ - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function(){ - var O = this._t - , kind = this._k - , index = this._i++; - if(!O || index >= O.length){ - this._t = undefined; - return step(1); - } - if(kind == 'keys' )return step(0, index); - if(kind == 'values')return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); + case "BooleanLiteralTypeAnnotation": + assert.strictEqual(typeof n.value, "boolean"); + return fromString("" + n.value, options); -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; + case "DeclareClass": + return printFlowDeclaration(path, [ + "class ", + path.call(print, "id"), + " ", + path.call(print, "body"), + ]); -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); -},{"./_add-to-unscopables":587,"./_iter-define":610,"./_iter-step":611,"./_iterators":612,"./_to-iobject":636}],647:[function(require,module,exports){ -// 20.1.2.6 Number.MAX_SAFE_INTEGER -var $export = require('./_export'); + case "DeclareFunction": + return printFlowDeclaration(path, [ + "function ", + path.call(print, "id"), + ";" + ]); -$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); -},{"./_export":599}],648:[function(require,module,exports){ -var $export = require('./_export') -// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -$export($export.S, 'Object', {create: require('./_object-create')}); -},{"./_export":599,"./_object-create":616}],649:[function(require,module,exports){ -// 19.1.2.14 Object.keys(O) -var toObject = require('./_to-object') - , $keys = require('./_object-keys'); + case "DeclareModule": + return printFlowDeclaration(path, [ + "module ", + path.call(print, "id"), + " ", + path.call(print, "body"), + ]); -require('./_object-sap')('keys', function(){ - return function keys(it){ - return $keys(toObject(it)); - }; -}); -},{"./_object-keys":625,"./_object-sap":627,"./_to-object":638}],650:[function(require,module,exports){ -arguments[4][255][0].apply(exports,arguments) -},{"dup":255}],651:[function(require,module,exports){ -'use strict'; -var $at = require('./_string-at')(true); + case "DeclareModuleExports": + return printFlowDeclaration(path, [ + "module.exports", + path.call(print, "typeAnnotation"), + ]); -// 21.1.3.27 String.prototype[@@iterator]() -require('./_iter-define')(String, 'String', function(iterated){ - this._t = String(iterated); // target - this._i = 0; // next index -// 21.1.5.2.1 %StringIteratorPrototype%.next() -}, function(){ - var O = this._t - , index = this._i - , point; - if(index >= O.length)return {value: undefined, done: true}; - point = $at(O, index); - this._i += point.length; - return {value: point, done: false}; -}); -},{"./_iter-define":610,"./_string-at":633}],652:[function(require,module,exports){ -'use strict'; -// ECMAScript 6 symbols shim -var global = require('./_global') - , has = require('./_has') - , DESCRIPTORS = require('./_descriptors') - , $export = require('./_export') - , redefine = require('./_redefine') - , META = require('./_meta').KEY - , $fails = require('./_fails') - , shared = require('./_shared') - , setToStringTag = require('./_set-to-string-tag') - , uid = require('./_uid') - , wks = require('./_wks') - , wksExt = require('./_wks-ext') - , wksDefine = require('./_wks-define') - , keyOf = require('./_keyof') - , enumKeys = require('./_enum-keys') - , isArray = require('./_is-array') - , anObject = require('./_an-object') - , toIObject = require('./_to-iobject') - , toPrimitive = require('./_to-primitive') - , createDesc = require('./_property-desc') - , _create = require('./_object-create') - , gOPNExt = require('./_object-gopn-ext') - , $GOPD = require('./_object-gopd') - , $DP = require('./_object-dp') - , $keys = require('./_object-keys') - , gOPD = $GOPD.f - , dP = $DP.f - , gOPN = gOPNExt.f - , $Symbol = global.Symbol - , $JSON = global.JSON - , _stringify = $JSON && $JSON.stringify - , PROTOTYPE = 'prototype' - , HIDDEN = wks('_hidden') - , TO_PRIMITIVE = wks('toPrimitive') - , isEnum = {}.propertyIsEnumerable - , SymbolRegistry = shared('symbol-registry') - , AllSymbols = shared('symbols') - , OPSymbols = shared('op-symbols') - , ObjectProto = Object[PROTOTYPE] - , USE_NATIVE = typeof $Symbol == 'function' - , QObject = global.QObject; -// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 -var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + case "DeclareVariable": + return printFlowDeclaration(path, [ + "var ", + path.call(print, "id"), + ";" + ]); + + case "DeclareExportDeclaration": + case "DeclareExportAllDeclaration": + return concat([ + "declare ", + printExportDeclaration(path, options, print) + ]); -// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 -var setSymbolDesc = DESCRIPTORS && $fails(function(){ - return _create(dP({}, 'a', { - get: function(){ return dP(this, 'a', {value: 7}).a; } - })).a != 7; -}) ? function(it, key, D){ - var protoDesc = gOPD(ObjectProto, key); - if(protoDesc)delete ObjectProto[key]; - dP(it, key, D); - if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); -} : dP; + case "FunctionTypeAnnotation": + // FunctionTypeAnnotation is ambiguous: + // declare function(a: B): void; OR + // var A: (a: B) => void; + var parent = path.getParentNode(0); + var isArrowFunctionTypeAnnotation = !( + namedTypes.ObjectTypeCallProperty.check(parent) || + namedTypes.DeclareFunction.check(path.getParentNode(2)) + ); -var wrap = function(tag){ - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; -}; + var needsColon = + isArrowFunctionTypeAnnotation && + !namedTypes.FunctionTypeParam.check(parent); -var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ - return typeof it == 'symbol'; -} : function(it){ - return it instanceof $Symbol; -}; + if (needsColon) { + parts.push(": "); + } -var $defineProperty = function defineProperty(it, key, D){ - if(it === ObjectProto)$defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if(has(AllSymbols, key)){ - if(!D.enumerable){ - if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; - D = _create(D, {enumerable: createDesc(0, false)}); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); -}; -var $defineProperties = function defineProperties(it, P){ - anObject(it); - var keys = enumKeys(P = toIObject(P)) - , i = 0 - , l = keys.length - , key; - while(l > i)$defineProperty(it, key = keys[i++], P[key]); - return it; -}; -var $create = function create(it, P){ - return P === undefined ? _create(it) : $defineProperties(_create(it), P); -}; -var $propertyIsEnumerable = function propertyIsEnumerable(key){ - var E = isEnum.call(this, key = toPrimitive(key, true)); - if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; -}; -var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ - it = toIObject(it); - key = toPrimitive(key, true); - if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; - var D = gOPD(it, key); - if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; - return D; -}; -var $getOwnPropertyNames = function getOwnPropertyNames(it){ - var names = gOPN(toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i){ - if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); - } return result; -}; -var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ - var IS_OP = it === ObjectProto - , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) - , result = [] - , i = 0 - , key; - while(names.length > i){ - if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); - } return result; -}; + parts.push( + "(", + fromString(", ").join(path.map(print, "params")), + ")" + ); -// 19.4.1.1 Symbol([description]) -if(!USE_NATIVE){ - $Symbol = function Symbol(){ - if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function(value){ - if(this === ObjectProto)$set.call(OPSymbols, value); - if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString(){ - return this._k; - }); + // The returnType is not wrapped in a TypeAnnotation, so the colon + // needs to be added separately. + if (n.returnType) { + parts.push( + isArrowFunctionTypeAnnotation ? " => " : ": ", + path.call(print, "returnType") + ); + } - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames; - require('./_object-pie').f = $propertyIsEnumerable; - require('./_object-gops').f = $getOwnPropertySymbols; + return concat(parts); - if(DESCRIPTORS && !require('./_library')){ - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } + case "FunctionTypeParam": + return concat([ + path.call(print, "name"), + n.optional ? '?' : '', + ": ", + path.call(print, "typeAnnotation"), + ]); - wksExt.f = function(name){ - return wrap(wks(name)); - } -} + case "GenericTypeAnnotation": + return concat([ + path.call(print, "id"), + path.call(print, "typeParameters") + ]); -$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); + case "DeclareInterface": + parts.push("declare "); -for(var symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' -).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); + case "InterfaceDeclaration": + parts.push( + fromString("interface ", options), + path.call(print, "id"), + path.call(print, "typeParameters"), + " " + ); -for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); + if (n["extends"]) { + parts.push( + "extends ", + fromString(", ").join(path.map(print, "extends")) + ); + } -$export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function(key){ - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(key){ - if(isSymbol(key))return keyOf(SymbolRegistry, key); - throw TypeError(key + ' is not a symbol!'); - }, - useSetter: function(){ setter = true; }, - useSimple: function(){ setter = false; } -}); + parts.push(" ", path.call(print, "body")); -$export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols -}); + return concat(parts); -// 24.3.2 JSON.stringify(value [, replacer [, space]]) -$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; -})), 'JSON', { - stringify: function stringify(it){ - if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined - var args = [it] - , i = 1 - , replacer, $replacer; - while(arguments.length > i)args.push(arguments[i++]); - replacer = args[1]; - if(typeof replacer == 'function')$replacer = replacer; - if($replacer || !isArray(replacer))replacer = function(key, value){ - if($replacer)value = $replacer.call(this, key, value); - if(!isSymbol(value))return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } -}); + case "ClassImplements": + case "InterfaceExtends": + return concat([ + path.call(print, "id"), + path.call(print, "typeParameters") + ]); -// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) -$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); -// 19.4.3.5 Symbol.prototype[@@toStringTag] -setToStringTag($Symbol, 'Symbol'); -// 20.2.1.9 Math[@@toStringTag] -setToStringTag(Math, 'Math', true); -// 24.3.3 JSON[@@toStringTag] -setToStringTag(global.JSON, 'JSON', true); -},{"./_an-object":588,"./_descriptors":595,"./_enum-keys":598,"./_export":599,"./_fails":600,"./_global":601,"./_has":602,"./_hide":603,"./_is-array":607,"./_keyof":613,"./_library":614,"./_meta":615,"./_object-create":616,"./_object-dp":617,"./_object-gopd":619,"./_object-gopn":621,"./_object-gopn-ext":620,"./_object-gops":622,"./_object-keys":625,"./_object-pie":626,"./_property-desc":628,"./_redefine":629,"./_set-to-string-tag":630,"./_shared":632,"./_to-iobject":636,"./_to-primitive":639,"./_uid":640,"./_wks":643,"./_wks-define":641,"./_wks-ext":642}],653:[function(require,module,exports){ -require('./_wks-define')('asyncIterator'); -},{"./_wks-define":641}],654:[function(require,module,exports){ -require('./_wks-define')('observable'); -},{"./_wks-define":641}],655:[function(require,module,exports){ -require('./es6.array.iterator'); -var global = require('./_global') - , hide = require('./_hide') - , Iterators = require('./_iterators') - , TO_STRING_TAG = require('./_wks')('toStringTag'); - -for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ - var NAME = collections[i] - , Collection = global[NAME] - , proto = Collection && Collection.prototype; - if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = Iterators.Array; -} -},{"./_global":601,"./_hide":603,"./_iterators":612,"./_wks":643,"./es6.array.iterator":646}],656:[function(require,module,exports){ -arguments[4][277][0].apply(exports,arguments) -},{"dup":277}],657:[function(require,module,exports){ -arguments[4][278][0].apply(exports,arguments) -},{"dup":278}],658:[function(require,module,exports){ -arguments[4][279][0].apply(exports,arguments) -},{"./code":657,"dup":279}],659:[function(require,module,exports){ -arguments[4][280][0].apply(exports,arguments) -},{"./ast":656,"./code":657,"./keyword":658,"dup":280}],660:[function(require,module,exports){ -arguments[4][289][0].apply(exports,arguments) -},{"./_getNative":721,"./_root":757,"dup":289}],661:[function(require,module,exports){ -arguments[4][290][0].apply(exports,arguments) -},{"./_hashClear":728,"./_hashDelete":729,"./_hashGet":730,"./_hashHas":731,"./_hashSet":732,"dup":290}],662:[function(require,module,exports){ -arguments[4][291][0].apply(exports,arguments) -},{"./_listCacheClear":740,"./_listCacheDelete":741,"./_listCacheGet":742,"./_listCacheHas":743,"./_listCacheSet":744,"dup":291}],663:[function(require,module,exports){ -arguments[4][292][0].apply(exports,arguments) -},{"./_getNative":721,"./_root":757,"dup":292}],664:[function(require,module,exports){ -arguments[4][293][0].apply(exports,arguments) -},{"./_mapCacheClear":745,"./_mapCacheDelete":746,"./_mapCacheGet":747,"./_mapCacheHas":748,"./_mapCacheSet":749,"dup":293}],665:[function(require,module,exports){ -arguments[4][294][0].apply(exports,arguments) -},{"./_getNative":721,"./_root":757,"dup":294}],666:[function(require,module,exports){ -arguments[4][295][0].apply(exports,arguments) -},{"./_getNative":721,"./_root":757,"dup":295}],667:[function(require,module,exports){ -arguments[4][296][0].apply(exports,arguments) -},{"./_MapCache":664,"./_setCacheAdd":758,"./_setCacheHas":759,"dup":296}],668:[function(require,module,exports){ -arguments[4][297][0].apply(exports,arguments) -},{"./_ListCache":662,"./_stackClear":761,"./_stackDelete":762,"./_stackGet":763,"./_stackHas":764,"./_stackSet":765,"dup":297}],669:[function(require,module,exports){ -arguments[4][298][0].apply(exports,arguments) -},{"./_root":757,"dup":298}],670:[function(require,module,exports){ -arguments[4][299][0].apply(exports,arguments) -},{"./_root":757,"dup":299}],671:[function(require,module,exports){ -arguments[4][300][0].apply(exports,arguments) -},{"./_getNative":721,"./_root":757,"dup":300}],672:[function(require,module,exports){ -arguments[4][301][0].apply(exports,arguments) -},{"dup":301}],673:[function(require,module,exports){ -arguments[4][302][0].apply(exports,arguments) -},{"dup":302}],674:[function(require,module,exports){ -arguments[4][304][0].apply(exports,arguments) -},{"dup":304}],675:[function(require,module,exports){ -arguments[4][306][0].apply(exports,arguments) -},{"./_baseIndexOf":690,"dup":306}],676:[function(require,module,exports){ -arguments[4][307][0].apply(exports,arguments) -},{"dup":307}],677:[function(require,module,exports){ -arguments[4][308][0].apply(exports,arguments) -},{"./_baseTimes":698,"./_isIndex":736,"./isArguments":770,"./isArray":771,"./isBuffer":773,"./isTypedArray":780,"dup":308}],678:[function(require,module,exports){ -arguments[4][310][0].apply(exports,arguments) -},{"dup":310}],679:[function(require,module,exports){ -arguments[4][311][0].apply(exports,arguments) -},{"dup":311}],680:[function(require,module,exports){ -arguments[4][314][0].apply(exports,arguments) -},{"./_baseAssignValue":684,"./eq":769,"dup":314}],681:[function(require,module,exports){ -arguments[4][315][0].apply(exports,arguments) -},{"./eq":769,"dup":315}],682:[function(require,module,exports){ -arguments[4][316][0].apply(exports,arguments) -},{"./_copyObject":711,"./keys":781,"dup":316}],683:[function(require,module,exports){ -arguments[4][317][0].apply(exports,arguments) -},{"./_copyObject":711,"./keysIn":782,"dup":317}],684:[function(require,module,exports){ -arguments[4][318][0].apply(exports,arguments) -},{"./_defineProperty":716,"dup":318}],685:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"./_Stack":668,"./_arrayEach":674,"./_assignValue":680,"./_baseAssign":682,"./_baseAssignIn":683,"./_cloneBuffer":703,"./_copyArray":710,"./_copySymbols":712,"./_copySymbolsIn":713,"./_getAllKeys":718,"./_getAllKeysIn":719,"./_getTag":726,"./_initCloneArray":733,"./_initCloneByTag":734,"./_initCloneObject":735,"./isArray":771,"./isBuffer":773,"./isObject":776,"./keys":781,"dup":320}],686:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./isObject":776,"dup":321}],687:[function(require,module,exports){ -arguments[4][323][0].apply(exports,arguments) -},{"dup":323}],688:[function(require,module,exports){ -arguments[4][328][0].apply(exports,arguments) -},{"./_arrayPush":678,"./isArray":771,"dup":328}],689:[function(require,module,exports){ -var Symbol = require('./_Symbol'), - getRawTag = require('./_getRawTag'), - objectToString = require('./_objectToString'); + case "IntersectionTypeAnnotation": + return fromString(" & ").join(path.map(print, "types")); -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; + case "NullableTypeAnnotation": + return concat([ + "?", + path.call(print, "typeAnnotation") + ]); -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + case "NullLiteralTypeAnnotation": + return fromString("null", options); -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - value = Object(value); - return (symToStringTag && symToStringTag in value) - ? getRawTag(value) - : objectToString(value); -} + case "ThisTypeAnnotation": + return fromString("this", options); -module.exports = baseGetTag; + case "NumberTypeAnnotation": + return fromString("number", options); -},{"./_Symbol":669,"./_getRawTag":723,"./_objectToString":755}],690:[function(require,module,exports){ -arguments[4][332][0].apply(exports,arguments) -},{"./_baseFindIndex":687,"./_baseIsNaN":692,"./_strictIndexOf":766,"dup":332}],691:[function(require,module,exports){ -arguments[4][333][0].apply(exports,arguments) -},{"./_baseGetTag":689,"./isObjectLike":777,"dup":333}],692:[function(require,module,exports){ -arguments[4][337][0].apply(exports,arguments) -},{"dup":337}],693:[function(require,module,exports){ -arguments[4][338][0].apply(exports,arguments) -},{"./_isMasked":738,"./_toSource":767,"./isFunction":774,"./isObject":776,"dup":338}],694:[function(require,module,exports){ -arguments[4][339][0].apply(exports,arguments) -},{"./_baseGetTag":689,"./isObjectLike":777,"dup":339}],695:[function(require,module,exports){ -arguments[4][340][0].apply(exports,arguments) -},{"./_baseGetTag":689,"./isLength":775,"./isObjectLike":777,"dup":340}],696:[function(require,module,exports){ -arguments[4][342][0].apply(exports,arguments) -},{"./_isPrototype":739,"./_nativeKeys":752,"dup":342}],697:[function(require,module,exports){ -arguments[4][343][0].apply(exports,arguments) -},{"./_isPrototype":739,"./_nativeKeysIn":753,"./isObject":776,"dup":343}],698:[function(require,module,exports){ -arguments[4][356][0].apply(exports,arguments) -},{"dup":356}],699:[function(require,module,exports){ -arguments[4][358][0].apply(exports,arguments) -},{"dup":358}],700:[function(require,module,exports){ -arguments[4][359][0].apply(exports,arguments) -},{"./_SetCache":667,"./_arrayIncludes":675,"./_arrayIncludesWith":676,"./_cacheHas":701,"./_createSet":715,"./_setToArray":760,"dup":359}],701:[function(require,module,exports){ -arguments[4][361][0].apply(exports,arguments) -},{"dup":361}],702:[function(require,module,exports){ -arguments[4][363][0].apply(exports,arguments) -},{"./_Uint8Array":670,"dup":363}],703:[function(require,module,exports){ -arguments[4][364][0].apply(exports,arguments) -},{"./_root":757,"dup":364}],704:[function(require,module,exports){ -arguments[4][365][0].apply(exports,arguments) -},{"./_cloneArrayBuffer":702,"dup":365}],705:[function(require,module,exports){ -arguments[4][366][0].apply(exports,arguments) -},{"./_addMapEntry":672,"./_arrayReduce":679,"./_mapToArray":750,"dup":366}],706:[function(require,module,exports){ -arguments[4][367][0].apply(exports,arguments) -},{"dup":367}],707:[function(require,module,exports){ -arguments[4][368][0].apply(exports,arguments) -},{"./_addSetEntry":673,"./_arrayReduce":679,"./_setToArray":760,"dup":368}],708:[function(require,module,exports){ -arguments[4][369][0].apply(exports,arguments) -},{"./_Symbol":669,"dup":369}],709:[function(require,module,exports){ -arguments[4][370][0].apply(exports,arguments) -},{"./_cloneArrayBuffer":702,"dup":370}],710:[function(require,module,exports){ -arguments[4][373][0].apply(exports,arguments) -},{"dup":373}],711:[function(require,module,exports){ -arguments[4][374][0].apply(exports,arguments) -},{"./_assignValue":680,"./_baseAssignValue":684,"dup":374}],712:[function(require,module,exports){ -arguments[4][375][0].apply(exports,arguments) -},{"./_copyObject":711,"./_getSymbols":724,"dup":375}],713:[function(require,module,exports){ -arguments[4][376][0].apply(exports,arguments) -},{"./_copyObject":711,"./_getSymbolsIn":725,"dup":376}],714:[function(require,module,exports){ -arguments[4][377][0].apply(exports,arguments) -},{"./_root":757,"dup":377}],715:[function(require,module,exports){ -arguments[4][382][0].apply(exports,arguments) -},{"./_Set":666,"./_setToArray":760,"./noop":783,"dup":382}],716:[function(require,module,exports){ -arguments[4][384][0].apply(exports,arguments) -},{"./_getNative":721,"dup":384}],717:[function(require,module,exports){ -arguments[4][388][0].apply(exports,arguments) -},{"dup":388}],718:[function(require,module,exports){ -arguments[4][389][0].apply(exports,arguments) -},{"./_baseGetAllKeys":688,"./_getSymbols":724,"./keys":781,"dup":389}],719:[function(require,module,exports){ -arguments[4][390][0].apply(exports,arguments) -},{"./_baseGetAllKeys":688,"./_getSymbolsIn":725,"./keysIn":782,"dup":390}],720:[function(require,module,exports){ -arguments[4][391][0].apply(exports,arguments) -},{"./_isKeyable":737,"dup":391}],721:[function(require,module,exports){ -arguments[4][393][0].apply(exports,arguments) -},{"./_baseIsNative":693,"./_getValue":727,"dup":393}],722:[function(require,module,exports){ -arguments[4][394][0].apply(exports,arguments) -},{"./_overArg":756,"dup":394}],723:[function(require,module,exports){ -arguments[4][395][0].apply(exports,arguments) -},{"./_Symbol":669,"dup":395}],724:[function(require,module,exports){ -var overArg = require('./_overArg'), - stubArray = require('./stubArray'); + case "ObjectTypeCallProperty": + return path.call(print, "value"); -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols = Object.getOwnPropertySymbols; + case "ObjectTypeIndexer": + var variance = + n.variance === "plus" ? "+" : + n.variance === "minus" ? "-" : ""; -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; + return concat([ + variance, + "[", + path.call(print, "id"), + ": ", + path.call(print, "key"), + "]: ", + path.call(print, "value") + ]); -module.exports = getSymbols; + case "ObjectTypeProperty": + var variance = + n.variance === "plus" ? "+" : + n.variance === "minus" ? "-" : ""; -},{"./_overArg":756,"./stubArray":784}],725:[function(require,module,exports){ -arguments[4][397][0].apply(exports,arguments) -},{"./_arrayPush":678,"./_getPrototype":722,"./_getSymbols":724,"./stubArray":784,"dup":397}],726:[function(require,module,exports){ -arguments[4][398][0].apply(exports,arguments) -},{"./_DataView":660,"./_Map":663,"./_Promise":665,"./_Set":666,"./_WeakMap":671,"./_baseGetTag":689,"./_toSource":767,"dup":398}],727:[function(require,module,exports){ -arguments[4][399][0].apply(exports,arguments) -},{"dup":399}],728:[function(require,module,exports){ -arguments[4][401][0].apply(exports,arguments) -},{"./_nativeCreate":751,"dup":401}],729:[function(require,module,exports){ -arguments[4][402][0].apply(exports,arguments) -},{"dup":402}],730:[function(require,module,exports){ -arguments[4][403][0].apply(exports,arguments) -},{"./_nativeCreate":751,"dup":403}],731:[function(require,module,exports){ -var nativeCreate = require('./_nativeCreate'); + return concat([ + variance, + path.call(print, "key"), + n.optional ? "?" : "", + ": ", + path.call(print, "value") + ]); -/** Used for built-in method references. */ -var objectProto = Object.prototype; + case "QualifiedTypeIdentifier": + return concat([ + path.call(print, "qualification"), + ".", + path.call(print, "id") + ]); -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + case "StringLiteralTypeAnnotation": + return fromString(nodeStr(n.value, options), options); -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} + case "NumberLiteralTypeAnnotation": + case "NumericLiteralTypeAnnotation": + assert.strictEqual(typeof n.value, "number"); + return fromString(JSON.stringify(n.value), options); -module.exports = hashHas; + case "StringTypeAnnotation": + return fromString("string", options); -},{"./_nativeCreate":751}],732:[function(require,module,exports){ -arguments[4][405][0].apply(exports,arguments) -},{"./_nativeCreate":751,"dup":405}],733:[function(require,module,exports){ -arguments[4][406][0].apply(exports,arguments) -},{"dup":406}],734:[function(require,module,exports){ -arguments[4][407][0].apply(exports,arguments) -},{"./_cloneArrayBuffer":702,"./_cloneDataView":704,"./_cloneMap":705,"./_cloneRegExp":706,"./_cloneSet":707,"./_cloneSymbol":708,"./_cloneTypedArray":709,"dup":407}],735:[function(require,module,exports){ -arguments[4][408][0].apply(exports,arguments) -},{"./_baseCreate":686,"./_getPrototype":722,"./_isPrototype":739,"dup":408}],736:[function(require,module,exports){ -arguments[4][410][0].apply(exports,arguments) -},{"dup":410}],737:[function(require,module,exports){ -arguments[4][413][0].apply(exports,arguments) -},{"dup":413}],738:[function(require,module,exports){ -arguments[4][414][0].apply(exports,arguments) -},{"./_coreJsData":714,"dup":414}],739:[function(require,module,exports){ -arguments[4][415][0].apply(exports,arguments) -},{"dup":415}],740:[function(require,module,exports){ -arguments[4][417][0].apply(exports,arguments) -},{"dup":417}],741:[function(require,module,exports){ -arguments[4][418][0].apply(exports,arguments) -},{"./_assocIndexOf":681,"dup":418}],742:[function(require,module,exports){ -arguments[4][419][0].apply(exports,arguments) -},{"./_assocIndexOf":681,"dup":419}],743:[function(require,module,exports){ -arguments[4][420][0].apply(exports,arguments) -},{"./_assocIndexOf":681,"dup":420}],744:[function(require,module,exports){ -arguments[4][421][0].apply(exports,arguments) -},{"./_assocIndexOf":681,"dup":421}],745:[function(require,module,exports){ -arguments[4][422][0].apply(exports,arguments) -},{"./_Hash":661,"./_ListCache":662,"./_Map":663,"dup":422}],746:[function(require,module,exports){ -arguments[4][423][0].apply(exports,arguments) -},{"./_getMapData":720,"dup":423}],747:[function(require,module,exports){ -arguments[4][424][0].apply(exports,arguments) -},{"./_getMapData":720,"dup":424}],748:[function(require,module,exports){ -arguments[4][425][0].apply(exports,arguments) -},{"./_getMapData":720,"dup":425}],749:[function(require,module,exports){ -arguments[4][426][0].apply(exports,arguments) -},{"./_getMapData":720,"dup":426}],750:[function(require,module,exports){ -arguments[4][427][0].apply(exports,arguments) -},{"dup":427}],751:[function(require,module,exports){ -arguments[4][430][0].apply(exports,arguments) -},{"./_getNative":721,"dup":430}],752:[function(require,module,exports){ -arguments[4][431][0].apply(exports,arguments) -},{"./_overArg":756,"dup":431}],753:[function(require,module,exports){ -arguments[4][432][0].apply(exports,arguments) -},{"dup":432}],754:[function(require,module,exports){ -arguments[4][433][0].apply(exports,arguments) -},{"./_freeGlobal":717,"dup":433}],755:[function(require,module,exports){ -arguments[4][434][0].apply(exports,arguments) -},{"dup":434}],756:[function(require,module,exports){ -arguments[4][435][0].apply(exports,arguments) -},{"dup":435}],757:[function(require,module,exports){ -arguments[4][437][0].apply(exports,arguments) -},{"./_freeGlobal":717,"dup":437}],758:[function(require,module,exports){ -arguments[4][438][0].apply(exports,arguments) -},{"dup":438}],759:[function(require,module,exports){ -arguments[4][439][0].apply(exports,arguments) -},{"dup":439}],760:[function(require,module,exports){ -arguments[4][440][0].apply(exports,arguments) -},{"dup":440}],761:[function(require,module,exports){ -arguments[4][443][0].apply(exports,arguments) -},{"./_ListCache":662,"dup":443}],762:[function(require,module,exports){ -arguments[4][444][0].apply(exports,arguments) -},{"dup":444}],763:[function(require,module,exports){ -arguments[4][445][0].apply(exports,arguments) -},{"dup":445}],764:[function(require,module,exports){ -arguments[4][446][0].apply(exports,arguments) -},{"dup":446}],765:[function(require,module,exports){ -arguments[4][447][0].apply(exports,arguments) -},{"./_ListCache":662,"./_Map":663,"./_MapCache":664,"dup":447}],766:[function(require,module,exports){ -arguments[4][448][0].apply(exports,arguments) -},{"dup":448}],767:[function(require,module,exports){ -arguments[4][451][0].apply(exports,arguments) -},{"dup":451}],768:[function(require,module,exports){ -arguments[4][455][0].apply(exports,arguments) -},{"./_baseClone":685,"dup":455}],769:[function(require,module,exports){ -arguments[4][460][0].apply(exports,arguments) -},{"dup":460}],770:[function(require,module,exports){ -arguments[4][472][0].apply(exports,arguments) -},{"./_baseIsArguments":691,"./isObjectLike":777,"dup":472}],771:[function(require,module,exports){ -arguments[4][473][0].apply(exports,arguments) -},{"dup":473}],772:[function(require,module,exports){ -arguments[4][474][0].apply(exports,arguments) -},{"./isFunction":774,"./isLength":775,"dup":474}],773:[function(require,module,exports){ -arguments[4][476][0].apply(exports,arguments) -},{"./_root":757,"./stubFalse":785,"dup":476}],774:[function(require,module,exports){ -arguments[4][477][0].apply(exports,arguments) -},{"./_baseGetTag":689,"./isObject":776,"dup":477}],775:[function(require,module,exports){ -arguments[4][479][0].apply(exports,arguments) -},{"dup":479}],776:[function(require,module,exports){ -arguments[4][480][0].apply(exports,arguments) -},{"dup":480}],777:[function(require,module,exports){ -arguments[4][481][0].apply(exports,arguments) -},{"dup":481}],778:[function(require,module,exports){ -arguments[4][482][0].apply(exports,arguments) -},{"./_baseGetTag":689,"./_getPrototype":722,"./isObjectLike":777,"dup":482}],779:[function(require,module,exports){ -arguments[4][483][0].apply(exports,arguments) -},{"./_baseIsRegExp":694,"./_baseUnary":699,"./_nodeUtil":754,"dup":483}],780:[function(require,module,exports){ -arguments[4][486][0].apply(exports,arguments) -},{"./_baseIsTypedArray":695,"./_baseUnary":699,"./_nodeUtil":754,"dup":486}],781:[function(require,module,exports){ -arguments[4][487][0].apply(exports,arguments) -},{"./_arrayLikeKeys":677,"./_baseKeys":696,"./isArrayLike":772,"dup":487}],782:[function(require,module,exports){ -arguments[4][488][0].apply(exports,arguments) -},{"./_arrayLikeKeys":677,"./_baseKeysIn":697,"./isArrayLike":772,"dup":488}],783:[function(require,module,exports){ -arguments[4][492][0].apply(exports,arguments) -},{"dup":492}],784:[function(require,module,exports){ -arguments[4][497][0].apply(exports,arguments) -},{"dup":497}],785:[function(require,module,exports){ -arguments[4][498][0].apply(exports,arguments) -},{"dup":498}],786:[function(require,module,exports){ -arguments[4][504][0].apply(exports,arguments) -},{"./_baseUniq":700,"dup":504}],787:[function(require,module,exports){ -arguments[4][510][0].apply(exports,arguments) -},{"dup":510}],788:[function(require,module,exports){ -'use strict'; -module.exports = function toFastProperties(obj) { - function f() {} - f.prototype = obj; - new f(); - return; - eval(obj); -}; - -},{}],789:[function(require,module,exports){ -arguments[4][255][0].apply(exports,arguments) -},{"dup":255}],790:[function(require,module,exports){ -arguments[4][255][0].apply(exports,arguments) -},{"dup":255}],791:[function(require,module,exports){ -(function (global){ -'use strict'; + case "DeclareTypeAlias": + parts.push("declare "); -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: + case "TypeAlias": + return concat([ + "type ", + path.call(print, "id"), + path.call(print, "typeParameters"), + " = ", + path.call(print, "right"), + ";" + ]); -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } + case "TypeCastExpression": + return concat([ + "(", + path.call(print, "expression"), + path.call(print, "typeAnnotation"), + ")" + ]); - var x = a.length; - var y = b.length; + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + return concat([ + "<", + fromString(", ").join(path.map(print, "params")), + ">" + ]); + case "TypeParameter": + switch (n.variance) { + case 'plus': + parts.push('+'); + break; + case 'minus': + parts.push('-'); + break; + default: + } - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } + parts.push(path.call(print, 'name')); - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} + if (n.bound) { + parts.push(path.call(print, 'bound')); + } -// based on node assert, original notice: + if (n['default']) { + parts.push('=', path.call(print, 'default')); + } -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + return concat(parts); -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. + case "TypeofTypeAnnotation": + return concat([ + fromString("typeof ", options), + path.call(print, "argument") + ]); -var assert = module.exports = ok; + case "UnionTypeAnnotation": + return fromString(" | ").join(path.map(print, "types")); -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) + case "VoidTypeAnnotation": + return fromString("void", options); -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; + case "NullTypeAnnotation": + return fromString("null", options); - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } + // Unhandled types below. If encountered, nodes of these types should + // be either left alone or desugared into AST types that are fully + // supported by the pretty-printer. + case "ClassHeritage": // TODO + case "ComprehensionBlock": // TODO + case "ComprehensionExpression": // TODO + case "Glob": // TODO + case "GeneratorExpression": // TODO + case "LetStatement": // TODO + case "LetExpression": // TODO + case "GraphExpression": // TODO + case "GraphIndexExpression": // TODO - this.stack = out; + // XML types that nobody cares about or needs to print. + case "XMLDefaultDeclaration": + case "XMLAnyName": + case "XMLQualifiedIdentifier": + case "XMLFunctionQualifiedIdentifier": + case "XMLAttributeSelector": + case "XMLFilterExpression": + case "XML": + case "XMLElement": + case "XMLList": + case "XMLEscape": + case "XMLText": + case "XMLStartTag": + case "XMLEndTag": + case "XMLPointTag": + case "XMLName": + case "XMLAttribute": + case "XMLCdata": + case "XMLComment": + case "XMLProcessingInstruction": + default: + debugger; + throw new Error("unknown type: " + JSON.stringify(n.type)); } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); + return p; } -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. +function printStatementSequence(path, options, print) { + var inClassBody = + namedTypes.ClassBody && + namedTypes.ClassBody.check(path.getParentNode()); -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. + var filtered = []; + var sawComment = false; + var sawStatement = false; -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} + path.each(function(stmtPath) { + var i = stmtPath.getName(); + var stmt = stmtPath.getValue(); -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; + // Just in case the AST has been modified to contain falsy + // "statements," it's safer simply to skip them. + if (!stmt) { + return; + } -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. + // Skip printing EmptyStatement nodes to avoid leaving stray + // semicolons lying around. + if (stmt.type === "EmptyStatement") { + return; + } -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; + if (namedTypes.Comment.check(stmt)) { + // The pretty printer allows a dangling Comment node to act as + // a Statement when the Comment can't be attached to any other + // non-Comment node in the tree. + sawComment = true; + } else if (namedTypes.Statement.check(stmt)) { + sawStatement = true; + } else { + // When the pretty printer encounters a string instead of an + // AST node, it just prints the string. This behavior can be + // useful for fine-grained formatting decisions like inserting + // blank lines. + isString.assert(stmt); + } -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); + // We can't hang onto stmtPath outside of this function, because + // it's just a reference to a mutable FastPath object, so we have + // to go ahead and print it here. + filtered.push({ + node: stmt, + printed: print(stmtPath) + }); + }); -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; + if (sawComment) { + assert.strictEqual( + sawStatement, false, + "Comments may appear as statements in otherwise empty statement " + + "lists, but may not coexist with non-Comment nodes." + ); + } -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); + var prevTrailingSpace = null; + var len = filtered.length; + var parts = []; -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; + filtered.forEach(function(info, i) { + var printed = info.printed; + var stmt = info.node; + var multiLine = printed.length > 1; + var notFirst = i > 0; + var notLast = i < len - 1; + var leadingSpace; + var trailingSpace; + var lines = stmt && stmt.loc && stmt.loc.lines; + var trueLoc = lines && options.reuseWhitespace && + util.getTrueLoc(stmt, lines); -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); + if (notFirst) { + if (trueLoc) { + var beforeStart = lines.skipSpaces(trueLoc.start, true); + var beforeStartLine = beforeStart ? beforeStart.line : 1; + var leadingGap = trueLoc.start.line - beforeStartLine; + leadingSpace = Array(leadingGap + 1).join("\n"); + } else { + leadingSpace = multiLine ? "\n\n" : "\n"; + } + } else { + leadingSpace = ""; + } -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; + if (notLast) { + if (trueLoc) { + var afterEnd = lines.skipSpaces(trueLoc.end); + var afterEndLine = afterEnd ? afterEnd.line : lines.length; + var trailingGap = afterEndLine - trueLoc.end.line; + trailingSpace = Array(trailingGap + 1).join("\n"); + } else { + trailingSpace = multiLine ? "\n\n" : "\n"; + } + } else { + trailingSpace = ""; + } -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; + parts.push( + maxSpace(prevTrailingSpace, leadingSpace), + printed + ); -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; + if (notLast) { + prevTrailingSpace = trailingSpace; + } else if (trailingSpace) { + parts.push(trailingSpace); + } + }); - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); + return concat(parts); +} - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; +function maxSpace(s1, s2) { + if (!s1 && !s2) { + return fromString(""); + } - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; + if (!s1) { + return fromString(s2); + } - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; + if (!s2) { + return fromString(s1); + } - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; + var spaceLines1 = fromString(s1); + var spaceLines2 = fromString(s2); - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } + if (spaceLines2.length > spaceLines1.length) { + return spaceLines2; } - memos.actual.push(actual); - memos.expected.push(expected); - - return objEquiv(actual, expected, strict, memos); - } + return spaceLines1; } -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} +function printMethod(path, options, print) { + var node = path.getNode(); + var kind = node.kind; + var parts = []; -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} + if (node.type === "ObjectMethod" || node.type === "ClassMethod") { + node.value = node; + } else { + namedTypes.FunctionExpression.assert(node.value); + } -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); + if (node.value.async) { + parts.push("async "); + } -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; + if (!kind || kind === "init" || kind === "method" || kind === "constructor") { + if (node.value.generator) { + parts.push("*"); + } + } else { + assert.ok(kind === "get" || kind === "set"); + parts.push(kind, " "); + } -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } + var key = path.call(print, "key"); + if (node.computed) { + key = concat(["[", key, "]"]); + } + + parts.push( + key, + path.call(print, "value", "typeParameters"), + "(", + path.call(function(valuePath) { + return printFunctionParams(valuePath, options, print); + }, "value"), + ")", + path.call(print, "value", "returnType"), + " ", + path.call(print, "value", "body") + ); + + return concat(parts); } +function printArgumentsList(path, options, print) { + var printed = path.map(print, "arguments"); + var trailingComma = util.isTrailingCommaEnabled(options, "parameters"); -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); + var joined = fromString(", ").join(printed); + if (joined.getLineLength(1) > options.wrapColumn) { + joined = fromString(",\n").join(printed); + return concat([ + "(\n", + joined.indent(options.tabWidth), + trailingComma ? ",\n)" : "\n)" + ]); + } -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; + return concat(["(", joined, ")"]); +} -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); +function printFunctionParams(path, options, print) { + var fun = path.getValue(); -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; + namedTypes.Function.assert(fun); -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + var printed = path.map(print, "params"); - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } + if (fun.defaults) { + path.each(function(defExprPath) { + var i = defExprPath.getName(); + var p = printed[i]; + if (p && defExprPath.getValue()) { + printed[i] = concat([p, " = ", print(defExprPath)]); + } + }, "defaults"); + } - try { - if (actual instanceof expected) { - return true; + if (fun.rest) { + printed.push(concat(["...", path.call(print, "rest")])); } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - if (Error.isPrototypeOf(expected)) { - return false; - } + var joined = fromString(", ").join(printed); + if (joined.length > 1 || + joined.getLineLength(1) > options.wrapColumn) { + joined = fromString(",\n").join(printed); + if (util.isTrailingCommaEnabled(options, "parameters") && + !fun.rest && + fun.params[fun.params.length - 1].type !== 'RestElement') { + joined = concat([joined, ",\n"]); + } else { + joined = concat([joined, "\n"]); + } + return concat(["\n", joined.indent(options.tabWidth)]); + } - return expected.call({}, actual) === true; + return joined; } -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} +function printObjectMethod(path, options, print) { + var objMethod = path.getValue(); + var parts = []; -function _throws(shouldThrow, block, expected, message) { - var actual; + if (objMethod.async) + parts.push("async "); - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } + if (objMethod.generator) + parts.push("*"); - if (typeof expected === 'string') { - message = expected; - expected = null; - } + if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") { + return printMethod(path, options, print); + } - actual = _tryBlock(block); + var key = path.call(print, "key"); + if (objMethod.computed) { + parts.push("[", key, "]"); + } else { + parts.push(key); + } - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + parts.push( + "(", + printFunctionParams(path, options, print), + ")", + path.call(print, "returnType"), + " ", + path.call(print, "body") + ); - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + return concat(parts); +} - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; +function printExportDeclaration(path, options, print) { + var decl = path.getValue(); + var parts = ["export "]; + var shouldPrintSpaces = options.objectCurlySpacing; - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } + namedTypes.Declaration.assert(decl); - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} + if (decl["default"] || + decl.type === "ExportDefaultDeclaration") { + parts.push("default "); + } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); + if (decl.declaration) { + parts.push(path.call(print, "declaration")); -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; + } else if (decl.specifiers && + decl.specifiers.length > 0) { -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; + if (decl.specifiers.length === 1 && + decl.specifiers[0].type === "ExportBatchSpecifier") { + parts.push("*"); + } else { + parts.push( + shouldPrintSpaces ? "{ " : "{", + fromString(", ").join(path.map(print, "specifiers")), + shouldPrintSpaces ? " }" : "}" + ); + } + + if (decl.source) { + parts.push(" from ", path.call(print, "source")); + } + } -assert.ifError = function(err) { if (err) throw err; }; + var lines = concat(parts); -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; + if (lastNonSpaceCharacter(lines) !== ";" && + ! (decl.declaration && + (decl.declaration.type === "FunctionDeclaration" || + decl.declaration.type === "ClassDeclaration"))) { + lines = concat([lines, ";"]); + } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":821}],792:[function(require,module,exports){ -'use strict' + return lines; +} -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray +function printFlowDeclaration(path, parts) { + var parentExportDecl = util.getParentExportDeclaration(path); -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + if (parentExportDecl) { + assert.strictEqual( + parentExportDecl.type, + "DeclareExportDeclaration" + ); + } else { + // If the parent node has type DeclareExportDeclaration, then it + // will be responsible for printing the "declare" token. Otherwise + // it needs to be printed with this non-exported declaration node. + parts.unshift("declare "); + } -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i + return concat(parts); } -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +function adjustClause(clause, options) { + if (clause.length > 1) + return concat([" ", clause]); -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + return concat([ + "\n", + maybeAddSemicolon(clause).indent(options.tabWidth) + ]); +} - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +function lastNonSpaceCharacter(lines) { + var pos = lines.lastPos(); + do { + var ch = lines.charAt(pos); + if (/\S/.test(ch)) + return ch; + } while (lines.prevPos(pos)); } -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return (b64.length * 3 / 4) - placeHoldersCount(b64) +function endsWithBrace(lines) { + return lastNonSpaceCharacter(lines) === "}"; } -function toByteArray (b64) { - var i, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) +function swapQuotes(str) { + return str.replace(/['"]/g, function(m) { + return m === '"' ? '\'' : '"'; + }); +} - arr = new Arr((len * 3 / 4) - placeHolders) +function nodeStr(str, options) { + isString.assert(str); + switch (options.quote) { + case "auto": + var double = JSON.stringify(str); + var single = swapQuotes(JSON.stringify(swapQuotes(str))); + return double.length > single.length ? single : double; + case "single": + return swapQuotes(JSON.stringify(swapQuotes(str))); + case "double": + default: + return JSON.stringify(str); + } +} - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len +function maybeAddSemicolon(lines) { + var eoc = lastNonSpaceCharacter(lines); + if (!eoc || "\n};".indexOf(eoc) < 0) + return concat([lines, ";"]); + return lines; +} - var L = 0 +},{"./comments":549,"./fast-path":550,"./lines":551,"./options":553,"./patcher":555,"./types":557,"./util":558,"assert":2,"source-map":572}],557:[function(require,module,exports){ +// This module was originally created so that Recast could add its own +// custom types to the AST type system (in particular, the File type), but +// those types are now incorporated into ast-types, so this module doesn't +// have much to do anymore. Still, it might prove useful in the future. +module.exports = require("ast-types"); - for (i = 0; i < l; i += 4) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } +},{"ast-types":60}],558:[function(require,module,exports){ +var assert = require("assert"); +var types = require("./types"); +var getFieldValue = types.getFieldValue; +var n = types.namedTypes; +var sourceMap = require("source-map"); +var SourceMapConsumer = sourceMap.SourceMapConsumer; +var SourceMapGenerator = sourceMap.SourceMapGenerator; +var hasOwn = Object.prototype.hasOwnProperty; +var util = exports; - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF +function getUnionOfKeys() { + var result = {}; + var argc = arguments.length; + for (var i = 0; i < argc; ++i) { + var keys = Object.keys(arguments[i]); + var keyCount = keys.length; + for (var j = 0; j < keyCount; ++j) { + result[keys[j]] = true; + } } + return result; +} +util.getUnionOfKeys = getUnionOfKeys; - return arr +function comparePos(pos1, pos2) { + return (pos1.line - pos2.line) || (pos1.column - pos2.column); } +util.comparePos = comparePos; -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +function copyPos(pos) { + return { + line: pos.line, + column: pos.column + }; } +util.copyPos = copyPos; -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) +util.composeSourceMaps = function(formerMap, latterMap) { + if (formerMap) { + if (!latterMap) { + return formerMap; + } + } else { + return latterMap || null; } - return output.join('') -} -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 + var smcFormer = new SourceMapConsumer(formerMap); + var smcLatter = new SourceMapConsumer(latterMap); + var smg = new SourceMapGenerator({ + file: latterMap.file, + sourceRoot: latterMap.sourceRoot + }); - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } + var sourcesToContents = {}; - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } + smcLatter.eachMapping(function(mapping) { + var origPos = smcFormer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); - parts.push(output) + var sourceName = origPos.source; + if (sourceName === null) { + return; + } - return parts.join('') -} + smg.addMapping({ + source: sourceName, + original: copyPos(origPos), + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + }, + name: mapping.name + }); -},{}],793:[function(require,module,exports){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ + var sourceContent = smcFormer.sourceContentFor(sourceName); + if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { + sourcesToContents[sourceName] = sourceContent; + smg.setSourceContent(sourceName, sourceContent); + } + }); -'use strict' + return smg.toJSON(); +}; -var base64 = require('base64-js') -var ieee754 = require('ieee754') +util.getTrueLoc = function(node, lines) { + // It's possible that node is newly-created (not parsed by Esprima), + // in which case it probably won't have a .loc property (or an + // .original property for that matter). That's fine; we'll just + // pretty-print it as usual. + if (!node.loc) { + return null; + } -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 + var result = { + start: node.loc.start, + end: node.loc.end + }; -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH + function include(node) { + expandLoc(result, node.loc); + } -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + // If the node has any comments, their locations might contribute to + // the true start/end positions of the node. + if (node.comments) { + node.comments.forEach(include); + } -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} + // If the node is an export declaration and its .declaration has any + // decorators, their locations might contribute to the true start/end + // positions of the export declaration node. + if (node.declaration && util.isExportDeclaration(node) && + node.declaration.decorators) { + node.declaration.decorators.forEach(include); + } -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 - } catch (e) { - return false + if (comparePos(result.start, result.end) < 0) { + // Trim leading whitespace. + result.start = copyPos(result.start); + lines.skipSpaces(result.start, false, true); + + if (comparePos(result.start, result.end) < 0) { + // Trim trailing whitespace, if the end location is not already the + // same as the start location. + result.end = copyPos(result.end); + lines.skipSpaces(result.end, true, true); + } } -} -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('Invalid typed array length') + return result; +}; + +function expandLoc(parentLoc, childLoc) { + if (parentLoc && childLoc) { + if (comparePos(childLoc.start, parentLoc.start) < 0) { + parentLoc.start = childLoc.start; + } + + if (comparePos(parentLoc.end, childLoc.end) < 0) { + parentLoc.end = childLoc.end; + } } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf } -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ +util.fixFaultyLocations = function(node, lines) { + var loc = node.loc; + if (loc) { + if (loc.start.line < 1) { + loc.start.line = 1; + } -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) + if (loc.end.line < 1) { + loc.end.line = 1; } - return allocUnsafe(arg) } - return from(arg, encodingOrOffset, length) -} -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} + if (node.type === "File") { + // Babylon returns File nodes whose .loc.{start,end} do not include + // leading or trailing whitespace. + loc.start = lines.firstPos(); + loc.end = lines.lastPos(); + } -Buffer.poolSize = 8192 // not used by this implementation + if (node.type === "TemplateLiteral") { + fixTemplateLiteral(node, lines); -function from (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + } else if (loc && node.decorators) { + // Expand the .loc of the node responsible for printing the decorators + // (here, the decorated node) so that it includes node.decorators. + node.decorators.forEach(function (decorator) { + expandLoc(loc, decorator.loc); + }); + + } else if (node.declaration && util.isExportDeclaration(node)) { + // Nullify .loc information for the child declaration so that we never + // try to reprint it without also reprinting the export declaration. + node.declaration.loc = null; + + // Expand the .loc of the node responsible for printing the decorators + // (here, the export declaration) so that it includes node.decorators. + var decorators = node.declaration.decorators; + if (decorators) { + decorators.forEach(function (decorator) { + expandLoc(loc, decorator.loc); + }); + } + + } else if ((n.MethodDefinition && n.MethodDefinition.check(node)) || + (n.Property.check(node) && (node.method || node.shorthand))) { + // If the node is a MethodDefinition or a .method or .shorthand + // Property, then the location information stored in + // node.value.loc is very likely untrustworthy (just the {body} + // part of a method, or nothing in the case of shorthand + // properties), so we null out that information to prevent + // accidental reuse of bogus source code during reprinting. + node.value.loc = null; + + if (n.FunctionExpression.check(node.value)) { + // FunctionExpression method values should be anonymous, + // because their .id fields are ignored anyway. + node.value.id = null; + } + + } else if (node.type === "ObjectTypeProperty") { + var loc = node.loc; + var end = loc && loc.end; + if (end) { + end = copyPos(end); + if (lines.prevPos(end) && + lines.charAt(end) === ",") { + // Some parsers accidentally include trailing commas in the + // .loc.end information for ObjectTypeProperty nodes. + if ((end = lines.skipSpaces(end, true, true))) { + loc.end = end; + } + } + } } +}; - if (isArrayBuffer(value)) { - return fromArrayBuffer(value, encodingOrOffset, length) +function fixTemplateLiteral(node, lines) { + assert.strictEqual(node.type, "TemplateLiteral"); + + if (node.quasis.length === 0) { + // If there are no quasi elements, then there is nothing to fix. + return; } - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) + // First we need to exclude the opening ` from the .loc of the first + // quasi element, in case the parser accidentally decided to include it. + var afterLeftBackTickPos = copyPos(node.loc.start); + assert.strictEqual(lines.charAt(afterLeftBackTickPos), "`"); + assert.ok(lines.nextPos(afterLeftBackTickPos)); + var firstQuasi = node.quasis[0]; + if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) { + firstQuasi.loc.start = afterLeftBackTickPos; } - return fromObject(value) -} + // Next we need to exclude the closing ` from the .loc of the last quasi + // element, in case the parser accidentally decided to include it. + var rightBackTickPos = copyPos(node.loc.end); + assert.ok(lines.prevPos(rightBackTickPos)); + assert.strictEqual(lines.charAt(rightBackTickPos), "`"); + var lastQuasi = node.quasis[node.quasis.length - 1]; + if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) { + lastQuasi.loc.end = rightBackTickPos; + } -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} + // Now we need to exclude ${ and } characters from the .loc's of all + // quasi elements, since some parsers accidentally include them. + node.expressions.forEach(function (expr, i) { + // Rewind from expr.loc.start over any whitespace and the ${ that + // precedes the expression. The position of the $ should be the same + // as the .loc.end of the preceding quasi element, but some parsers + // accidentally include the ${ in the .loc of the quasi element. + var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false); + if (lines.prevPos(dollarCurlyPos) && + lines.charAt(dollarCurlyPos) === "{" && + lines.prevPos(dollarCurlyPos) && + lines.charAt(dollarCurlyPos) === "$") { + var quasiBefore = node.quasis[i]; + if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) { + quasiBefore.loc.end = dollarCurlyPos; + } + } -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array + // Likewise, some parsers accidentally include the } that follows + // the expression in the .loc of the following quasi element. + var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false); + if (lines.charAt(rightCurlyPos) === "}") { + assert.ok(lines.nextPos(rightCurlyPos)); + // Now rightCurlyPos is technically the position just after the }. + var quasiAfter = node.quasis[i + 1]; + if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) { + quasiAfter.loc.start = rightCurlyPos; + } + } + }); +} -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') +util.isExportDeclaration = function (node) { + if (node) switch (node.type) { + case "ExportDeclaration": + case "ExportDefaultDeclaration": + case "ExportDefaultSpecifier": + case "DeclareExportDeclaration": + case "ExportNamedDeclaration": + case "ExportAllDeclaration": + return true; } -} -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) + return false; +}; + +util.getParentExportDeclaration = function (path) { + var parentNode = path.getParentNode(); + if (path.getName() === "declaration" && + util.isExportDeclaration(parentNode)) { + return parentNode; } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) + + return null; +}; + +util.isTrailingCommaEnabled = function(options, context) { + var trailingComma = options.trailingComma; + if (typeof trailingComma === "object") { + return !!trailingComma[context]; } - return createBuffer(size) -} + return !!trailingComma; +}; -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} +},{"./types":557,"assert":2,"source-map":572}],559:[function(require,module,exports){ +(function (process){ +var types = require("./lib/types"); +var parse = require("./lib/parser").parse; +var Printer = require("./lib/printer").Printer; -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) +function print(node, options) { + return new Printer(options).print(node); } -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) +function prettyPrint(node, options) { + return new Printer(options).printGenerically(node); } -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) +function run(transformer, options) { + return runFile(process.argv[2], transformer, options); +} - var actual = buf.write(string, encoding) +function runFile(path, transformer, options) { + require("fs").readFile(path, "utf-8", function(err, code) { + if (err) { + console.error(err); + return; + } - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } + runString(code, transformer, options); + }); +} - return buf +function defaultWriteback(output) { + process.stdout.write(output); } -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf +function runString(code, transformer, options) { + var writeback = options && options.writeback || defaultWriteback; + transformer(parse(code, options), function(node) { + writeback(print(node, options).code); + }); } -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } +Object.defineProperties(exports, { + /** + * Parse a string of code into an augmented syntax tree suitable for + * arbitrary modification and reprinting. + */ + parse: { + enumerable: true, + value: parse + }, - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + /** + * Traverse and potentially modify an abstract syntax tree using a + * convenient visitor syntax: + * + * recast.visit(ast, { + * names: [], + * visitIdentifier: function(path) { + * var node = path.value; + * this.visitor.names.push(node.name); + * this.traverse(path); + * } + * }); + */ + visit: { + enumerable: true, + value: types.visit + }, - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } + /** + * Reprint a modified syntax tree using as much of the original source + * code as possible. + */ + print: { + enumerable: true, + value: print + }, - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} + /** + * Print without attempting to reuse any original source code. + */ + prettyPrint: { + enumerable: false, + value: prettyPrint + }, -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) + /** + * Customized version of require("ast-types"). + */ + types: { + enumerable: false, + value: types + }, - if (buf.length === 0) { - return buf + /** + * Convenient command-line interface (see e.g. example/add-braces). + */ + run: { + enumerable: false, + value: run } +}); - obj.copy(buf, 0, 0, len) - return buf - } +}).call(this,require('_process')) +},{"./lib/parser":554,"./lib/printer":556,"./lib/types":557,"_process":15,"fs":4}],560:[function(require,module,exports){ +'use strict'; +var isFinite = require('is-finite'); - if (obj) { - if (isArrayBufferView(obj) || 'length' in obj) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } +module.exports = function (str, n) { + if (typeof str !== 'string') { + throw new TypeError('Expected `input` to be a string'); + } - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } - } + if (n < 0 || !isFinite(n)) { + throw new TypeError('Expected `count` to be a positive finite number'); + } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} + var ret = ''; -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} + do { + if (n & 1) { + ret += str; + } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} + str += str; + } while ((n >>= 1)); -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true -} + return ret; +}; -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } +},{"is-finite":323}],561:[function(require,module,exports){ +'use strict'; +module.exports = function (str) { + var isExtendedLengthPath = /^\\\\\?\\/.test(str); + var hasNonAscii = /[^\x00-\x80]+/.test(str); - if (a === b) return 0 + if (isExtendedLengthPath || hasNonAscii) { + return str; + } - var x = a.length - var y = b.length + return str.replace(/\\/g, '/'); +}; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } +},{}],562:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - if (x < y) return -1 - if (y < x) return 1 - return 0 -} +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = Object.create(null); } -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); } + return set; +}; - if (list.length === 0) { - return Buffer.alloc(0) - } +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; +}; - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = util.toSetString(aStr); + var isDuplicate = has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length + if (!isDuplicate) { + this._set[sStr] = idx; } - return buffer -} +}; -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (isArrayBufferView(string) || isArrayBuffer(string)) { - return string.byteLength +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; } - if (typeof string !== 'string') { - string = '' + string + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; } + throw new Error('No element indexed by ' + aIdx); +}; - var len = string.length - if (len === 0) return 0 +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength +exports.ArraySet = ArraySet; -function slowToString (encoding, start, end) { - var loweredCase = false +},{"./util":571}],563:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. +var base64 = require('./base64'); - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 - if (end === undefined || end > this.length) { - end = this.length - } +var VLQ_BASE_SHIFT = 5; - if (end <= 0) { - return '' - } +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; - if (end <= start) { - return '' - } +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; - if (!encoding) encoding = 'utf8' +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; - case 'ascii': - return asciiSlice(this, start, end) + var vlq = toVLQSigned(aValue); - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); - case 'base64': - return base64Slice(this, start, end) + return encoded; +}; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); } - } -} -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} +},{"./base64":564}],564:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; } - return this -} + throw new TypeError("Must be between 0 and 63: " + number); +}; -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} + var littleA = 97; // 'a' + var littleZ = 122; // 'z' -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} + var zero = 48; // '0' + var nine = 57; // '9' -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + var plus = 43; // '+' + var slash = 47; // '/' - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); } - if (thisStart >= thisEnd && start >= end) { - return 0 + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); } - if (thisStart >= thisEnd) { - return -1 + + // 62: + + if (charCode == plus) { + return 62; } - if (start >= end) { - return 1 + + // 63: / + if (charCode == slash) { + return 63; } - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 + // Invalid base64 digit. + return -1; +}; - if (this === target) return 0 +},{}],565:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; } } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } } +} - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; } - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; } - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + --index; } - throw new TypeError('val must be string, number or Buffer') + return index; +}; + +},{}],566:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; } + return this._array; +}; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } +exports.MappingList = MappingList; - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } +},{"./util":571}],567:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - return -1 -} +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; } -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); } -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} + swap(ary, pivotIndex, r); + var pivot = ary[r]; -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} + swap(ary, i + 1, j); + var q = i + 1; -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} + // (2) Recurse on each half. -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } } -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } +},{}],568:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') +function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); +} - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) +SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); +} - case 'ascii': - return asciiWrite(this, string, offset, length) +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + return this.__generatedMappings; + } +}); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); } - } -} -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) + return this.__originalMappings; } -} +}); -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); } - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + var mappings = []; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); -function hexSlice (buf, start, end) { - var len = buf.length + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} + mapping = this._originalMappings[++index]; + } + } + } -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} + return mappings; + }; -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end +exports.SourceMapConsumer = SourceMapConsumer; - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); } - if (end < start) end = start + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; } -/* - * Need to make sure that buffer isn't trying to write out of bounds. +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. - return val -} + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; - return val -} + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} + destOriginalMappings.push(destMapping); + } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + destGeneratedMappings.push(destMapping); + } -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} + quickSort(smc.__originalMappings, util.compareByOriginalPositions); -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + return smc; + }; - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } +}); - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; } -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); - return val -} + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + cachedSegments[str] = segment; + } - return val -} + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; - return offset + byteLength -} + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + if (index >= 0) { + var mapping = this._generatedMappings[index]; - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } - return offset + byteLength -} + return { + source: null, + line: null, + column: null, + name: null + }; + }; -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); - return offset + byteLength -} + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + if (index >= 0) { + var mapping = this._originalMappings[index]; - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - return offset + byteLength -} + return { + line: null, + column: null, + lastColumn: null + }; + }; -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + this._sources = new ArraySet(); + this._names = new ArraySet(); -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); } -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} +}); -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; - var len = end - start - var i +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } } - } else if (len < 1000) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] + if (nullOnMissing) { + return null; } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; - return len -} +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; } } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } + return { + line: null, + column: null + }; + }; - if (end <= start) { - return this - } +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); - if (!val) val = 0 + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : new Buffer(val, encoding) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } } - } - return this -} + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; -// HELPER FUNCTIONS -// ================ +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g +},{"./array-set":562,"./base64-vlq":563,"./binary-search":565,"./quick-sort":567,"./util":571}],569:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; } -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] +SourceMapGenerator.prototype._version = 3; - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); } - // valid lead - leadSurrogate = codePoint + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; - continue + if (mapping.name != null) { + newMapping.name = mapping.name; + } } - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); } + }); + return generator; + }; - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); } - } - return bytes -} + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } - return byteArray -} + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } -// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check -// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 -function isArrayBuffer (obj) { - return obj instanceof ArrayBuffer || - (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && - typeof obj.byteLength === 'number') -} + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } -// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` -function isArrayBufferView (obj) { - return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) -} + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } -function numberIsNaN (obj) { - return obj !== obj // eslint-disable-line no-self-compare -} + }, this); + this._sources = newSources; + this._names = newNames; -},{"base64-js":792,"ieee754":797}],794:[function(require,module,exports){ -(function (global){ -'use strict'; + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; -var buffer = require('buffer'); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); - } - return buf; -} -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - return new Buffer(size); -} -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); - } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); } - } + }; - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); -} -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); - } - return new SlowBuffer(size); -} +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"buffer":793}],795:[function(require,module,exports){ -(function (Buffer){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + result += next; + } -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + return result; + }; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + return map; + }; -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; +exports.SourceMapGenerator = SourceMapGenerator; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +},{"./array-set":562,"./base64-vlq":563,"./mapping-list":566,"./util":571}],570:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); -exports.isBuffer = Buffer.isBuffer; +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; -function objectToString(o) { - return Object.prototype.toString.call(o); -} +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":799}],796:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); } -module.exports = EventEmitter; -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); - if (!this._events) - this._events = {}; + return node; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); } } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; + }; - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); } - - return true; + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; }; -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); } } } +}; +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } return this; }; -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; - var fired = false; +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; - function g() { - this.removeListener(type, g); +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } - if (!fired) { - fired = true; - listener.apply(this, arguments); + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } - } + }; - g.listener = listener; - this.on(type, g); +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; - return this; +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; }; -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; +exports.SourceNode = SourceNode; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +},{"./source-map-generator":569,"./util":571}],571:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - if (!this._events || !this._events[type]) - return this; +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; - list = this._events[type]; - length = list.length; - position = -1; +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; } } + } + path = parts.join('/'); - if (position < 0) - return this; + if (path === '') { + path = isAbsolute ? '/' : '.'; + } - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; - if (this._events.removeListener) - this.emit('removeListener', type, listener); +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; } - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; } - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); } - listeners = this._events[type]; + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); } - delete this._events[type]; + return joined; +} +exports.join = join; - return this; +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + aRoot = aRoot.replace(/\/$/, ''); - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } -function isFunction(arg) { - return typeof arg === 'function'; -} + ++level; + } -function isNumber(arg) { - return typeof arg === 'number'; + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } +exports.relative = relative; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); -function isUndefined(arg) { - return arg === void 0; +function identity (s) { + return s; } -},{}],797:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } - i += d + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias +function isProtoString(s) { + if (!s) { + return false; } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + var length = s.length; - value = Math.abs(value) + if (length < 9 /* "__proto__".length */) { + return false; + } - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; } } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],798:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } + return true; } -},{}],799:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer +/** + * Comparator between two mappings where the original positions are compared. * - * @author Feross Aboukhadijeh - * @license MIT + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } -},{}],800:[function(require,module,exports){ -exports.endianness = function () { return 'LE' }; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } -exports.hostname = function () { - if (typeof location !== 'undefined') { - return location.hostname - } - else return ''; -}; + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } -exports.loadavg = function () { return [] }; + return mappingA.name - mappingB.name; +} +exports.compareByOriginalPositions = compareByOriginalPositions; -exports.uptime = function () { return 0 }; +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } -exports.freemem = function () { - return Number.MAX_VALUE; -}; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } -exports.totalmem = function () { - return Number.MAX_VALUE; -}; + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } -exports.cpus = function () { return [] }; + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } -exports.type = function () { return 'Browser' }; + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } -exports.release = function () { - if (typeof navigator !== 'undefined') { - return navigator.appVersion; - } - return ''; -}; + return mappingA.name - mappingB.name; +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; -exports.networkInterfaces -= exports.getNetworkInterfaces -= function () { return {} }; +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } -exports.arch = function () { return 'javascript' }; + if (aStr1 > aStr2) { + return 1; + } -exports.platform = function () { return 'browser' }; + return -1; +} -exports.tmpdir = exports.tmpDir = function () { - return '/tmp'; -}; +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } -exports.EOL = '\n'; + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } -},{}],801:[function(require,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; } - return parts; + return strcmp(mappingA.name, mappingB.name); } +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); +},{}],572:[function(require,module,exports){ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; + +},{"./lib/source-map-consumer":568,"./lib/source-map-generator":569,"./lib/source-node":570}],573:[function(require,module,exports){ +'use strict'; +var ansiRegex = require('ansi-regex')(); + +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; }; -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; +},{"ansi-regex":40}],574:[function(require,module,exports){ +(function (process){ +'use strict'; +var argv = process.argv; - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); +var terminator = argv.indexOf('--'); +var hasFlag = function (flag) { + flag = '--' + flag; + var pos = argv.indexOf(flag); + return pos !== -1 && (terminator !== -1 ? pos < terminator : true); +}; - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } +module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; + } + + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + return false; + } - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } + if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + return true; + } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) + if (process.stdout && !process.stdout.isTTY) { + return false; + } - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); + if (process.platform === 'win32') { + return true; + } - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; + if ('COLORTERM' in process.env) { + return true; + } -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; + if (process.env.TERM === 'dumb') { + return false; + } - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } + return false; +})(); - return (isAbsolute ? '/' : '') + path; -}; +}).call(this,require('_process')) +},{"_process":15}],575:[function(require,module,exports){ +(function (process){ +var Stream = require('stream') -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; +exports = module.exports = through +through.through = through +//create a readable writable stream. -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) - if (start > end) return []; - return arr.slice(start, end - start + 1); + stream.write = function (data) { + write.call(this, data) + return !stream.paused } - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) } } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) - if (!root && !dir) { - // No dirname whatsoever - return '.'; + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() } - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream } - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream } - return f; -}; + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') } - return res; + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream } -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; }).call(this,require('_process')) -},{"_process":803}],802:[function(require,module,exports){ -(function (process){ +},{"_process":15,"stream":30}],576:[function(require,module,exports){ 'use strict'; - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; -} else { - module.exports = process.nextTick; +module.exports = function toFastproperties(o) { + function Sub() {} + Sub.prototype = o; + var receiver = new Sub(); // create an instance + function ic() { return typeof receiver.foo; } // perform access + ic(); + ic(); + return o; + eval("o" + o); // ensure no dead code elimination } -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} +},{}],577:[function(require,module,exports){ +'use strict'; +module.exports = function (str) { + var tail = str.length; -}).call(this,require('_process')) -},{"_process":803}],803:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; + while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { + tail--; + } -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + return str.slice(0, tail); +}; -var cachedSetTimeout; -var cachedClearTimeout; +},{}],578:[function(require,module,exports){ +module.exports = { + buildPreset: function (context, opts) { + opts = opts !== undefined ? opts : {}; + var modules = opts.modules !== undefined ? opts.modules : true; + var loose = opts.loose !== undefined ? opts.loose : false; + var strict = opts.strict !== undefined ? opts.strict : true; + var globalRuntimeName = opts.globalRuntimeName !== undefined ? opts.globalRuntimeName : false; + + var plugins = [ + require("babel-plugin-syntax-async-functions"), + require("babel-plugin-syntax-async-generators"), + require("babel-plugin-transform-es2015-classes"), + require("babel-plugin-transform-es2015-arrow-functions"), + require("babel-plugin-transform-es2015-block-scoping"), + require("babel-plugin-transform-es2015-for-of"), + [require("regenerator-transform"), { globalRuntimeName: globalRuntimeName }] + ]; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + if (modules) { + plugins.push([require("babel-plugin-transform-es2015-modules-commonjs"), { loose: loose, strict: strict }]); } + return { + plugins: plugins, + }; + } +}; -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } +},{"babel-plugin-syntax-async-functions":116,"babel-plugin-syntax-async-generators":117,"babel-plugin-transform-es2015-arrow-functions":118,"babel-plugin-transform-es2015-block-scoping":119,"babel-plugin-transform-es2015-classes":121,"babel-plugin-transform-es2015-for-of":124,"babel-plugin-transform-es2015-modules-commonjs":125,"regenerator-transform":582}],579:[function(require,module,exports){ +'use strict'; +var undefined; // More compressible than void 0. +Object.defineProperty(exports, '__esModule', { value: true }); +var $Symbol = typeof Symbol === "function" ? Symbol : {}; +var iterator = $Symbol.iterator || "@@iterator"; +var asyncIterator = $Symbol.asyncIterator || "@@asyncIterator"; +var toStringTag = $Symbol.toStringTag || "@@toStringTag"; + +// Try/catch helper to minimize deoptimizations. Returns a completion +// record like context.tryEntries[i].completion. This interface could +// have been (and was previously) designed to take a closure to be +// invoked without arguments, but in all the cases we care about we +// already have an existing method we want to call, so there's no need +// to create a new function object. We can even get away with assuming +// the method takes exactly one argument, since that happens to be true +// in every case, so we don't have to touch the arguments object. The +// only additional allocation required is the completion record, which +// has a stable shape and so hopefully should be cheap to allocate. +function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } +function doneResult() { + return { value: undefined, done: true }; } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; +// Returning this object from the innerFn has the same effect as +// breaking out of the dispatch switch statement. +var ContinueSentinel = {}; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} +var ObjectPrototype = Object.prototype; +var hasOwn = ObjectPrototype.hasOwnProperty; -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); +function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iterator]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + if (typeof iterable.next === "function") { + return iterable; + } -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } -},{}],804:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + next.value = undefined; + next.done = true; -module.exports = Stream; + return next; + }; -var EE = require('events').EventEmitter; -var inherits = require('inherits'); + return next.next = next; + } + } -inherits(Stream, EE); -Stream.Readable = require('readable-stream/readable.js'); -Stream.Writable = require('readable-stream/writable.js'); -Stream.Duplex = require('readable-stream/duplex.js'); -Stream.Transform = require('readable-stream/transform.js'); -Stream.PassThrough = require('readable-stream/passthrough.js'); + // Return an iterator with no values. + return { next: doneResult }; +} -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; +var _IteratorPrototypePol; +// This is a polyfill for %IteratorPrototype% for environments that +// don't natively support it. +var IteratorPrototypePolyfill = (_IteratorPrototypePol = {}, _IteratorPrototypePol[iterator] = function () { + return this; +}, _IteratorPrototypePol); +var getProto = Object.getPrototypeOf; +var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. +var IteratorPrototype = NativeIteratorPrototype && NativeIteratorPrototype !== ObjectPrototype && hasOwn.call(NativeIteratorPrototype, iterator) ? NativeIteratorPrototype : IteratorPrototypePolyfill; -function Stream() { - EE.call(this); +// Helper for defining the .next, .throw, and .return methods of the +// Iterator interface in terms of a single ._invoke method. +function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + prototype[method] = function (arg) { + return this._invoke(method, arg); + }; + }); } -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } +var classCallCheck = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); } +}; - source.on('data', ondata); +function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } + if (1 in locs) { + entry.catchLoc = locs[1]; } - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + this.tryEntries.push(entry); +} - dest.end(); +function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; +} + +var Context = function () { + function Context(tryLocsList) { + classCallCheck(this, Context); + + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); } + Context.prototype.reset = function reset(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; - function onclose() { - if (didOnEnd) return; - didOnEnd = true; + this.method = "next"; + this.arg = undefined; - if (typeof dest.destroy === 'function') dest.destroy(); - } + this.tryEntries.forEach(resetTryEntry); - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } } - } + }; - source.on('error', onerror); - dest.on('error', onerror); + Context.prototype.stop = function stop() { + this.done = true; - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } - source.removeListener('end', onend); - source.removeListener('close', onclose); + return this.rval; + }; - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + Context.prototype.dispatchException = function dispatchException(exception) { + if (this.done) { + throw exception; + } - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; - dest.removeListener('close', cleanup); - } + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } - source.on('end', cleanup); - source.on('close', cleanup); + return !!caught; + } - dest.on('close', cleanup); + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; - dest.emit('pipe', source); + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); -},{"events":796,"inherits":798,"readable-stream/duplex.js":806,"readable-stream/passthrough.js":813,"readable-stream/readable.js":814,"readable-stream/transform.js":815,"readable-stream/writable.js":816}],805:[function(require,module,exports){ -var toString = {}.toString; + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }; -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + Context.prototype.abrupt = function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } -},{}],806:[function(require,module,exports){ -module.exports = require("./lib/_stream_duplex.js") + if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } -},{"./lib/_stream_duplex.js":807}],807:[function(require,module,exports){ -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; -'use strict'; + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } -/**/ + return this.complete(record); + }; -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + Context.prototype.complete = function complete(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } -module.exports = Duplex; + if (record.type === "break" || record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } -/**/ -var processNextTick = require('process-nextick-args'); -/**/ + return ContinueSentinel; + }; -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + Context.prototype.finish = function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }; -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); + Context.prototype.catch = function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } -util.inherits(Duplex, Readable); + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }; -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} + Context.prototype.delegateYield = function delegateYield(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } - Readable.call(this, options); - Writable.call(this, options); + return ContinueSentinel; + }; - if (options && options.readable === false) this.readable = false; + return Context; +}(); - if (options && options.writable === false) this.writable = false; +var GenStateSuspendedStart = "suspendedStart"; +var GenStateSuspendedYield = "suspendedYield"; +var GenStateExecuting = "executing"; +var GenStateCompleted = "completed"; + +// Dummy constructor functions that we use as the .constructor and +// .constructor.prototype properties for functions that return Generator +// objects. For full spec compliance, you may wish to configure your +// minifier not to mangle the names of these two functions. +function Generator() {} +function GeneratorFunction() {} +function GeneratorFunctionPrototype() {} + +var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + +GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; +GeneratorFunctionPrototype.constructor = GeneratorFunction; +GeneratorFunctionPrototype[toStringTag] = GeneratorFunction.displayName = "GeneratorFunction"; + +// Define Generator.prototype.{next,throw,return} in terms of the +// unified ._invoke helper method. +/*#__PURE__*/defineIteratorMethods(Gp); + +Gp[toStringTag] = "Generator"; + +// A Generator should always return itself as the iterator object when the +// @@iterator function is called on it. Some browsers' implementations of the +// iterator prototype chain incorrectly implement this, causing the Generator +// object to not be returned from this call. This ensures that doesn't happen. +// See https://github.com/facebook/regenerator/issues/274 for more details. +Gp[iterator] = function () { + return this; +}; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; +Gp.toString = function () { + return "[object Generator]"; +}; - this.once('end', onend); +function isGeneratorFunction(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" : false; } -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); +function mark(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTag in genFun)) { + genFun[toStringTag] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; } -function onEndNT(self) { - self.end(); -} +function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; } -},{"./_stream_readable":809,"./_stream_writable":811,"core-util-is":795,"inherits":798,"process-nextick-args":802}],808:[function(require,module,exports){ -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; +function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; -module.exports = PassThrough; + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } -var Transform = require('./_stream_transform'); + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } -util.inherits(PassThrough, Transform); + context.method = method; + context.arg = arg; -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } - Transform.call(this, options); -} + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":810,"core-util-is":795,"inherits":798}],809:[function(require,module,exports){ -(function (process){ -'use strict'; + context.dispatchException(context.arg); + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } -module.exports = Readable; + state = GenStateExecuting; -/**/ -var processNextTick = require('process-nextick-args'); -/**/ + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done ? GenStateCompleted : GenStateSuspendedYield; -/**/ -var isArray = require('isarray'); -/**/ + if (record.arg === ContinueSentinel) { + continue; + } -/**/ -var Duplex; -/**/ + return { + value: record.arg, + done: context.done + }; + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; +} -Readable.ReadableState = ReadableState; +// Call delegate.iterator[context.method](context.arg) and handle the +// result, either by returning a { value, done } result from the +// delegate iterator, or by modifying context.method and context.arg, +// setting context.delegate to null, and returning the ContinueSentinel. +function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; -/**/ -var EE = require('events').EventEmitter; + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } -/**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; + context.method = "throw"; + context.arg = new TypeError("The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; } -})(); -/**/ -var Buffer = require('buffer').Buffer; -/**/ -var bufferShim = require('buffer-shims'); -/**/ + var record = tryCatch(method, delegate.iterator, context.arg); -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ + var info = record.arg; -var BufferList = require('./internal/streams/BufferList'); -var StringDecoder; + if (!info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } -util.inherits(Readable, Stream); + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + // Re-yield the result returned by the delegate method. + return info; } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; } -function ReadableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); +function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && typeof value === "object" && hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }); + } - options = options || {}; + return Promise.resolve(value).then(function (unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; +} + +/*#__PURE__*/defineIteratorMethods(AsyncIterator.prototype); +AsyncIterator.prototype[asyncIterator] = function () { + return this; +}; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +// Note that simple async functions are implemented on top of +// AsyncIterator objects; they just return a Promise for the value of +// the final result produced by the iterator. +function async(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + return isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); +} - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; +function keys(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; +} - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; +// Within the body of any async function, `await x` is transformed to +// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test +// `hasOwn.call(value, "__await")` to determine if the yielded value is +// meant to be awaited. +var awrap = function (arg) { + return { __await: arg }; +}; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +exports.awrap = awrap; +exports.isGeneratorFunction = isGeneratorFunction; +exports.mark = mark; +exports.wrap = wrap; +exports.AsyncIterator = AsyncIterator; +exports.async = async; +exports.keys = keys; +exports.values = values; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; +},{}],580:[function(require,module,exports){ +"use strict"; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +var _stringify = require("babel-runtime/core-js/json/stringify"); - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +var _stringify2 = _interopRequireDefault(_stringify); - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} +var _assert = require("assert"); -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); +var _assert2 = _interopRequireDefault(_assert); - if (!(this instanceof Readable)) return new Readable(options); +var _babelTypes = require("babel-types"); - this._readableState = new ReadableState(options, this); +var t = _interopRequireWildcard(_babelTypes); - // legacy - this.readable = true; +var _leap = require("./leap"); - if (options && typeof options.read === 'function') this._read = options.read; +var leap = _interopRequireWildcard(_leap); - Stream.call(this); -} +var _meta = require("./meta"); -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; +var meta = _interopRequireWildcard(_meta); - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ''; - } - } +var _util = require("./util"); - return readableAddChunk(this, state, chunk, encoding, false); -}; +var util = _interopRequireWildcard(_util); -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } +var hasOwn = Object.prototype.hasOwnProperty; /** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - if (!addToFront) state.reading = false; +function Emitter(contextId, visitorState) { + _assert2.default.ok(this instanceof Emitter); + t.assertIdentifier(contextId); - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + this.visitorState = visitorState; - if (state.needReadable) emitReadable(stream); - } - } + // Used to generate unique temporary names. + this.nextTempId = 0; - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } + // In order to make sure the context object does not collide with + // anything in the local scope, we might have to rename it, so we + // refer to it symbolically instead of just assuming that it will be + // called "context". + this.contextId = contextId; - return needMoreData(state); -} + // An append-only list of Statements that grows each time this.emit is + // called. + this.listing = []; -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + // A sparse array whose keys correspond to locations in this.listing + // that have been marked as branch/jump targets. + this.marked = [true]; + + // The last location will be marked when this.getDispatchLoop is + // called. + this.finalLoc = loc(); + + // A list of all leap.TryEntry statements emitted. + this.tryEntries = []; + + // Each time we evaluate the body of a loop, we tell this.leapManager + // to enter a nested loop context that determines the meaning of break + // and continue statements therein. + this.leapManager = new leap.LeapManager(this); } -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +var Ep = Emitter.prototype; +exports.Emitter = Emitter; -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; +// Offsets into this.listing that could be used as targets for branches or +// jumps are represented as numeric Literal nodes. This representation has +// the amazingly convenient benefit of allowing the exact value of the +// location to be determined at any time, even after generating code that +// refers to the location. +function loc() { + return t.numericLiteral(-1); } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; +// Sets the exact value of the given location to the offset of the next +// Statement emitted. +Ep.mark = function (loc) { + t.assertLiteral(loc); + var index = this.listing.length; + if (loc.value === -1) { + loc.value = index; + } else { + // Locations can be marked redundantly, but their values cannot change + // once set the first time. + _assert2.default.strictEqual(loc.value, index); } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; + this.marked[index] = true; + return loc; +}; + +Ep.emit = function (node) { + if (t.isExpression(node)) { + node = t.expressionStatement(node); } - return state.length; -} -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + t.assertStatement(node); + this.listing.push(node); +}; - if (n !== 0) state.emittedReadable = false; +// Shorthand for emitting assignment statements. This will come in handy +// for assignments to temporary variables. +Ep.emitAssign = function (lhs, rhs) { + this.emit(this.assign(lhs, rhs)); + return lhs; +}; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +// Shorthand for an assignment statement. +Ep.assign = function (lhs, rhs) { + return t.expressionStatement(t.assignmentExpression("=", lhs, rhs)); +}; - n = howMuchToRead(n, state); +// Convenience function for generating expressions like context.next, +// context.sent, and context.rval. +Ep.contextProperty = function (name, computed) { + return t.memberExpression(this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed); +}; - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; +// Shorthand for setting context.rval and jumping to `context.stop()`. +Ep.stop = function (rval) { + if (rval) { + this.setReturnValue(rval); } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + this.jump(this.finalLoc); +}; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +Ep.setReturnValue = function (valuePath) { + t.assertExpression(valuePath.value); - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + this.emitAssign(this.contextProperty("rval"), this.explodeExpression(valuePath)); +}; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +Ep.clearPendingException = function (tryLoc, assignee) { + t.assertLiteral(tryLoc); - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + var catchCall = t.callExpression(this.contextProperty("catch", true), [tryLoc]); - if (ret === null) { - state.needReadable = true; - n = 0; + if (assignee) { + this.emitAssign(assignee, catchCall); } else { - state.length -= n; + this.emit(catchCall); } +}; - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +// Emits code for an unconditional jump to the given location, even if the +// exact value of the location is not yet known. +Ep.jump = function (toLoc) { + this.emitAssign(this.contextProperty("next"), toLoc); + this.emit(t.breakStatement()); +}; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); +// Conditional jump. +Ep.jumpIf = function (test, toLoc) { + t.assertExpression(test); + t.assertLiteral(toLoc); + + this.emit(t.ifStatement(test, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); +}; + +// Conditional jump, with the condition negated. +Ep.jumpIfNot = function (test, toLoc) { + t.assertExpression(test); + t.assertLiteral(toLoc); + + var negatedTest = void 0; + if (t.isUnaryExpression(test) && test.operator === "!") { + // Avoid double negation. + negatedTest = test.argument; + } else { + negatedTest = t.unaryExpression("!", test); } - if (ret !== null) this.emit('data', ret); + this.emit(t.ifStatement(negatedTest, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); +}; - return ret; +// Returns a unique MemberExpression that can be used to store and +// retrieve temporary values. Since the object of the member expression is +// the context object, which is presumed to coexist peacefully with all +// other local variables, and since we just increment `nextTempId` +// monotonically, uniqueness is assured. +Ep.makeTempVar = function () { + return this.contextProperty("t" + this.nextTempId++); }; -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} +Ep.getContextFunction = function (id) { + return t.functionExpression(id || null /*Anonymous*/ + , [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! + false // Nor an expression. + ); +}; -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; +// Turns this.listing into a loop of the form +// +// while (1) switch (context.next) { +// case 0: +// ... +// case n: +// return context.stop(); +// } +// +// Each marked location in this.listing will correspond to one generated +// case statement. +Ep.getDispatchLoop = function () { + var self = this; + var cases = []; + var current = void 0; + + // If we encounter a break, continue, or return statement in a switch + // case, we can skip the rest of the statements until the next case. + var alreadyEnded = false; + + self.listing.forEach(function (stmt, i) { + if (self.marked.hasOwnProperty(i)) { + cases.push(t.switchCase(t.numericLiteral(i), current = [])); + alreadyEnded = false; } - } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + if (!alreadyEnded) { + current.push(stmt); + if (t.isCompletionStatement(stmt)) alreadyEnded = true; + } + }); -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); - } -} + // Now that we know how many statements there will be in this.listing, + // we can finally resolve this.finalLoc.value. + this.finalLoc.value = this.listing.length; -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} + cases.push(t.switchCase(this.finalLoc, [ + // Intentionally fall through to the "end" case... + ]), -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} + // So that the runtime can jump to the final location without having + // to know its offset, we provide the "end" case as a synonym. + t.switchCase(t.stringLiteral("end"), [ + // This will check/clear both context.thrown and context.rval. + t.returnStatement(t.callExpression(this.contextProperty("stop"), []))])); -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; + return t.whileStatement(t.numericLiteral(1), t.switchStatement(t.assignmentExpression("=", this.contextProperty("prev"), this.contextProperty("next")), cases)); +}; + +Ep.getTryLocsList = function () { + if (this.tryEntries.length === 0) { + // To avoid adding a needless [] to the majority of runtime.wrap + // argument lists, force the caller to handle this case specially. + return null; } - state.readingMore = false; -} -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); + var lastLocValue = 0; + + return t.arrayExpression(this.tryEntries.map(function (tryEntry) { + var thisLocValue = tryEntry.firstLoc.value; + _assert2.default.ok(thisLocValue >= lastLocValue, "try entries out of order"); + lastLocValue = thisLocValue; + + var ce = tryEntry.catchEntry; + var fe = tryEntry.finallyEntry; + + var locs = [tryEntry.firstLoc, + // The null here makes a hole in the array. + ce ? ce.firstLoc : null]; + + if (fe) { + locs[2] = fe.firstLoc; + locs[3] = fe.afterLoc; + } + + return t.arrayExpression(locs); + })); }; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +// All side effects must be realized in order. - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); +// If any subexpression harbors a leap, all subexpressions must be +// neutered of side effects. - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +// No destructive modification of AST nodes. - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); +Ep.explode = function (path, ignoreResult) { + var node = path.node; + var self = this; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } + t.assertNode(node); - function onend() { - debug('onend'); - dest.end(); - } + if (t.isDeclaration(node)) throw getDeclError(node); - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); + if (t.isStatement(node)) return self.explodeStatement(path); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); + if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); - cleanedUp = true; + switch (node.type) { + case "Program": + return path.get("body").map(self.explodeStatement, self); - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + case "VariableDeclarator": + throw getDeclError(node); - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } + // These node types should be handled by their parent nodes + // (ObjectExpression, SwitchStatement, and TryStatement, respectively). + case "Property": + case "SwitchCase": + case "CatchClause": + throw new Error(node.type + " nodes should be handled by their parents"); - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + default: + throw new Error("unknown Node of type " + (0, _stringify2.default)(node.type)); } +}; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +function getDeclError(node) { + return new Error("all declarations should have been transformed into " + "assignments before the Exploder began its work: " + (0, _stringify2.default)(node)); +} - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); +Ep.explodeStatement = function (path, labelId) { + var stmt = path.node; + var self = this; + var before = void 0, + after = void 0, + head = void 0; + + t.assertStatement(stmt); + + if (labelId) { + t.assertIdentifier(labelId); + } else { + labelId = null; } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); + + // Explode BlockStatement nodes even if they do not contain a yield, + // because we don't want or need the curly braces. + if (t.isBlockStatement(stmt)) { + path.get("body").forEach(function (path) { + self.explodeStatement(path); + }); + return; } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); + if (!meta.containsLeap(stmt)) { + // Technically we should be able to avoid emitting the statement + // altogether if !meta.hasSideEffects(stmt), but that leads to + // confusing generated code (for instance, `while (true) {}` just + // disappears) and is probably a more appropriate job for a dedicated + // dead code elimination pass. + self.emit(stmt); + return; } - // tell the dest that it's being piped to - dest.emit('pipe', src); + switch (stmt.type) { + case "ExpressionStatement": + self.explodeExpression(path.get("expression"), true); + break; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + case "LabeledStatement": + after = loc(); - return dest; -}; + // Did you know you can break from any labeled block statement or + // control structure? Well, you can! Note: when a labeled loop is + // encountered, the leap.LabeledEntry created here will immediately + // enclose a leap.LoopEntry on the leap manager's stack, and both + // entries will have the same label. Though this works just fine, it + // may seem a bit redundant. In theory, we could check here to + // determine if stmt knows how to handle its own label; for example, + // stmt happens to be a WhileStatement and so we know it's going to + // establish its own LoopEntry when we explode it (below). Then this + // LabeledEntry would be unnecessary. Alternatively, we might be + // tempted not to pass stmt.label down into self.explodeStatement, + // because we've handled the label here, but that's a mistake because + // labeled loops may contain labeled continue statements, which is not + // something we can handle in this generic case. All in all, I think a + // little redundancy greatly simplifies the logic of this case, since + // it's clear that we handle all possible LabeledStatements correctly + // here, regardless of whether they interact with the leap manager + // themselves. Also remember that labels and break/continue-to-label + // statements are rare, and all of this logic happens at transform + // time, so it has no additional runtime cost. + self.leapManager.withEntry(new leap.LabeledEntry(after, stmt.label), function () { + self.explodeStatement(path.get("body"), stmt.label); + }); -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} + self.mark(after); -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; + break; + + case "WhileStatement": + before = loc(); + after = loc(); + + self.mark(before); + self.jumpIfNot(self.explodeExpression(path.get("test")), after); + self.leapManager.withEntry(new leap.LoopEntry(after, before, labelId), function () { + self.explodeStatement(path.get("body")); + }); + self.jump(before); + self.mark(after); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + break; - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + case "DoWhileStatement": + var first = loc(); + var test = loc(); + after = loc(); - if (!dest) dest = state.pipes; + self.mark(first); + self.leapManager.withEntry(new leap.LoopEntry(after, test, labelId), function () { + self.explode(path.get("body")); + }); + self.mark(test); + self.jumpIf(self.explodeExpression(path.get("test")), first); + self.mark(after); - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } + break; - // slow case. multiple pipe destinations. + case "ForStatement": + head = loc(); + var update = loc(); + after = loc(); - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + if (stmt.init) { + // We pass true here to indicate that if stmt.init is an expression + // then we do not care about its result. + self.explode(path.get("init"), true); + } - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); - }return this; - } + self.mark(head); - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + if (stmt.test) { + self.jumpIfNot(self.explodeExpression(path.get("test")), after); + } else { + // No test means continue unconditionally. + } - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + self.leapManager.withEntry(new leap.LoopEntry(after, update, labelId), function () { + self.explodeStatement(path.get("body")); + }); - dest.emit('unpipe', this); + self.mark(update); - return this; -}; + if (stmt.update) { + // We pass true here to indicate that if stmt.update is an + // expression then we do not care about its result. + self.explode(path.get("update"), true); + } -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + self.jump(head); - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } + self.mark(after); - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; + break; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} + case "TypeCastExpression": + return self.explodeExpression(path.get("expression")); -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; + case "ForInStatement": + head = loc(); + after = loc(); -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} + var keyIterNextFn = self.makeTempVar(); + self.emitAssign(keyIterNextFn, t.callExpression(util.runtimeProperty(self.visitorState, "keys"), [self.explodeExpression(path.get("right"))])); -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } + self.mark(head); - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + var keyInfoTmpVar = self.makeTempVar(); + self.jumpIf(t.memberExpression(t.assignmentExpression("=", keyInfoTmpVar, t.callExpression(keyIterNextFn, [])), t.identifier("done"), false), after); -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; + self.emitAssign(stmt.left, t.memberExpression(keyInfoTmpVar, t.identifier("value"), false)); -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} + self.leapManager.withEntry(new leap.LoopEntry(after, head, labelId), function () { + self.explodeStatement(path.get("body")); + }); -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; + self.jump(head); - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + self.mark(after); - self.push(null); - }); + break; - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + case "BreakStatement": + self.emitAbruptCompletion({ + type: "break", + target: self.leapManager.getBreakLoc(stmt.label) + }); - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + break; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); + case "ContinueStatement": + self.emitAbruptCompletion({ + type: "continue", + target: self.leapManager.getContinueLoc(stmt.label) + }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } + break; - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); + case "SwitchStatement": + // Always save the discriminant into a temporary variable in case the + // test expressions overwrite values like context.sent. + var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + after = loc(); + var defaultLoc = loc(); + var condition = defaultLoc; + var caseLocs = []; - return self; -}; + // If there are no cases, .cases might be undefined. + var cases = stmt.cases || []; -// exposed for testing purposes only. -Readable._fromList = fromList; + for (var i = cases.length - 1; i >= 0; --i) { + var c = cases[i]; + t.assertSwitchCase(c); -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + if (c.test) { + condition = t.conditionalExpression(t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition); + } else { + caseLocs[i] = defaultLoc; + } + } - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + var discriminant = path.get("discriminant"); + util.replaceWithOrRemove(discriminant, condition); + self.jump(self.explodeExpression(discriminant)); - return ret; -} + self.leapManager.withEntry(new leap.SwitchEntry(after), function () { + path.get("cases").forEach(function (casePath) { + var i = casePath.key; + self.mark(caseLocs[i]); -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} + casePath.get("consequent").forEach(function (path) { + self.explodeStatement(path); + }); + }); + }); -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); + self.mark(after); + if (defaultLoc.value === -1) { + self.mark(defaultLoc); + _assert2.default.strictEqual(after.value, defaultLoc.value); } - break; - } - ++c; - } - list.length -= c; - return ret; -} -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + case "IfStatement": + var elseLoc = stmt.alternate && loc(); + after = loc(); -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} + self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -}).call(this,require('_process')) -},{"./_stream_duplex":807,"./internal/streams/BufferList":812,"_process":803,"buffer":793,"buffer-shims":794,"core-util-is":795,"events":796,"inherits":798,"isarray":805,"process-nextick-args":802,"string_decoder/":817,"util":789}],810:[function(require,module,exports){ -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + self.explodeStatement(path.get("consequent")); -'use strict'; + if (elseLoc) { + self.jump(after); + self.mark(elseLoc); + self.explodeStatement(path.get("alternate")); + } -module.exports = Transform; + self.mark(after); -var Duplex = require('./_stream_duplex'); + break; -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + case "ReturnStatement": + self.emitAbruptCompletion({ + type: "return", + value: self.explodeExpression(path.get("argument")) + }); -util.inherits(Transform, Duplex); + break; -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; + case "WithStatement": + throw new Error("WithStatement not supported in generator functions."); - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} + case "TryStatement": + after = loc(); -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + var handler = stmt.handler; - var cb = ts.writecb; + var catchLoc = handler && loc(); + var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + var finallyLoc = stmt.finalizer && loc(); + var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); - ts.writechunk = null; - ts.writecb = null; + var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); - if (data !== null && data !== undefined) stream.push(data); + self.tryEntries.push(tryEntry); + self.updateContextPrevLoc(tryEntry.firstLoc); - cb(er); + self.leapManager.withEntry(tryEntry, function () { + self.explodeStatement(path.get("block")); - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} + if (catchLoc) { + if (finallyLoc) { + // If we have both a catch block and a finally block, then + // because we emit the catch block first, we need to jump over + // it to the finally block. + self.jump(finallyLoc); + } else { + // If there is no finally block, then we need to jump over the + // catch block to the fall-through location. + self.jump(after); + } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); + self.updateContextPrevLoc(self.mark(catchLoc)); - Duplex.call(this, options); + var bodyPath = path.get("handler.body"); + var safeParam = self.makeTempVar(); + self.clearPendingException(tryEntry.firstLoc, safeParam); - this._transformState = new TransformState(this); + bodyPath.traverse(catchParamVisitor, { + safeParam: safeParam, + catchParamName: handler.param.name + }); - var stream = this; + self.leapManager.withEntry(catchEntry, function () { + self.explodeStatement(bodyPath); + }); + } - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + if (finallyLoc) { + self.updateContextPrevLoc(self.mark(finallyLoc)); - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; + self.leapManager.withEntry(finallyEntry, function () { + self.explodeStatement(path.get("finalizer")); + }); - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; + self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); + } + }); - if (typeof options.flush === 'function') this._flush = options.flush; - } + self.mark(after); - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); -} + break; -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; + case "ThrowStatement": + self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; + break; -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + default: + throw new Error("unknown Statement of type " + (0, _stringify2.default)(stmt.type)); } }; -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; +var catchParamVisitor = { + Identifier: function Identifier(path, state) { + if (path.node.name === state.catchParamName && util.isReference(path)) { + util.replaceWithOrRemove(path, state.safeParam); + } + }, - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + Scope: function Scope(path, state) { + if (path.scope.hasOwnBinding(state.catchParamName)) { + // Don't descend into nested scopes that shadow the catch + // parameter with their own declarations. + path.skip(); + } } }; -function done(stream, er, data) { - if (er) return stream.emit('error', er); +Ep.emitAbruptCompletion = function (record) { + if (!isValidCompletion(record)) { + _assert2.default.ok(false, "invalid completion record: " + (0, _stringify2.default)(record)); + } - if (data !== null && data !== undefined) stream.push(data); + _assert2.default.notStrictEqual(record.type, "normal", "normal completions are not abrupt"); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + var abruptArgs = [t.stringLiteral(record.type)]; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (record.type === "break" || record.type === "continue") { + t.assertLiteral(record.target); + abruptArgs[1] = record.target; + } else if (record.type === "return" || record.type === "throw") { + if (record.value) { + t.assertExpression(record.value); + abruptArgs[1] = record.value; + } + } - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); +}; - return stream.push(null); -} -},{"./_stream_duplex":807,"core-util-is":795,"inherits":798}],811:[function(require,module,exports){ -(function (process){ -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +function isValidCompletion(record) { + var type = record.type; -'use strict'; + if (type === "normal") { + return !hasOwn.call(record, "target"); + } -module.exports = Writable; + if (type === "break" || type === "continue") { + return !hasOwn.call(record, "value") && t.isLiteral(record.target); + } -/**/ -var processNextTick = require('process-nextick-args'); -/**/ + if (type === "return" || type === "throw") { + return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); + } -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ + return false; +} -/**/ -var Duplex; -/**/ +// Not all offsets into emitter.listing are potential jump targets. For +// example, execution typically falls into the beginning of a try block +// without jumping directly there. This method returns the current offset +// without marking it, so that a switch case will not necessarily be +// generated for this offset (I say "not necessarily" because the same +// location might end up being marked in the process of emitting other +// statements). There's no logical harm in marking such locations as jump +// targets, but minimizing the number of switch cases keeps the generated +// code shorter. +Ep.getUnmarkedCurrentLoc = function () { + return t.numericLiteral(this.listing.length); +}; -Writable.WritableState = WritableState; +// The context.prev property takes the value of context.next whenever we +// evaluate the switch statement discriminant, which is generally good +// enough for tracking the last location we jumped to, but sometimes +// context.prev needs to be more precise, such as when we fall +// successfully out of a try block and into a finally block without +// jumping. This method exists to update context.prev to the freshest +// available location. If we were implementing a full interpreter, we +// would know the location of the current instruction with complete +// precision at all times, but we don't have that luxury here, as it would +// be costly and verbose to set context.prev before every statement. +Ep.updateContextPrevLoc = function (loc) { + if (loc) { + t.assertLiteral(loc); -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ + if (loc.value === -1) { + // If an uninitialized location literal was passed in, set its value + // to the current this.listing.length. + loc.value = this.listing.length; + } else { + // Otherwise assert that the location matches the current offset. + _assert2.default.strictEqual(loc.value, this.listing.length); + } + } else { + loc = this.getUnmarkedCurrentLoc(); + } -/**/ -var internalUtil = { - deprecate: require('util-deprecate') + // Make sure context.prev is up to date in case we fell into this try + // statement without jumping to it. TODO Consider avoiding this + // assignment when we know control must have jumped here. + this.emitAssign(this.contextProperty("prev"), loc); }; -/**/ -/**/ -var Stream; -(function () { - try { - Stream = require('st' + 'ream'); - } catch (_) {} finally { - if (!Stream) Stream = require('events').EventEmitter; +Ep.explodeExpression = function (path, ignoreResult) { + var expr = path.node; + if (expr) { + t.assertExpression(expr); + } else { + return expr; } -})(); -/**/ - -var Buffer = require('buffer').Buffer; -/**/ -var bufferShim = require('buffer-shims'); -/**/ -util.inherits(Writable, Stream); + var self = this; + var result = void 0; // Used optionally by several cases below. + var after = void 0; -function nop() {} + function finish(expr) { + t.assertExpression(expr); + if (ignoreResult) { + self.emit(expr); + } else { + return expr; + } + } -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} + // If the expression does not contain a leap, then we either emit the + // expression as a standalone statement or return it whole. + if (!meta.containsLeap(expr)) { + return finish(expr); + } -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); + // If any child contains a leap (such as a yield or labeled continue or + // break statement), then any sibling subexpressions will almost + // certainly have to be exploded in order to maintain the order of their + // side effects relative to the leaping child(ren). + var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); - options = options || {}; + // In order to save the rest of explodeExpression from a combinatorial + // trainwreck of special cases, explodeViaTempVar is responsible for + // deciding when a subexpression needs to be "exploded," which is my + // very technical term for emitting the subexpression as an assignment + // to a temporary variable and the substituting the temporary variable + // for the original subexpression. Think of exploded view diagrams, not + // Michael Bay movies. The point of exploding subexpressions is to + // control the precise order in which the generated code realizes the + // side effects of those subexpressions. + function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { + _assert2.default.ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + var result = self.explodeExpression(childPath, ignoreChildResult); - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + if (ignoreChildResult) { + // Side effects already emitted above. - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + } else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { + // If tempVar was provided, then the result will always be assigned + // to it, even if the result does not otherwise need to be assigned + // to a temporary variable. When no tempVar is provided, we have + // the flexibility to decide whether a temporary variable is really + // necessary. Unfortunately, in general, a temporary variable is + // required whenever any child contains a yield expression, since it + // is difficult to prove (at all, let alone efficiently) whether + // this result would evaluate to the same value before and after the + // yield (see #206). One narrow case where we can prove it doesn't + // matter (and thus we do not need a temporary variable) is when the + // result in question is a Literal value. + result = self.emitAssign(tempVar || self.makeTempVar(), result); + } + return result; + } - // cast to ints. - this.highWaterMark = ~ ~this.highWaterMark; + // If ignoreResult is true, then we must take full responsibility for + // emitting the expression with all its side effects, and we should not + // return a result. - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + switch (expr.type) { + case "MemberExpression": + return finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)); - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + case "CallExpression": + var calleePath = path.get("callee"); + var argsPath = path.get("arguments"); - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + var newCallee = void 0; + var newArgs = []; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + var hasLeapingArgs = false; + argsPath.forEach(function (argPath) { + hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); + }); - // a flag to see when we're in the middle of a write. - this.writing = false; + if (t.isMemberExpression(calleePath.node)) { + if (hasLeapingArgs) { + // If the arguments of the CallExpression contained any yield + // expressions, then we need to be sure to evaluate the callee + // before evaluating the arguments, but if the callee was a member + // expression, then we must be careful that the object of the + // member expression still gets bound to `this` for the call. - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var newObject = explodeViaTempVar( + // Assign the exploded callee.object expression to a temporary + // variable so that we can use it twice without reevaluating it. + self.makeTempVar(), calleePath.get("object")); - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + newArgs.unshift(newObject); - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + newCallee = t.memberExpression(t.memberExpression(newObject, newProperty, calleePath.node.computed), t.identifier("call"), false); + } else { + newCallee = self.explodeExpression(calleePath); + } + } else { + newCallee = explodeViaTempVar(null, calleePath); - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + if (t.isMemberExpression(newCallee)) { + // If the callee was not previously a MemberExpression, then the + // CallExpression was "unqualified," meaning its `this` object + // should be the global object. If the exploded expression has + // become a MemberExpression (e.g. a context property, probably a + // temporary variable), then we need to force it to be unqualified + // by using the (0, object.property)(...) trick; otherwise, it + // will receive the object of the MemberExpression as its `this` + // object. + newCallee = t.sequenceExpression([t.numericLiteral(0), newCallee]); + } + } - // the amount that is being written when _write is called. - this.writelen = 0; + argsPath.forEach(function (argPath) { + newArgs.push(explodeViaTempVar(null, argPath)); + }); - this.bufferedRequest = null; - this.lastBufferedRequest = null; + return finish(t.callExpression(newCallee, newArgs)); - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + case "NewExpression": + return finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { + return explodeViaTempVar(null, argPath); + }))); - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + case "ObjectExpression": + return finish(t.objectExpression(path.get("properties").map(function (propPath) { + if (propPath.isObjectProperty()) { + return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); + } else { + return propPath.node; + } + }))); - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + case "ArrayExpression": + return finish(t.arrayExpression(path.get("elements").map(function (elemPath) { + return explodeViaTempVar(null, elemPath); + }))); - // count buffered requests - this.bufferedRequestCount = 0; + case "SequenceExpression": + var lastIndex = expr.expressions.length - 1; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + path.get("expressions").forEach(function (exprPath) { + if (exprPath.key === lastIndex) { + result = self.explodeExpression(exprPath, ignoreResult); + } else { + self.explodeExpression(exprPath, true); + } + }); -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; + return result; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - } catch (_) {} -})(); + case "LogicalExpression": + after = loc(); -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; + if (!ignoreResult) { + result = self.makeTempVar(); + } - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + var left = explodeViaTempVar(result, path.get("left")); -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); + if (expr.operator === "&&") { + self.jumpIfNot(left, after); + } else { + _assert2.default.strictEqual(expr.operator, "||"); + self.jumpIf(left, after); + } - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + explodeViaTempVar(result, path.get("right"), ignoreResult); - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } + self.mark(after); - this._writableState = new WritableState(options, this); + return result; - // legacy. - this.writable = true; + case "ConditionalExpression": + var elseLoc = loc(); + after = loc(); + var test = self.explodeExpression(path.get("test")); - if (options) { - if (typeof options.write === 'function') this._write = options.write; + self.jumpIfNot(test, elseLoc); - if (typeof options.writev === 'function') this._writev = options.writev; - } + if (!ignoreResult) { + result = self.makeTempVar(); + } - Stream.call(this); -} + explodeViaTempVar(result, path.get("consequent"), ignoreResult); + self.jump(after); -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; + self.mark(elseLoc); + explodeViaTempVar(result, path.get("alternate"), ignoreResult); -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} + self.mark(after); -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; - } - return valid; -} + return result; -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + case "UnaryExpression": + return finish(t.unaryExpression(expr.operator, + // Can't (and don't need to) break up the syntax of the argument. + // Think about delete a[b]. + self.explodeExpression(path.get("argument")), !!expr.prefix)); - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + case "BinaryExpression": + return finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))); - if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + case "AssignmentExpression": + return finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))); - if (typeof cb !== 'function') cb = nop; + case "UpdateExpression": + return finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)); - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } + case "YieldExpression": + after = loc(); + var arg = expr.argument && self.explodeExpression(path.get("argument")); - return ret; -}; + if (arg && expr.delegate) { + var _result = self.makeTempVar(); -Writable.prototype.cork = function () { - var state = this._writableState; + self.emit(t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after]))); - state.corked++; -}; + self.mark(after); -Writable.prototype.uncork = function () { - var state = this._writableState; + return _result; + } - if (state.corked) { - state.corked--; + self.emitAssign(self.contextProperty("next"), after); + self.emit(t.returnStatement(arg || null)); + self.mark(after); - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + return self.contextProperty("sent"); + + default: + throw new Error("unknown Expression of type " + (0, _stringify2.default)(expr.type)); } }; +},{"./leap":583,"./meta":584,"./util":586,"assert":2,"babel-runtime/core-js/json/stringify":128,"babel-types":183}],581:[function(require,module,exports){ +"use strict"; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +var _keys = require("babel-runtime/core-js/object/keys"); -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = bufferShim.from(chunk, encoding); - } - return chunk; -} +var _keys2 = _interopRequireDefault(_keys); -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); +var _babelTypes = require("babel-types"); - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; +var t = _interopRequireWildcard(_babelTypes); - state.length += len; +var _util = require("./util"); - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; +var util = _interopRequireWildcard(_util); - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - return ret; -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); +var hasOwn = Object.prototype.hasOwnProperty; - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} +// The hoist function takes a FunctionExpression or FunctionDeclaration +// and replaces any Declaration nodes in its body with assignments, then +// returns a VariableDeclaration containing just the names of the removed +// declarations. +exports.hoist = function (funPath) { + t.assertFunction(funPath.node); -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + var vars = {}; -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + function varDeclToExpr(vdec, includeIdentifiers) { + t.assertVariableDeclaration(vdec); + // TODO assert.equal(vdec.kind, "var"); + var exprs = []; - onwriteStateUpdate(state); + vdec.declarations.forEach(function (dec) { + // Note: We duplicate 'dec.id' here to ensure that the variable declaration IDs don't + // have the same 'loc' value, since that can make sourcemaps and retainLines behave poorly. + vars[dec.id.name] = t.identifier(dec.id.name); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + if (dec.init) { + exprs.push(t.assignmentExpression("=", dec.id, dec.init)); + } else if (includeIdentifiers) { + exprs.push(dec.id); + } + }); - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + if (exprs.length === 0) return null; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } + if (exprs.length === 1) return exprs[0]; + + return t.sequenceExpression(exprs); } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + funPath.get("body").traverse({ + VariableDeclaration: { + exit: function exit(path) { + var expr = varDeclToExpr(path.node, false); + if (expr === null) { + path.remove(); + } else { + // We don't need to traverse this expression any further because + // there can't be any new declarations inside an expression. + util.replaceWithOrRemove(path, t.expressionStatement(expr)); + } -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} + // Since the original node has been either removed or replaced, + // avoid traversing it any further. + path.skip(); + } + }, -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + ForStatement: function ForStatement(path) { + var init = path.node.init; + if (t.isVariableDeclaration(init)) { + util.replaceWithOrRemove(path.get("init"), varDeclToExpr(init, false)); + } + }, - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + ForXStatement: function ForXStatement(path) { + var left = path.get("left"); + if (left.isVariableDeclaration()) { + util.replaceWithOrRemove(left, varDeclToExpr(left.node, true)); + } + }, - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } + FunctionDeclaration: function FunctionDeclaration(path) { + var node = path.node; + vars[node.id.name] = node.id; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + var assignment = t.expressionStatement(t.assignmentExpression("=", node.id, t.functionExpression(node.id, node.params, node.body, node.generator, node.expression))); - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + if (path.parentPath.isBlockStatement()) { + // Insert the assignment form before the first statement in the + // enclosing block. + path.parentPath.unshiftContainer("body", assignment); - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; + // Remove the function declaration now that we've inserted the + // equivalent assignment form at the beginning of the block. + path.remove(); + } else { + // If the parent node is not a block statement, then we can just + // replace the declaration with the equivalent assignment form + // without worrying about hoisting it. + util.replaceWithOrRemove(path, assignment); } - } - if (entry === null) state.lastBufferedRequest = null; - } + // Don't hoist variables out of inner functions. + path.skip(); + }, - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + FunctionExpression: function FunctionExpression(path) { + // Don't descend into nested function expressions. + path.skip(); + } + }); -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + var paramNames = {}; + funPath.get("params").forEach(function (paramPath) { + var param = paramPath.node; + if (t.isIdentifier(param)) { + paramNames[param.name] = param; + } else { + // Variables declared by destructuring parameter patterns will be + // harmlessly re-declared. + } + }); -Writable.prototype._writev = null; + var declarations = []; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + (0, _keys2.default)(vars).forEach(function (name) { + if (!hasOwn.call(paramNames, name)) { + declarations.push(t.variableDeclarator(vars[name], null)); + } + }); - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if (declarations.length === 0) { + return null; // Be sure to handle this case! } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + return t.variableDeclaration("var", declarations); +}; +},{"./util":586,"babel-runtime/core-js/object/keys":134,"babel-types":183}],582:[function(require,module,exports){ +"use strict"; - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } +exports.__esModule = true; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); +exports.default = function () { + return require("./visit"); }; +},{"./visit":587}],583:[function(require,module,exports){ +"use strict"; -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} +var _assert = require("assert"); -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; -} +var _assert2 = _interopRequireDefault(_assert); -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} +var _babelTypes = require("babel-types"); -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +var t = _interopRequireWildcard(_babelTypes); - this.next = null; - this.entry = null; +var _util = require("util"); - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; -} -}).call(this,require('_process')) -},{"./_stream_duplex":807,"_process":803,"buffer":793,"buffer-shims":794,"core-util-is":795,"events":796,"inherits":798,"process-nextick-args":802,"util-deprecate":819}],812:[function(require,module,exports){ -'use strict'; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var Buffer = require('buffer').Buffer; -/**/ -var bufferShim = require('buffer-shims'); -/**/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = BufferList; +function Entry() { + _assert2.default.ok(this instanceof Entry); +} /** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ -function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; +function FunctionEntry(returnLoc) { + Entry.call(this); + t.assertLiteral(returnLoc); + this.returnLoc = returnLoc; } -BufferList.prototype.push = function (v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; -}; - -BufferList.prototype.unshift = function (v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; -}; - -BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; -}; +(0, _util.inherits)(FunctionEntry, Entry); +exports.FunctionEntry = FunctionEntry; -BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; -}; +function LoopEntry(breakLoc, continueLoc, label) { + Entry.call(this); -BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; -}; + t.assertLiteral(breakLoc); + t.assertLiteral(continueLoc); -BufferList.prototype.concat = function (n) { - if (this.length === 0) return bufferShim.alloc(0); - if (this.length === 1) return this.head.data; - var ret = bufferShim.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; + if (label) { + t.assertIdentifier(label); + } else { + label = null; } - return ret; -}; -},{"buffer":793,"buffer-shims":794}],813:[function(require,module,exports){ -module.exports = require("./lib/_stream_passthrough.js") - -},{"./lib/_stream_passthrough.js":808}],814:[function(require,module,exports){ -(function (process){ -var Stream = (function (){ - try { - return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify - } catch(_){} -}()); -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = Stream || exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); -if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; + this.breakLoc = breakLoc; + this.continueLoc = continueLoc; + this.label = label; } -}).call(this,require('_process')) -},{"./lib/_stream_duplex.js":807,"./lib/_stream_passthrough.js":808,"./lib/_stream_readable.js":809,"./lib/_stream_transform.js":810,"./lib/_stream_writable.js":811,"_process":803}],815:[function(require,module,exports){ -module.exports = require("./lib/_stream_transform.js") +(0, _util.inherits)(LoopEntry, Entry); +exports.LoopEntry = LoopEntry; -},{"./lib/_stream_transform.js":810}],816:[function(require,module,exports){ -module.exports = require("./lib/_stream_writable.js") +function SwitchEntry(breakLoc) { + Entry.call(this); + t.assertLiteral(breakLoc); + this.breakLoc = breakLoc; +} -},{"./lib/_stream_writable.js":811}],817:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +(0, _util.inherits)(SwitchEntry, Entry); +exports.SwitchEntry = SwitchEntry; -var Buffer = require('buffer').Buffer; +function TryEntry(firstLoc, catchEntry, finallyEntry) { + Entry.call(this); -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } + t.assertLiteral(firstLoc); + if (catchEntry) { + _assert2.default.ok(catchEntry instanceof CatchEntry); + } else { + catchEntry = null; + } -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); + if (finallyEntry) { + _assert2.default.ok(finallyEntry instanceof FinallyEntry); + } else { + finallyEntry = null; } + + // Have to have one or the other (or both). + _assert2.default.ok(catchEntry || finallyEntry); + + this.firstLoc = firstLoc; + this.catchEntry = catchEntry; + this.finallyEntry = finallyEntry; } -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } +(0, _util.inherits)(TryEntry, Entry); +exports.TryEntry = TryEntry; - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; +function CatchEntry(firstLoc, paramId) { + Entry.call(this); + t.assertLiteral(firstLoc); + t.assertIdentifier(paramId); -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + this.firstLoc = firstLoc; + this.paramId = paramId; +} - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } +(0, _util.inherits)(CatchEntry, Entry); +exports.CatchEntry = CatchEntry; - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); +function FinallyEntry(firstLoc, afterLoc) { + Entry.call(this); + t.assertLiteral(firstLoc); + t.assertLiteral(afterLoc); + this.firstLoc = firstLoc; + this.afterLoc = afterLoc; +} - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } +(0, _util.inherits)(FinallyEntry, Entry); +exports.FinallyEntry = FinallyEntry; - charStr += buffer.toString(this.encoding, 0, end); +function LabeledEntry(breakLoc, label) { + Entry.call(this); - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + t.assertLiteral(breakLoc); + t.assertIdentifier(label); - // or just emit the charStr - return charStr; -}; + this.breakLoc = breakLoc; + this.label = label; +} -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; +(0, _util.inherits)(LabeledEntry, Entry); +exports.LabeledEntry = LabeledEntry; - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; +function LeapManager(emitter) { + _assert2.default.ok(this instanceof LeapManager); - // See http://en.wikipedia.org/wiki/UTF-8#Description + var Emitter = require("./emit").Emitter; + _assert2.default.ok(emitter instanceof Emitter); - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + this.emitter = emitter; + this.entryStack = [new FunctionEntry(emitter.finalLoc)]; +} - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } +var LMp = LeapManager.prototype; +exports.LeapManager = LeapManager; - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } +LMp.withEntry = function (entry, callback) { + _assert2.default.ok(entry instanceof Entry); + this.entryStack.push(entry); + try { + callback.call(this.emitter); + } finally { + var popped = this.entryStack.pop(); + _assert2.default.strictEqual(popped, entry); } - this.charReceived = i; }; -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); +LMp._findLeapLocation = function (property, label) { + for (var i = this.entryStack.length - 1; i >= 0; --i) { + var entry = this.entryStack[i]; + var loc = entry[property]; + if (loc) { + if (label) { + if (entry.label && entry.label.name === label.name) { + return loc; + } + } else if (entry instanceof LabeledEntry) { + // Ignore LabeledEntry entries unless we are actually breaking to + // a label. + } else { + return loc; + } + } } - return res; + return null; }; -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} +LMp.getBreakLoc = function (label) { + return this._findLeapLocation("breakLoc", label); +}; -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} +LMp.getContinueLoc = function (label) { + return this._findLeapLocation("continueLoc", label); +}; +},{"./emit":580,"assert":2,"babel-types":183,"util":36}],584:[function(require,module,exports){ +"use strict"; -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} +var _assert = require("assert"); -},{"buffer":793}],818:[function(require,module,exports){ -exports.isatty = function () { return false; }; +var _assert2 = _interopRequireDefault(_assert); -function ReadStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.ReadStream = ReadStream; +var _babelTypes = require("babel-types"); -function WriteStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.WriteStream = WriteStream; +var t = _interopRequireWildcard(_babelTypes); -},{}],819:[function(require,module,exports){ -(function (global){ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -/** - * Module exports. - */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = deprecate; +var m = require("private").makeAccessor(); /** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ +var hasOwn = Object.prototype.hasOwnProperty; -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } +function makePredicate(propertyName, knownTypes) { + function onlyChildren(node) { + t.assertNode(node); - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); + // Assume no side effects until we find out otherwise. + var result = false; + + function check(child) { + if (result) { + // Do nothing. + } else if (Array.isArray(child)) { + child.some(check); + } else if (t.isNode(child)) { + _assert2.default.strictEqual(result, false); + result = predicate(child); } - warned = true; + return result; } - return fn.apply(this, arguments); - } - - return deprecated; -} -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ + var keys = t.VISITOR_KEYS[node.type]; + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var child = node[key]; + check(child); + } + } -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; + return result; } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],820:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],821:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + function predicate(node) { + t.assertNode(node); -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + var meta = m(node); + if (hasOwn.call(meta, propertyName)) return meta[propertyName]; - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; + // Certain types are "opaque," which means they have no side + // effects or leaps and we don't care about their subexpressions. + if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; + if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; + return meta[propertyName] = onlyChildren(node); } - if (process.noDeprecation === true) { - return fn; - } + predicate.onlyChildren = onlyChildren; - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + return predicate; +} - return deprecated; +var opaqueTypes = { + FunctionExpression: true, + ArrowFunctionExpression: true }; - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; +// These types potentially have side effects regardless of what side +// effects their subexpressions have. +var sideEffectTypes = { + CallExpression: true, // Anything could happen! + ForInStatement: true, // Modifies the key variable. + UnaryExpression: true, // Think delete. + BinaryExpression: true, // Might invoke .toString() or .valueOf(). + AssignmentExpression: true, // Side-effecting by definition. + UpdateExpression: true, // Updates are essentially assignments. + NewExpression: true // Similar to CallExpression. }; +// These types are the direct cause of all leaps in control flow. +var leapTypes = { + YieldExpression: true, + BreakStatement: true, + ContinueStatement: true, + ReturnStatement: true, + ThrowStatement: true +}; -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); +// All leap types are also side effect types. +for (var type in leapTypes) { + if (hasOwn.call(leapTypes, type)) { + sideEffectTypes[type] = leapTypes[type]; } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); } -exports.inspect = inspect; +exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); +exports.containsLeap = makePredicate("containsLeap", leapTypes); +},{"assert":2,"babel-types":183,"private":548}],585:[function(require,module,exports){ +"use strict"; -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; +exports.__esModule = true; +exports.default = replaceShorthandObjectMethod; -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; +var _babelTypes = require("babel-types"); +var t = _interopRequireWildcard(_babelTypes); -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; +var _util = require("./util"); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} +var util = _interopRequireWildcard(_util); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function stylizeNoColor(str, styleType) { - return str; -} +// this function converts a shorthand object generator method into a normal +// (non-shorthand) object property which is a generator function expression. for +// example, this: +// +// var foo = { +// *bar(baz) { return 5; } +// } +// +// should be replaced with: +// +// var foo = { +// bar: function*(baz) { return 5; } +// } +// +// to do this, it clones the parameter array and the body of the object generator +// method into a new FunctionExpression. +// +// this method can be passed any Function AST node path, and it will return +// either: +// a) the path that was passed in (iff the path did not need to be replaced) or +// b) the path of the new FunctionExpression that was created as a replacement +// (iff the path did need to be replaced) +// +// In either case, though, the caller can count on the fact that the return value +// is a Function AST node path. +// +// If this function is called with an AST node path that is not a Function (or with an +// argument that isn't an AST node path), it will throw an error. +function replaceShorthandObjectMethod(path) { + if (!path.node || !t.isFunction(path.node)) { + throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); + } + // this function only replaces shorthand object methods (called ObjectMethod + // in Babel-speak). + if (!t.isObjectMethod(path.node)) { + return path; + } -function arrayToHash(array) { - var hash = {}; + // this function only replaces generators. + if (!path.node.generator) { + return path; + } - array.forEach(function(val, idx) { - hash[val] = true; + var parameters = path.node.params.map(function (param) { + return t.cloneDeep(param); }); - return hash; + var functionExpression = t.functionExpression(null, // id + parameters, // params + t.cloneDeep(path.node.body), // body + path.node.generator, path.node.async); + + util.replaceWithOrRemove(path, t.objectProperty(t.cloneDeep(path.node.key), // key + functionExpression, //value + path.node.computed, // computed + false // shorthand + )); + + // path now refers to the ObjectProperty AST node path, but we want to return a + // Function AST node path for the function expression we created. we know that + // the FunctionExpression we just created is the value of the ObjectProperty, + // so return the "value" path off of this path. + return path.get("value"); } +},{"./util":586,"babel-types":183}],586:[function(require,module,exports){ +"use strict"; +exports.__esModule = true; +exports.runtimeProperty = runtimeProperty; +exports.isReference = isReference; +exports.replaceWithOrRemove = replaceWithOrRemove; -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } +var _babelTypes = require("babel-types"); - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } +var t = _interopRequireWildcard(_babelTypes); - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } +function runtimeProperty(state, name) { + return t.memberExpression(state.get("regeneratorRuntime"), t.identifier(name), false); +} /** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } +function isReference(path) { + return path.isReferenced() || path.parentPath.isAssignmentExpression({ left: path.node }); +} - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } +function replaceWithOrRemove(path, replacement) { + if (replacement) { + path.replaceWith(replacement); + } else { + path.remove(); } +} +},{"babel-types":183}],587:[function(require,module,exports){ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ - var base = '', array = false, braces = ['{', '}']; +"use strict"; - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } +var _assert = require("assert"); - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } +var _assert2 = _interopRequireDefault(_assert); - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } +var _babelTypes = require("babel-types"); - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } +var t = _interopRequireWildcard(_babelTypes); - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } +var _hoist = require("./hoist"); - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } +var _emit = require("./emit"); - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } +var _replaceShorthandObjectMethod = require("./replaceShorthandObjectMethod"); - ctx.seen.push(value); +var _replaceShorthandObjectMethod2 = _interopRequireDefault(_replaceShorthandObjectMethod); - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } +var _util = require("./util"); - ctx.seen.pop(); +var util = _interopRequireWildcard(_util); - return reduceToSingleString(output, base, braces); -} +var _private = require("private"); +var _private2 = _interopRequireDefault(_private); -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} +var getMarkInfo = _private2.default.makeAccessor(); +exports.name = "regenerator-transform"; -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } +exports.pre = function (file) { + this.setDynamic("regeneratorRuntime", function () { + return file.addImport("regenerator-runtime", "*", "regeneratorRuntime"); }); - return output; -} +}; +exports.visitor = { + Function: { + exit: function exit(path, state) { + var node = path.node; -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); + if (node.generator) { + if (node.async) { + // Async generator + if (state.opts.asyncGenerators === false) return; + } else { + // Plain generator + if (state.opts.generators === false) return; + } + } else if (node.async) { + // Async function + if (state.opts.async === false) return; } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); + // Not a generator or async function. + return; } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); + + // if this is an ObjectMethod, we need to convert it to an ObjectProperty + path = (0, _replaceShorthandObjectMethod2.default)(path); + node = path.node; + + var contextId = path.scope.generateUidIdentifier("context"); + var argsId = path.scope.generateUidIdentifier("args"); + + path.ensureBlock(); + var bodyBlockPath = path.get("body"); + + if (node.async) { + bodyBlockPath.traverse(awaitVisitor, { parentState: state }); + } + + bodyBlockPath.traverse(functionSentVisitor, { + context: contextId + }); + + var outerBody = []; + var innerBody = []; + + bodyBlockPath.get("body").forEach(function (childPath) { + var node = childPath.node; + if (t.isExpressionStatement(node) && t.isStringLiteral(node.expression)) { + // Babylon represents directives like "use strict" as elements + // of a bodyBlockPath.node.directives array, but they could just + // as easily be represented (by other parsers) as traditional + // string-literal-valued expression statements, so we need to + // handle that here. (#248) + outerBody.push(node); + } else if (node && node._blockHoist != null) { + outerBody.push(node); } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); + innerBody.push(node); } + }); + + if (outerBody.length > 0) { + // Only replace the inner body if we actually hoisted any statements + // to the outer body. + bodyBlockPath.node.body = innerBody; } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - return name + ': ' + str; -} + var outerFnExpr = getOuterFnExpr(path, state); + // Note that getOuterFnExpr has the side-effect of ensuring that the + // function has a name (so node.id will always be an Identifier), even + // if a temporary name has to be synthesized. + t.assertIdentifier(node.id); + var innerFnId = t.identifier(node.id.name + "$"); + // Turn all declarations into vars, and replace the original + // declarations with equivalent assignment expressions. + var vars = (0, _hoist.hoist)(path); -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + var didRenameArguments = renameArguments(path, argsId); + if (didRenameArguments) { + vars = vars || t.variableDeclaration("var", []); + var argumentIdentifier = t.identifier("arguments"); + // we need to do this as otherwise arguments in arrow functions gets hoisted + argumentIdentifier._shadowedFunctionLiteral = path; + vars.declarations.push(t.variableDeclarator(argsId, argumentIdentifier)); + } - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + var emitter = new _emit.Emitter(contextId, state); + emitter.explode(path.get("body")); - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} + if (vars && vars.declarations.length > 0) { + outerBody.push(vars); + } + var wrapArgs = [emitter.getContextFunction(innerFnId), + // Async functions that are not generators don't care about the + // outer function because they don't need it to be marked and don't + // inherit from its .prototype. + node.generator ? outerFnExpr : t.nullLiteral(), t.thisExpression()]; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; + var tryLocsList = emitter.getTryLocsList(); + if (tryLocsList) { + wrapArgs.push(tryLocsList); + } -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + var wrapCall = t.callExpression(util.runtimeProperty(state, node.async ? "async" : "wrap"), wrapArgs); -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + outerBody.push(t.returnStatement(wrapCall)); + node.body = t.blockStatement(outerBody); -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + var oldDirectives = bodyBlockPath.node.directives; + if (oldDirectives) { + // Babylon represents directives like "use strict" as elements of + // a bodyBlockPath.node.directives array. (#248) + node.body.directives = oldDirectives; + } -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + var wasGeneratorFunction = node.generator; + if (wasGeneratorFunction) { + node.generator = false; + } -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + if (node.async) { + node.async = false; + } -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + if (wasGeneratorFunction && t.isExpression(node)) { + util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty(state, "mark"), [node])); + path.addComment("leading", "#__PURE__"); + } -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + // Generators are processed in 'exit' handlers so that regenerator only has to run on + // an ES5 AST, but that means traversal will not pick up newly inserted references + // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue. + path.requeue(); + } + } +}; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +// Given a NodePath for a Function, return an Expression node that can be +// used to refer reliably to the function object from inside the function. +// This expression is essentially a replacement for arguments.callee, with +// the key advantage that it works in strict mode. +function getOuterFnExpr(funPath, state) { + var node = funPath.node; + t.assertFunction(node); -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + if (!node.id) { + // Default-exported function declarations, and function expressions may not + // have a name to reference, so we explicitly add one. + node.id = funPath.scope.parent.generateUidIdentifier("callee"); + } -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + if (node.generator && // Non-generator functions don't need to be marked. + t.isFunctionDeclaration(node)) { + // Return the identifier returned by runtime.mark(). + return getMarkedFunctionId(funPath, state); + } -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + return node.id; } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +function getMarkedFunctionId(funPath, state) { + var node = funPath.node; + t.assertIdentifier(node.id); -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + var blockPath = funPath.findParent(function (path) { + return path.isProgram() || path.isBlockStatement(); + }); -exports.isBuffer = require('./support/isBuffer'); + if (!blockPath) { + return node.id; + } -function objectToString(o) { - return Object.prototype.toString.call(o); -} + var block = blockPath.node; + _assert2.default.ok(Array.isArray(block.body)); + + var info = getMarkInfo(block); + if (!info.decl) { + info.decl = t.variableDeclaration("var", []); + blockPath.unshiftContainer("body", info.decl); + info.declPath = blockPath.get("body.0"); + } + _assert2.default.strictEqual(info.declPath.node, info.decl); -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); + // Get a new unique identifier for our marked variable. + var markedId = blockPath.scope.generateUidIdentifier("marked"); + var markCallExp = t.callExpression(util.runtimeProperty(state, "mark"), [node.id]); + + var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1; + + var markCallExpPath = info.declPath.get("declarations." + index + ".init"); + + _assert2.default.strictEqual(markCallExpPath.node, markCallExp); + + markCallExpPath.addComment("leading", "#__PURE__"); + + return markedId; } +function renameArguments(funcPath, argsId) { + var state = { + didRenameArguments: false, + argsId: argsId + }; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + funcPath.traverse(argumentsVisitor, state); -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); + // If the traversal replaced any arguments references, then we need to + // alias the outer function's arguments binding (be it the implicit + // arguments object or some other parameter or variable) to the variable + // named by argsId. + return state.didRenameArguments; } +var argumentsVisitor = { + "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { + path.skip(); + }, -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + Identifier: function Identifier(path, state) { + if (path.node.name === "arguments" && util.isReference(path)) { + util.replaceWithOrRemove(path, state.argsId); + state.didRenameArguments = true; + } + } }; +var functionSentVisitor = { + MetaProperty: function MetaProperty(path) { + var node = path.node; -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; + if (node.meta.name === "function" && node.property.name === "sent") { + util.replaceWithOrRemove(path, t.memberExpression(this.context, t.identifier("_sent"))); + } } - return origin; }; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +var awaitVisitor = { + Function: function Function(path) { + path.skip(); // Don't descend into nested function scopes. + }, -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":820,"_process":803,"inherits":798}]},{},[3])(3) + AwaitExpression: function AwaitExpression(path) { + // Convert await expressions to yield expressions. + var argument = path.node.argument; + + // Transforming `await x` to `yield regeneratorRuntime.awrap(x)` + // causes the argument to be wrapped in such a way that the runtime + // can distinguish between awaited and merely yielded values. + util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty(this.parentState, "awrap"), [argument]), false)); + } +}; +},{"./emit":580,"./hoist":581,"./replaceShorthandObjectMethod":585,"./util":586,"assert":2,"babel-types":183,"private":548}]},{},[39])(39) }); \ No newline at end of file diff --git a/main.js b/main.js index a5654dce0..4ad4cdbf0 100644 --- a/main.js +++ b/main.js @@ -44,7 +44,7 @@ function runtime() { regeneratorRuntime = require("regenerator-runtime"); } exports.runtime = runtime; -runtime.path = require.resolve("regenerator-runtime") +runtime.path = "regenerator-runtime/lib/index.js" var cachedRuntimeCode; function getRuntimeCode() { @@ -70,7 +70,7 @@ var getTransformOptions = function (opts) { }); return { - presets: [["regenerator-preset", opts]], + presets: [[require("regenerator-preset"), opts]], parserOpts: { sourceType: "module", allowImportExportEverywhere: true, diff --git a/package.json b/package.json index 50029fb4c..630fb5669 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "main": "main.js", "bin": "bin/regenerator", "scripts": { + "docs:build": "browserify -s regenerator ./main.js > docs/bundle.js", "bootstrap": "lerna bootstrap", "pretest": "lerna run --parallel build", "test": "node test/run.js" @@ -67,7 +68,7 @@ "npm-run-all": "^4.0.2", "promise": "^7.0.4", "rimraf": "^2.6.1", - "rollup": "^0.45.2", + "rollup": "^0.46.2", "rollup-plugin-babel": "^2.7.1", "semver": "^5.0.3", "uglify-js": "^3.0.27" diff --git a/packages/regenerator-preset/index.js b/packages/regenerator-preset/index.js index 31dd08f25..9c50f0299 100644 --- a/packages/regenerator-preset/index.js +++ b/packages/regenerator-preset/index.js @@ -13,11 +13,11 @@ module.exports = { require("babel-plugin-transform-es2015-arrow-functions"), require("babel-plugin-transform-es2015-block-scoping"), require("babel-plugin-transform-es2015-for-of"), - ["regenerator-transform", { globalRuntimeName: globalRuntimeName }] + [require("regenerator-transform"), { globalRuntimeName: globalRuntimeName }] ]; if (modules) { - plugins.push(["babel-plugin-transform-es2015-modules-commonjs", { loose: loose, strict: strict }]); + plugins.push([require("babel-plugin-transform-es2015-modules-commonjs"), { loose: loose, strict: strict }]); } return { diff --git a/packages/regenerator-runtime/package.json b/packages/regenerator-runtime/package.json index a878b23b7..5052d22bc 100644 --- a/packages/regenerator-runtime/package.json +++ b/packages/regenerator-runtime/package.json @@ -26,7 +26,7 @@ "cross-env": "^5.0.1", "npm-run-all": "^4.0.2", "rimraf": "^2.6.1", - "rollup": "^0.45.2", + "rollup": "^0.46.2", "rollup-plugin-babel": "^2.7.1" }, "scripts": {